Easy-to-understand explanation of Python Web application (Django) even for beginners (3) [Application creation / DB setting]

Composition of commentary articles

No. title
1 Easy-to-understand explanation of Python Web application (Django) even for beginners (1) [Environment construction]
2 Easy-to-understand explanation of Python Web application (Django) even for beginners (2) [Project creation]
3 Easy-to-understand explanation of Python Web application (Django) even for beginners (3) [Application creation / DB setting]
4 Easy-to-understand explanation of Python web application (Django) even for beginners (4) [Routing settings / Introduction to MTV design patterns]
5 Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]
6 Easy-to-understand explanation of Python web application (Django) even for beginners (6) [MTV design pattern completion]

Development environment

We will proceed on the premise of a Mac environment.

Check the Python version as follows.

$ python3 --version
Python 3.5.2

Creating an application

This time, we'll start by creating a Django application.

Create an application in your project. Here, we will create a blog following the Django Girls Tutorial.

$ python3 manage.py startapp blog

The directory structure is as follows.

myvenv
├── bin
├── blog
├── db.sqlite3
├── include
├── lib
├── manage.py
├── myapp
└── pyvenv.cfg

After creating the application, first change the configuration file. This is to define the application to use on Django.

Find the code below and add `` `blog``` to the bottom.

myapp/settings.py


# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
)

Creating a model

blogTo use inmodelI will make. modelIs it a convenient object that can store data? You can have a method in this Model`` itself, and you can handle the communication with DB without worrying about SQL etc. thanks to this Model```.

Now let's define Model for `blog.

blog/models.Open py and rewrite it as follows.




#### **`blog/models.py`**
```py

from django.db import models
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title  = models.CharField(max_length=200)
    text   = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

The explanation is a little long here, but the following is an excerpt from the explanation of Django Girls Tutorial only where necessary.

class Post (models.Model): --This line defines this model (this is the object).

  • class is a keyword that indicates that you are defining an object.

Let's define the property:  title、text、created_date、published_date、author First you have to decide on the type of field. text? Numbers? date? Relationships with other objects, such as users

It sounds like you're declaring the type of property you want to use in your model.

As an aside, in Ruby on Rails,

$ rails g model post author title text

Since the migration file was created by declaring like, it seems a little troublesome compared to that.

Now that we have defined the model, we will create a migration file.

$ python3 manage.py makemigrations blog
Migrations for 'blog':
  0001_initial.py:
    - Create model Post

This will allow Django to create a migration file for you to put in your database, so we'll do the migration.

$ python3 manage.py migrate blog
Operations to perform:
  Apply all migrations: blog
Running migrations:
  Rendering model states... DONE
  Applying blog.0001_initial... OK

The `` `Post``` model is now successfully reflected in the DB (SQLite).

DB confirmation

Django allows you to check the model with a GUI via a browser so that even beginners can easily understand it. This seems to be called Django admin.

First, open the blog / admin.py file and modify Django admin for the Post model you just created.

blog/admin.py


from django.contrib import admin
from .models import Post

# Register your models here.
admin.site.register(Post)

This completes the settings.

Start your server and access Django admin (http://127.0.0.1:8000/admin) from your browser.

Server startup


$ python3 manage.py runserver
スクリーンショット 2016-11-11 2.45.57.png

Hopefully you can access a web page like this. However, the login screen is displayed, and you don't remember setting it, right? That should be it, you need to create a separate superuser (site administrator) to log in.

Now let's create `` `superuser```.

Creating superuser


$ python manage.py createsuperuser
Username (leave blank to use 'your_name'): admin
Email address: [email protected] #Set email address individually
Password: #Enter password
Password (again): #Password again
Superuser created successfully.

This completes the creation of `superuser`. Go to Django admin (http://127.0.0.1:8000/admin) again and try logging in.

スクリーンショット 2016-11-11 2.52.04.png

Log in with the `` `superuser``` you created earlier.

スクリーンショット 2016-11-11 2.52.11.png

If you can log in successfully, you can access such a screen. The model name was declared as `Post```, but it is automatically pluralized as `Posts```.

Let's try adding an article by adding Posts on the screen. スクリーンショット 2016-11-11 2.56.16.png

After registering, a new article was created on the DB. スクリーンショット 2016-11-11 3.01.20.png

This completes the DB confirmation. From now on, if you want to check the DB, ask Django admin to help you.

Now you can set the model, reflect it in the DB, and check it.

Next time, I will create an original template and go to the point where I can edit the View side.

Next commentary article

Explanation of Python Web application (Django) in an easy-to-understand manner even for beginners (4) [Routing settings / Introduction to MTV design patterns]

References

bonus

We are waiting for you to follow us!

Service introduction Please feel free to contact us if you are interested in "Kikagaku", a one-on-one tutoring service for machine learning that allows you to learn "math → programming → web applications" all at once.

Recommended Posts

Easy-to-understand explanation of Python Web application (Django) even for beginners (3) [Application creation / DB setting]
Easy-to-understand explanation of Python Web application (Django) even for beginners (2) [Project creation]
Easy-to-understand explanation of Python Web application (Django) even for beginners (1) [Environment construction]
Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]
Easy-to-understand explanation of Python web application (Django) even for beginners (6) [MTV design pattern completion]
Easy-to-understand explanation of Python web application (Django) even for beginners (4) [Routing settings / Introduction to MTV design patterns]
Web application creation with Django
[For beginners] Summary of standard input in Python (with explanation)
Beginners use Python for web scraping (1)
Beginners use Python for web scraping (4) ―― 1
[Python] Minutes of study meeting for beginners (7/15)
Beginners use Python for web scraping (4) -3 GCE VM instance creation and scraping on VM
[Python] Web application design for machine learning
WebApi creation with Python (CRUD creation) For beginners
Explanation of creating an application for displaying images and drawing with Python
[For beginners] Try web scraping with Python
WEB application development using Django [Admin screen creation]
Django tutorial summary for beginners by beginners ① (project creation ~)
[Python] Web application from 0! Hands-on (1) -Design, DB construction-
Easy understanding of Python for & arrays (for super beginners)
[Python] Beginners troubleshoot while studying Django web applications
Basic story of inheritance in Python (for beginners)
Beginners can use Python for web scraping (1) Improved version
(Python) Try to develop a web application using Django
Summary of pre-processing practices for Python beginners (Pandas dataframe)
Web application made with Python3.4 + Django (Part.1 Environment construction)
[Linux] Basics of authority setting by chmod for beginners
Explanation of NoReverseMatch error in "python django super introduction"
Beginners use Python for web scraping (4) --2 Scraping on Cloud Shell
Django python web framework
Application of Python 3 vars
OpenCV for Python beginners
[For beginners] Basics of Python explained by Java Gold Part 2
Python x Flask x Tensorflow.Keras Web application for predicting cat breeds 2
■ Kaggle Practice for Beginners --Introduction of Python --by Google Colaboratory
[Python] The biggest weakness / disadvantage of Google Colaboratory [For beginners]
[Python] Introduction to graph creation using coronavirus data [For beginners]
(For beginners) Try creating a simple web API with Django
[For beginners] Basics of Python explained by Java Gold Part 1