[PYTHON] I want to create a lunch database [EP1] Django study for the first time

I want to make a web application

That's why I decided to study Django in Python. Django seems to be a Python web framework. What is a framework? That's what it looks like, but the official website says "Django makes it easier to build better Web apps more quickly and with less code." It seems that Youtube, Dropbox, and Instagram are also made with Django in famous places. Wow ...

Note) This article is "I tried a tutorial on the official Django project".

Environment

First of all, from the environment construction to the rabbit and the corner

I think you can start Django if you keep these three points in check. In my case on Windows 10 1909

I prepared it in. Below are the links that I referred to during setup.

Reference link [Mastering Django the fastest part1](https://qiita.com/gragragrao/items/373057783ba8856124f3) [django official documentation-tutorial](https://docs.djangoproject.com/ja/3.0/intro/tutorial01/) [Python environment construction (Anaconda + VSCode) @ Windows10 [January 2020 version]](https://qiita.com/manamana/items/38e963ce04f24de4bbe4)

First step

After installing Django, I built a virtual environment. As you can see, the step is quite slow. Please forgive me.

Generally, there are many articles about pyenv or venv when building a virtual environment, so when I make it with ʻAnaconda this time It was built with a little confusion. Since the GUI of ʻAnaconda is fairly easy to understand, it is possible to build a virtual environment without typing any honest commands. So it may be easy for beginners to get along with. The following is the setting screen for ʻAnaconda` Navigator.

    1. Click Enviroment in the menu on the left to enter the virtual environment setting screen 2020-07-30_LI.jpg
  1. Create a new environment The name should be easy to understand and you can decide it freely. (I named it Django, but maybe there's a namespace conflict) 2020-07-30 (1)_LI.jpg

    1. Once you've created a virtual environment for Django, select it, find the libraries you need in the search window, and put them in your virtual environment. 2020-07-30 (2)_LI.jpg

Let's make a project

Once the virtual environment is created, start the virtual environment from ʻAnaconda` Prompt, enter the working directory, and create a project.

cmd


(base)C:\User>conda activate Django
(Django)C:\User>django-admin startproject mysite

This will create a mysite directory in which the project and starter kit-like code will be created automatically.

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Since the tutorial has exactly the same explanation, I will omit it in detail, but the basic movement is controlled by manage.py, and ʻurls.py` is responsible for routing within the site. Detailed article ⇒ Explanation of the mechanism of code for django-django (framework) in an easy-to-understand manner [Thoroughly chew]

First, let's run the web server!

cmd


(Django)C:\User\mysite>python manage.py runserver

You have successfully set up a server. As those who understand it will understand, the one set up here is a so-called trial server on the development server. Actually, ʻApache` etc. is put in and operated.

So let's check the development server we set up. If you enter 127.0.0.1:8000 in your browser 2020-08-01.png It's okay if you see a screen with a rocket like this flying. 127.0.0.1:8000 represents your own port 8000 because 127.0.0.1 is the loopback address, and this page shows that django is running on port 8000 in your computer. I will.

Make a poll application

In the tutorial, we will start creating a voting application here. First, create a template for your application.

cmd


(Django)C:\User\mysite>python startapp polls

This will create a directory named polls, which already contains the basic scripts for building your application.

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

This script called views.py controls the appearance of the page. Now, let's play with this views.py a little to change the appearance.

From here, we will edit using vscode.

In vscode, I have included Japanese localization and Python extensions as plugins, and Pylance, which I introduced because it was a hot topic recently.

When you open the vscode screen, it looks like this. 2020-08-02 (1)_LI.jpg

Add the following script to views.py.


from django.http import HttpResponse

def index(request):
#I put in the appropriate words
    return HttpResponse("Hello!")

The content of HttpResponse of return is different from the tutorial, but since this is a display message, I put in whatever I like.

Then set the routing in ʻurls.py` to display this function.

polls/urls.py


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

I'm calling views.py to put the path to views.index in the list of ʻurl patterns. This alone cannot call views.indexyet. You need to show the routing to polls inmysite / urls.py`.

mysite/urls.py


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

admin is originally included. Added path to polls. ʻInclude is a function needed to pass the action to the lower ʻurls.py. The exception is ʻadmin.site.urls. You can now look up views.index on 127.0.0.1:8000/polls`.

Reference about URL dispatch ⇒ Study of DJango (1)

Let's check it immediately. 2020-08-02 (3).png

It's pretty lonely, but it feels good because the response is as per the code.

Database settings

Set the database to be used in mysite / setting.py. Thankfully Python comes standard with a small database called SQLite. These places also show the philosophy of Python's battery attachment.

cmd


(Django) C:\User\mysite>python manage.py migrate

This completes the database table creation. I'm surprised that it's too ridiculous, but is this a good thing about Django? When using a database other than SQLite, a separate setting in setting.py is required.

Creating a model

Create the core model of the polls application.

polls/models.py


from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

As you can see from the code, we have defined two subclasses of the class models.Model, Question and Choice. In addition, the attribute is set to Field. I haven't caught up with Field yet. I will devote myself. models.ForeignKey is the one who goes to get the external key. I'm sorry.

Enable the model

After creating the model, the next step is to enable the model in setting.py so that it can be referenced.

mysite/setting.py


INSTALLED_APPS = [
    'polls.apps.PollsConfig', #Add this line
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

By the way, what is polls.apps.PollsConfig? It was this ↓

polls/apps.py


from django.apps import AppConfig

#I'm calling this.
class PollsConfig(AppConfig):
    name = 'polls'

And when you finish setting to setting.py,

cmd


(Django) C:\User\mysite>python manage.py makemigrations polls

I was able to save the model changes by doing makemigrations . After that, it seems that you can go with migrate.

It's getting longer, so I'd like to cut it once here. Thank you very much. If you notice a mistake, correct it accordingly.

Recommended Posts

I want to create a lunch database [EP1] Django study for the first time
I want to create a lunch database [EP1-4] Django study for the first time
I want to create a Dockerfile for the time being.
[Hi Py (Part 1)] I want to make something for the time being, so first set a goal.
I want to move selenium for the time being [for mac]
Start Django for the first time
I want to record the execution time and keep a log.
I want to create a system to prevent forgetting to tighten the key 1
For the time being, I want to convert files with ffmpeg !!
I tried tensorflow for the first time
I tried to create serverless batch processing for the first time with DynamoDB and Step Functions
For the first time in Numpy, I will update it from time to time
Python: I want to measure the processing time of a function neatly
I tried using scrapy for the first time
How to use MkDocs for the first time
I want to easily create a Noise Model
I want to create a window in Python
I tried python programming for the first time.
I tried Mind Meld for the first time
I want to create a plug-in type implementation
I want to upload a Django app to heroku
Try posting to Qiita for the first time
I want to create a nice Python development environment for my new Mac
I want to make a music player and file music at the same time
I want to add silence to the beginning of a wav file for 1 second
Let's display a simple template that is ideal for Django for the first time
GTUG Girls + PyLadiesTokyo Meetup I went to machine learning for the first time
Create a command to search for similar compounds from the target database with RDKit and check the processing time
I tried to create a table only with Django
What I got into Python for the first time
I tried Python on Mac for the first time.
I want to scroll the Django shift table, but ...
Register a task in cron for the first time
I tried python on heroku for the first time
For the first time, I learned about Unix (Linux).
I want to manually create a legend with matplotlib
AI Gaming I tried it for the first time
I made a command to wait for Django to start until the DB is ready
It's okay to participate for the first time! A hackathon starter kit that you want to prepare "before" participating in the hackathon!
Kaggle for the first time (kaggle ①)
Kaguru for the first time
[TensorFlow] I want to master the indexing for Ragged Tensor
I want to make a blog editor with django admin
A study method for beginners to learn time series analysis
Summary of stumbling blocks in Django for the first time
I tried the Google Cloud Vision API for the first time
I tried to create a bot for PES event notification
I want to use the Ubuntu desktop environment on Android for the time being (Termux version)
I want to use Ubuntu's desktop environment on Android for the time being (UserLAnd version)
A story that I had a hard time trying to create an "app that converts images like paintings" with the first web application
Steps to create a Django project
[Django] What to do if the model you want to create has a large number of fields
Qiskit: I want to create a circuit that creates arbitrary states! !!
I want to create a graph with wavy lines omitted in the middle with matplotlib (I want to manipulate the impression)
[For self-learning] Go2 for the first time
I want to create a histogram and overlay the normal distribution curve on it. matplotlib edition
I made a function to check if the webhook is received in Lambda for the time being
I want to create a pipfile and reflect it in docker
See python for the first time
Raspberry Pi --1 --First time (Connect a temperature sensor to display the temperature)
I want to create a machine learning service without programming! WebAPI