Django beginners make simple apps 4

Introduction

A continuation of 3 where Django beginners create simple apps. Last time, I created C of CRUD, that is, Create part with Class-based-view. This time I'd like to rewrite Class-based-view to Function-view and follow how Django works by comparing the two.

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 --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 (← Now here) --Comparison of Class-based-view and Function-view --Django Beginners make simple apps 5 (Completed) --Implementation of Update part and Delete part

environment

Ubuntu 20.04 LTS Python 3.8.2 Django 3.02

Premise

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


(myenv)$ django-admin startproject config .
(myenv)$ python manage.py startapp myapp

The templates directory is created in the same hierarchy as manage.py, and setting.py has also been modified. (See "Beginners Create Easy Apps 1")

1. Rewrite Class IndexView to def index

index_view



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

#Below is the Function-view

def index(request):
    movie_list = Movie.objects.all()
    return render(request, 'myapp/index.html', {'movie_list': movie_list})

Actually it ended in 2 lines ... Function-view has shorter code. What you are doing

  1. Collect all the data from the movie of the model (database) and put it into an object (instance) called movie_list.
  2. Render to index.html using movie_list as material

Knowledge learned

1-1. What is a request?

-Request and Response Objects

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Django then passes HttpRequest as the first function of the view function to load the appropriate view. Every view should return an HttpResponse object.

What is the argument request? Who is requesting what? I was wondering, but the identity of ** request was an object (instance) ** of HttpRequest.

1-2. What is render ()?

Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

The render function will format the dictionary type data into an HTML file and display it. ** The final thing that comes out with render () is the HttpResponse object (instance). ** **

1-3. What are objects?

Each non-abstract Model class must have a Manager instance added to it. Django ensures that in your model class you have at least a default Manager specified. If you don’t add your own Manager, Django will add an attribute objects containing default Manager instance.

** There is a thing called Manager to pull the data in the model (database), and its name is objects. ** So Movie.objects.all () means "Movie objects (Manager), bring all the data!".

2. Rewrite Class MovieDetailView to def moviedetail

detail_view



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

#Function from here-view

def moviedetail(request, pk):
    m = Movie.objects.get(pk=pk)
    return render(request, 'myapp/detail.html', {'movie': m})

Only two lines were needed here. The pk in the(request, pk)part is the<int: pk>of thepath ('movie / <int: pk> /',described in urls.py. This is changed. Yes. If you change the url to <int: movie_id>, change it to (request, movie_id). What you're doing with this function is

  1. Get the data in Movie (database) whose pk (primary key) matches the request and make it an object called m
  2. Render m as a movie in detail.html I wonder if that will be the case.

3. Rewrite Class RegisterDirectorView to def registerdirector

register_director_view


class RegisterDirectorView(generic.CreateView):
    model = Director
    form_class = DirectorForm
    template_name = 'myapp/register.html'
    def get_success_url(self):
        return reverse('myapp:registermovie') 

#Function from here-view

def registerdirector(request):
    if request.method == "POST":
        form = DirectorForm(request.POST)
        if form.is_valid():
            d = form.save(commit=False)
            d.save()
            return redirect('myapp:registermovie')
    else:
        form = DirectorForm()
        return render(request, 'myapp/register.html', {'form': form})

The big difference between Class-based-view and Function-view is here at CreateView. Function-view is easier to understand in order to understand the mechanism.

Knowledge learned

3-1. request.method == What is "POST"?

-IT Glossary that makes you feel like you understand even if you don't understand it --HTTP Request Methods -Explanation of the difference between POST and GET in django [There are also specific examples]

The browser communicates with the server via HTTP, but the method is POST. Actually, there is a description of <form method =" POST "> in register.html, which means that when the save button is pressed, the data will be sent as POST, which is entwined with this line.

3-2. form = What is DirectorForm (request.POST)?

-Create your first Django app, part 4

request.POST is a dictionary-like object. You can specify the key to access the data you sent. In this case, request.POST ['choice'] returns the ID of the selected choice as a string. The value of request.POST is always a string.

In other words, if the data entered in request.POST is included. It means that an object called form is created by applying it to DirectorForm.

3-3. What is form.is_valid ()?

The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid:

Whether an object called form is valid. If there is an input omission, it will play with this. I didn't know the terms validation (checking if the data I entered was correct) and cleaning the data (formatting the data into an easy-to-use form), so at first I was sick.

3-4. What is d = form.save (commit = False)?

-Django, note of commit = False in form set

This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.

The form containing the data is saved to an object called d, but it is not yet in the database. I wondered why I was doing this, but it seems that I may add data to this form later and save it in the database again. Is it something like temporary storage? Then, when it is finally saved in the database with d.save () on the next line.

Other

redirect () says "Fly to the address in ()", and below else says "Create an empty form and render it in register.html". If you use the knowledge you learned in this way, you will be able to read more and more code. I'm glad that I have evolved.

4. Rewrite Class RegisterMovieView to def registermovie

register_movie_view



class RegisterMovieView(generic.CreateView):
    model = Movie
    form_class = MovieForm
    template_name = 'myapp/register.html'
    def get_success_url(self):
        return reverse('myapp:movie_detail', kwargs={'pk': self.object.pk }) 

#Function from here-view

def registermovie(request):
    if request.method  == "POST":
        form = MovieForm(request.POST)
        if form.is_valid():
            m = form.save(commit=False)
            m.save()
            return redirect('myapp:movie_detail', pk=m.pk)
    else:
        form = MovieForm()
        return render(request, 'myapp/register.html', {'form': form})

The code is almost the same as last time. If you dare to say it, it's the redirect ('myapp: movie_detail', pk = m.pk) part, but does it mean "fly the pk of the object m as the pk of the movie_detail"?

5. Rewrite Class WritingLogView to def writinglog

writing_log_view



class WritingLogView(generic.CreateView):
    model = Log
    form_class = LogForm
    template_name = 'myapp/register.html'
    def get_success_url(self):
        return reverse('myapp:movie_detail', kwargs={'pk': self.object.movie.pk }) 

#Function from here-view

def writinglog(request):
    if request.method == "POST":
        form = LogForm(request.POST)
        if form.is_valid():
            l = form.save(commit=False)
            l.save()
            return redirect('myapp:movie_detail', pk=l.movie.pk)
    else:
        form = LogForm()
        return render(request, 'myapp/register.html', {'form': form})

The code is almost the same. "I can read! I can read!" (By Muska)

Afterword

Class-based-View will be easier to write in the end, but Function-view is easier to understand the mechanism and I feel that I can reach the details. Is it like an automatic car and a manual car? No, if you rewrite it to Function-view, it will not work unless you rewrite urls.py properly, so it's not bad. Next time, we plan to implement CRUD UD, that is, Update and Delete. It's probably easier to understand if you write the code side by side like this time. If you have any mistakes, please point out and give us guidance. Is the goal close ...?

Recommended Posts

Django beginners make simple apps 4
Django beginners create simple apps 2
Django beginners create simple apps 5
# 1 Python beginners make simple English word learning tools
django oscar simple tutorial
[Django] Make a pull-down menu
(For beginners) Try creating a simple web API with Django
Hello World (beginners) on Django
Django beginners tried building an environment
[For beginners] Django -Development environment construction-
Make a filter with a django template