[PYTHON] Django environment construction

■ Generate Django project files

django-admin startproject ‘project name'

Create a project directory in your current directory

■ Initial setting of setting.py in the project (general frame)

LANGUAGE_CODE = ‘ja/'
TIMEZONE = ‘Asia/Tokyo’

■ Build as many Django applications as you need In the directory where manage.py is located (note that the same file name as the project name exists)

python3 manage.py startapp ‘App name'

The db file (sqlite3) and the application file specified above are generated

■ Register the application created by settings.py on the project side

INSTALLED_APPS = [ …

In the inside, write app name + .apps. + App name (starting with capital letters) + Config (Example: App name → myapp)

‘myapp.apps.MyappConfig’

■ Import the include function in urls.py on the project side

from django urls import path, include

Also added that it follows the routing of urls.py in the application generated by urlpatterns of urls.py

urlpatterns = [
    …
    path(‘myapp/‘, include(‘myapp.urls’))
]

path関数の最初の引数は、ルートディレクトリの次のURL(~.com/xxxx/のxxxx) It can be written by specifying the url in the url in the app specified by the following argument

■ Create a urls.py file in your application

from django.urls import path
from . import views

app_name = 'myapp'

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

From. import views is basically OK to write the second line of the django app like this Going to see the views file in the application directory

urlpatterns is routing

■ The contents described in views.py are displayed (sample code below)

from django.http import HttpResponse

def index(request):
    return HttpResponse('Hello World')

■ Actually create a directory called templates and edit in it -Create a templates directory within the django app -Create a directory with the same name as the application name in the templates directory ・ Furthermore, create index.html in it

■ views.py is set to read in templates

from django.shortcuts import render

def index(request):
    context = {
        ’name’ = ‘xxxx'
    }
    return render(request, ‘myapp/index.html’, context)

The first argument of the render function always returns a request

Variables can be passed in curly braces like {{}} in index.html (template method) For variables, prepare a "dictionary" in the context and display the associated value by calling the key as a variable.

■ Editing models.py

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


class Day(models.Model):
    title = models.CharField('title', max_length=200)
    text = models.TextField('Text')
    date = models.DateTimeField('date', default=timezone.now)

To make a model (models.Model) creates a unique class that inherits models.Model

timezone.now

There are many other fields

■ make migrations (notify changes and creations) Register the created class to db when you touch the model

python3 manage.py makemigrations

■ migrate (reflect)

python3 manage.py migrate

■ Use the administrator screen

Create superuser

python3 manage.py createsuperuser

/ admin will be available.

■ Test memo posts/tests.py

Make the test look like if the logged-in user can create a blog post by entering the title and body.

from django.test import TestCase
from django.contrib.auth.models import User


from .models import Post


class BlogTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        # Create a User
        testuser1 = User.objects.create_user(
            username='testuser1',
            password='abc123!'
        )
        testuser1.save()


        # Create a blog post
        test_post = Post.objects.create(
            author=testuser1,
            title='Blog title',
            body='Body content...'
        )
        test_post.save()


    def test_blog_content(self):
        post = Post.objects.get(id=1)
        expected_author = f'{post.author}'
        expected_title = f'{post.title}'
        expected_body = f'{post.body}'
        self.assertEquals(expected_author, 'testuser1')
        self.assertEquals(expected_title, 'Blog title')
        self.assertEquals(expected_body, 'Body content...')

If the local server is running, stop it with Ctrl + c and press the following command from the terminal to test.

(blogapi-H-RPCYMU) $ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.125s


OK
Destroying test database for alias 'default'...

Django's test code seems to be written like this.

Recommended Posts

Django environment construction
django environment construction
Django project environment construction
Django development environment construction memo
Docker + Django + React environment construction
django project development environment construction
Mac + Eclipse (PyDev) + Django environment construction
DeepIE3D environment construction
Emacs-based environment construction
Linux environment construction
Python environment construction
[Django] Memorandum of environment construction procedure
Environment construction (python)
[For beginners] Django -Development environment construction-
CodeIgniter environment construction
python environment construction
Python --Environment construction
Python environment construction
Golang environment construction
python environment construction
Word2vec environment construction
Environment construction: GCP + Docker
python windows environment construction
Go language environment construction
ConoHa environment construction memo
homebrew python environment construction
PyData related environment construction
Anaconda-4.2.0-python3 environment construction (Mac)
Python development environment construction
YOLO v4 environment construction ①
pyenv + fish environment construction
python2.7 development environment construction
BigGorilla environment construction memo
grip environment construction onCentOS6.5
Anaconda environment construction memo
Golang environment construction [goenv]
Mac environment construction Python
Pyxel environment construction (Mac)
[Memo] Django development environment
Python environment construction @ Win7
[Django3] Environment construction and various settings summary [Python3]
From 0 to Django development environment construction to basic operation
[Ubuntu 18.04] Tensorflow 2.0.0-GPU environment construction
Python + Anaconda + Pycharm environment construction
About Linux environment construction (CentOS)
Minimal website environment with django
PyTorch C ++ (LibTorch) environment construction
Anaconda environment construction on CentOS7
Django Getting Started: 1_Environment Building
First LAMP environment construction (Linux)
Python environment construction (Windows10 + Emacs)
Environment
CI environment construction ~ Python edition ~
Django
[Memo] Construction of cygwin environment
ML environment construction with Miniconda
Python environment construction For Mac
Anaconda3 python environment construction procedure
Anaconda3 × Pycharm environment construction memo
Python3 environment construction (for beginners)
Python environment construction and TensorFlow