[PYTHON] WEB application development using django-Development 1-

Introduction

Creating a project

--Enable virtual environment

cd C:\Python\env1
. Scripts/activate

--Create a project

django-admin startproject mysite

Mysite is created in the current directory.

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

--Top mysite: You can create it with any name in the root directory. Can be changed. --manage.py ... A command line utility for performing various operations on your Django project. --mysite ・ ・ ・ Package of this project. --mysite / __ init__.py ・ ・ ・ An empty file that this directory is python. --mysite / settings.py ・ ・ ・ Project settings file. --mysite / urls.py ・ ・ ・ Declare the URL. --mysite / asgi.py ・ ・ ・ Entry point of ASGI compatible WEB server that provides the project. --mysite / wsgi.py ・ ・ ・ Entry point of WSGI compatible WEB server for serving the project.

Start development server

--Go to the top mysite directory

cd mysite

--Start the development server

python manage.py runserver

After successful startup, access the URL (http://127.0.0.1:8000/) If there is a page where the rocket is taking off, it is successful.

Polls application creation

--Create an application

python manage.py startapp polls

The application is now created.

View creation

--Create a view

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

Map the URL to call the view.

--Link the url

from django.urls import path
from . import views

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

--Reflect the module description in the root URL

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

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

--Start the server

python manage.py runserver

After starting the server, check the operation. (http: // localhost: 8000 / polls /) You can see that "Hello, world. You're at the polls index." Is displayed.

DataBase settings

--SQLite is set by default in mysite / settings.py. --If you want to use another database, modify this file.

python manage.py migrate

The table is created. Based on the INSTALL_APPS settings, create all the required tables according to the database settings in the mysite / settings.py file.

Creating a model

--The poll application creates two models, Question and Choice.

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)

Each class variable represents a database field in the model.

Enable the model

--I have installed the polls application, so I need to set it. Set polls.apps.PollsConfig.

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

After setting, execute the following command to reflect the Django model.

python manage.py makemigrations polls

When executed, the migration will be created.

Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Question
    - Create model Choice

Created as polls / migrations / 0001_initial.py. Execute the command to manage the database schema automatically.

python manage.py sqlmigrate polls 0001

The sqlmigrate command takes the name of the migration as an argument and returns SQL. The SQL that is not actually reflected and is executed when it is reflected is displayed.

--Reflect the table

python manage.py migrate

migrate is not applied, it supplements the migration and runs against the database. Synchronize.

Try implementing the API provided by Django

--Edit Question and Choice models

import datetime

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

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

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

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

We've added the str () method to the model to make it easier to see in interactive mode and to be used as an object representation in Django's auto-generated admin.

--Launch interactive mode

python manage.py shell

Start a dialogue

>>> from polls.models import Choice, Question
>>> Question.objects.all()
>>> Question.objects.filter(id=1)
>>> Question.objects.filter(question_text__startswith='What')
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
>>> Question.objects.get(pk=1)
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
>>> q.choice_set.create(choice_text='Not much', votes=0)
>>> q.choice_set.create(choice_text='The sky', votes=0)
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
>>> q.choice_set.all()
>>> q.choice_set.count(
>>> Choice.objects.filter(question__pub_date__year=current_year)
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

I am working on model relations.

Create an admin user

--Create user Create a user who can log in to the application's admin site.

python manage.py createsuperuser

Please give the user name appropriately

 Username: Username

Enter your email address

Email address: [email protected]

exampl.com is an example domain name that anyone can use. Once entered, you will be prompted for a password.

Password: **********
Password (again): *********
Superuser created successfully.

This completes the creation of the admin user.

Start development server

--Start the development server If the server is not up, do it

python manage.py runserver

Once started, go to * http: // localhost: 8000 / admin / *. Log in _ Django site admin - Google Chrome 2020_09_21 16_56_20 (2).png

Log in to the management screen

--The following screen will be displayed if you successfully log in by entering the username and password that you set when creating the admin user earlier. Log in _ Django site admin - Google Chrome 2020_09_21 17_02_35 (2).png

Groups and Users are content provided by Django's authentication framework, django.contrib.auth.

Add Poll app so that it can be edited on admin

--Open polls / admin.py and edit it.

The Question object can be displayed by having an admin interface. Tell admin that you have an interface.

from django.contrib import admin
from .models import Question

admin.site.register(Question)

Polls are now displayed on the admin screen. Log in _ Django site admin - Google Chrome 2020_09_21 17_14_02.png

-① Added polls -② When you perform the operation, it is displayed as a history.

Try to operate the management screen

--Press Questions on polls Log in _ Django site admin - Google Chrome 2020_09_21 17_14_28.png

--Press do you like sushi? Log in _ Django site admin - Google Chrome 2020_09_21 17_14_34.png Can be updated in various ways

WEB application development using django-development part 2->>>

Recommended Posts

WEB application development using django-Development 1-
WEB application development using django-Development environment construction-
WEB application development using Django [Django startup]
WEB application development using Django [Application addition]
WEB application development using Django [Model definition]
WEB application development using Django [Initial settings]
WEB application development using Django [Request processing]
WEB application development using Django [Template addition]
Web application using Bottle (1)
WEB application development using Django [Admin screen creation]
Web application development with Flask
Creating a web application using Flask ②
Web application development memo in python
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
Application development using Azure Machine Learning
Try using the web application framework Flask
Application development using SQLite with Django (PTVS)
Web application development in Go language_Hands-on day 1
About Cloud run + Firebase development [Web application development]
(Python) Try to develop a web application using Django
Tech-Circle Let's start application development using machine learning (self-study)
Web application creation with Django
Web scraping using Selenium (Python)
Web scraping using AWS lambda
Web application with Python + Flask ② ③
[Remote development] Control application (Practice 2)
Web application with Python + Flask ④
Text development using Mac services
Web application created with Python + Flask (using VScode) # 1-Virtual environment construction-
About HTTP cache when developing REST API-based web application [using GCP]
The road to web application development is a long way off
Proxy measures when using WEB API
Automatic minimum testing in web development
Authentication using tweepy-User authentication and application authentication (Python)
Creating a voice transcription web application
[Remote development] Video analysis application (Practice 3)
Build a web application with Django
Application development with Docker + Python + Flask
[Remote development] Voice analysis application (Practice 4)
Web application performance measurement tool Funkload ...
Development and deployment of REST API in Python using Falcon Web Framework
How to build an application from the cloud using the Django web framework
I want to make a web application using React and Python flask
Implement a simple application with Python full scratch without using a web framework.