[PYTHON] Django beginners create simple apps 2

Introduction

Continuation of Django Beginners Create Easy Apps 1. We'll strip away the complexity and hassle as much as possible, create a simplified web app, and specialize in learning how Django works. Only understand what is connected and how it moves around the back end. Implement CRUD (Create, Read, Update, Delete) and if it works, you will reach the goal. (Please don't ask me if it's a web application even though I can't connect to the internet.)

Series table of contents for beginners to create simple apps

-Django Beginners Create Easy Apps 1 --Preparation-Overview of Django-Creating models.py -Django beginners make simple apps 2 (← Now here) --Implementation of Read part (creation of urls.py, views.py, template file) -Django beginners make simple apps 3 --Implementation of Create part (creation of form.py etc.) --Django Beginners make simple apps 4 --Comparison of Class-based-view and Function-view --Django Beginners make simple apps 5 (Completed) --Implementation of Update part and Delete part

environment

Premise

The project name is config and the app name is myapp. In other words, the following two commands have been executed

The templates directory is in the same hierarchy as manage.py, and setting.py has also been modified.

1. Create urls.py

Now that you have a box (or table) with the information in model.py, decide where to put that information. To do this, first write the code in config / urls.py.

Code in config / urls.py

config/urls.py


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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')), #Add this line
]

path ('myapp /'... means 127.0.0.1:8000/myapp/.myapp.urls in include parentheses is "detailed in urls.py in myapp directory" It means "yo". Next, create myapp / urls.py. Create and edit the file yourself. First, write the code for these two addresses: ʻindex (list screen) that displays the entire list, and movie_detail` (detail screen) that displays the details of the movie when you click the title of the movie.

Code in myapp / urls.py

myapp/urls.py


from django.urls import path
from . import views

app_name = 'myapp'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('movie/<int:pk>/', views.MovieDetailView.as_view(), name='movie_detail'),
]

Note on urls.py

The explanation of the code is as follows ... just a reminder. C569F59B-714E-403C-9E99-CF594A52FBDC.jpeg

Beginners don't know what code they need, where they can or shouldn't change. What you can decide on your own

  1. Address part of '' or movie / <int: pk>
  2. ʻIndexVieworMovieDetailView` (because it will be described later in views.py)
  3. The part after name = such as ʻindex or movie_detail`

Above three. Other than that, it's the code and instructions that Django and python come with from the beginning, so don't change them.

urls.py Summary

Write the following three codes in the path function

  1. Determine the address
  2. Decide which view to use
  3. Give a name that summarizes the addresses

2. Create views.py

I made a box with information in models.py. I decided where to paste (address) in urls.py. The next thing to do is "how to take out the information contained in the model and prepare for pasting", and views.py is responsible for that.

Implementation in Class Based View

Speaking of which is better, View to function (function view) or Class (class view). From the conclusion, Class Based View is recommended. Very easy to write code. However, for beginners, it is difficult to understand how to use it because it is not clear what is going on with blackboxing. Actually, if you read the Document and dig deeper, you can see that it is nothing like a black box, but I do not understand the terms explained further, so I'm sick. On the contrary, the view function has a little more code, but you can see how it works. This time, I would like to implement it with Class Based View and try to rewrite it with view function when it is completed. In other words, in the reverse order of the tutorial. Since I decided the addresses of the list screen and the detail screen earlier, I will write the code to extract the information to be displayed there and prepare to paste the information.

Views.py code

myapp/views.py



from django.views import generic
from myapp.models import Movie, Director, Log


class IndexView(generic.ListView):
    template_name = 'myapp/index.html'
    context_object_name = 'movie_list'
    queryset = Movie.objects.all()


class MovieDetailView(generic.DetailView):
    model = Movie
    template_name = 'myapp/detail.html'

That's it. Greatly less code. After that, DetailView automatically handles it well. The memorandum is as follows.

Notes on views.py

79ED0F5D-22EC-4DD4-BF16-FD761F622640.jpeg

views.py Summary

【The entire】

  1. Import generic to use Class Based View
  2. Import the model (Movie, Director, etc.) created in models.py

【ListView】 3. Use queryset to retrieve information from model 4. Name the chunk of information with context_object_name 5. Pass the information to the HTML file specified by template_name

【DetailView】 6. Decide the model to bring the information 7. Pass the information to the HTML file specified by template_name

3. Create Template

Now it's time to display the information properly. A template file is an HTML file. See how you write the code and how it looks. Before that, create a myapp directory in the templates directory, and create an HTML file in that myapp directory. The directory structure is as follows.

.
├── config
├── db.sqlite3
├── manage.py
├── myapp
├── myenv
├── static
└── templates
    └── myapp #Create an HTML file in this directory
        └── index.html
        └── detail.html

Originally, I would create base.html, extend it with {% block%}, and so on, but I'm honestly creating index.html and detail.html.

code in index.html

templates/myapp/index.html


{% if movie_list %}
    {% for movie in movie_list %}
    <li>
        <a href="{% url 'myapp:movie_detail' movie.id %}">{{ movie.title }}</a>
        {{ movie.director }}
        {{ movie.watch_date }}
    </li>
    {% endfor %}
{% endif %}

So, if you run server and check the display, it will be as shown in the figure below.

Result of index.html (list screen)

indexpicturecrop.png

Note on index.html

0D505FE9-A3E7-4F95-98D7-6C23DD358983.jpeg

If you click the link of the title part from the list screen, the details screen will be displayed, but the code is as follows

code in detail.html

templates/myapp/detail.html


<h1>{{ movie.title }}</h1>
<h2>{{ movie.director }}</h2>
<h3>{{ movie.watch_date }}Viewing</h3>

{% for log in movie.log.all %}
    <li>{{ log.text }}</li>
{% endfor %}

So, if you also display the result with runserver, it will be as shown in the figure below

Result of detail.html (detail screen)

detailpicturecrop.png

Note on detail.html

94ADC53D-A192-4282-AEBE-ADFBECD067D9.jpeg

Template summary

  1. Hit in the head which file to pull the name written in
  2. Use Django, Python, and HTML in three parentheses, and combine them into a template. -{{Parents used when writing variables to display}} --{% Parentheses used when writing Python code%} -
  3. It is important to determine whether it is a forward reference or a reverse reference. Use related_name for reverse reference

Afterword

As long as you understand where and how they are connected, you can write and display code with that combination. I had a hard time not knowing the connection in the official tutorial. By the way, the following two articles (I wrote it) understood and summarized the connection of the official tutorial as a beginner.

-Review Django Tutorial: How Views.py and urls.py are Connected -Review Django Tutorial: How is view and each html connected

Even after a year and a half, I couldn't get out of the beginner's class by walking like a turtle (crying) ... Anyway, this time I got the Read part of CRUD (Create, Read, Update, Delete). Next time Create! However, I may flirt and go to rewrite the function View. If you have any mistakes, I would appreciate your guidance.

Recommended Posts

Django beginners create simple apps 3
Django beginners create simple apps 1
Django beginners create simple apps 2
Django beginners create simple apps 5
Django beginners make simple apps 4
Create initial settings and staff apps in Django
Create a Django schedule
django oscar simple tutorial
Create Django Todo list
Create an API with Django
Create a (simple) REST server
Create ToDo List [Python Django]
Create a homepage with django
Shell to create django project
Create a Django login screen
Create your own Django middleware
Create a simple textlint server
Create and list Django models
(For beginners) Try creating a simple web API with Django
Hello World (beginners) on Django
Create a social integration API for smartphone apps with Django
Steps to create a Django project
Django beginners tried building an environment
[For beginners] Django -Development environment construction-
Create new application use python, django
[Django] Create your own 403, 404, 500 error pages
Create a file uploader with Django
Create a LINE Bot in Django