admin管理员组

文章数量:1530085

        (This blog merely for self-reading, self-review and every progamming lover's share under no commercial circumstance.)

<html lang="en">

        As I research and test with django for many days, django's concealed working procedure has ultimately been revealed.

        First it is really thankful for the following pictures:

 

which copied from the oringinal wirter 只小白 in CSDN platform. (Ii is more appropriate that I should deliver my sincere gratitude to CSDN and every programers.)

        Let's assume that you have deploy your Django project to the open internet and someone is inclined to browse your website. The first thing is to search in client-side( Browser: Chrome, Firefox,etc.).  Let's assume that this person is searching the domain name.

        (By the way, in HTML:<meta name='keywords' content='specific keywords contents' />, when someone searches in Google CSEs( Custom Search Engines), the 'specific keywords contents' is which CSEs are scouring for.)

        Client-side delivers the request to the server-side. Then server-side invokes the web pattern to process the request. Django is one of the web patterns.

        Let's assume the web project is as the following pictures show:

         trial is the folder which saves all the project. ve, the virtual environment in abbreviation, is the folder to provide virtual environment for respective projects to work individually with no interaction to other projects in the computer. project, as it is named, is the project, forms is a web application( You may need to create many web applications for one project. By doing so, the users system, blog system, etc. are seperated, which allows the projects to become more regular and alse, simple for revising one system with no affects for other system.).

        Then let's keep on. The web pattern is invoked for the request processing, Firstly, Django goes to the project urls.py to search the url:

"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""



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

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

        The first url pattern 'admin/' is for the web administrators. However, this person is searching https://www.aens/register_page nor https://www.aens/admin. So Django chooses the second path:

path(' ', include(' forms.urls')).        The contents in ' ' are the domain name's suffix                                                         (e.g. https://baidu/(' ')).

                                                        ' forms.urls' is the one Django wants to view, which indicates                                                         the first urlpattern.

        Then Django finds the forms's urls, which is in the urls.py in forms folder:

         Django keeps search the second urlpatterns in trial/forms/urls.py:

from django.urls import path
from . import views

app_name = 'forms'
urlpatterns=[
    path('', views.index, name='index'),
    path('register_page', views.register_page, name='register_page'),
    path('login_page', views.login_page, name='login_page'),
    path('users_homepage', views.users_homepage, name='users_homepage'),
]

 As the person searches https://www.aens/register_page/ nor https://www.aens/login_page  nor https://www.aens/users_homepage etc. , Django chooses the seconde path and goes to the tiral/forms/views.py to find register_page function:

from django.shortcuts import render, redirect
from .models import Users
from django.http import HttpResponse

# Create your views here.


def index(request):
    return render(request, 'index.html')

def users_homepage(request):
    return render(request, 'users_homepage.html')

def register_page(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if Users.objects.filter(username=username):
            return HttpResponse('该账户已被注册')
        else:
            user_info=Users(username=username, password=password)
            user_info.save()
            return redirect('forms:login_page')

    return render(request, 'register_page.html')


def login_page(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if Users.objects.filter(username=username):
            if Users.objects.filter(username=username,password=password):
                return redirect('forms:users_homepage')
            else:
                return HttpResponse('密码错误')
        else:
            HttpResponse('用户名错误或压根不存在')
    return render(request, 'login_page.html')

        Django finds that the register_page function invokes for circumstance and method POST, Django initially notes the function in background and render the register_page.html because return statement orders Django to render the register_page.html in Hypertext Markup Language first:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>login/register</title>
</head>
<body bgcolor="#EED8AE">
    <h1>
        <font size="20" color="grey">
            Forms experiment
        </font>
    </h1>
    <form method="post">
        {% csrf_token %}
        <p>
            username created:
            <input type="text" name="username" placeholder="Username">
        </p>
        <p>
            password created:
            <input type="password" name="password" placeholder="Password">
        </p>
        <br/>
        <input type="submit" value="提交" style="width: 60px; text-align: center;">

    </form>
</body>
</html>

( This html fragment tutorial will not be involved.)

        This webpage shows like:

        Django takes the function in its background and render this webpage. Once the person inputs the username and password and tap "提交". The form is created and  will be submitted to Django's background and processed by Django's background function: register_page(request).

        Let's assume the person sets his:

        username: 00drdelius

        password: 123456

        Then it is the time for the interaction between database and Django.

        First, it is supposed to analyse the register_page function:

def register_page(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if Users.objects.filter(username=username):
            return HttpResponse('该账户已被注册')
        else:
            user_info=Users(username=username, password=password)
            user_info.save()
            return redirect('forms:login_page')

    return render(request, 'register_page.html')

        The username and password informations have been saved in the form. By the method PSOT analysis in the register_page function, variable username and variable password are valued ( In Python, it is more appropriate to say "referred" nor "valued".) by the form.

        Be careful here: 'username' and 'password' are respectively referred to the name in register_page.html:  (Which means the variable's contents shall be identical to the name)

         The form has been analysed, it's the time for database. But it is supposed to mention the trial/forms/models.py first.

        models.py is the file to interact between web application and database. The picture beneath is trial/forms/model.py:

from django.db import models

# Create your models here.
class Users(models.Model):
    objects = models.Manager()
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=10)
    password = models.CharField(max_length=20)

    def __str__(self):
        return self.username

    class Meta:
        verbose_name='用户'
        verbose_name_plural='用户'

        class Users(models.Model) means to create a table in your database, the table name is automatically set by models class.

        ( The table is named as forms_users here. If you want to change the table's name, you may         add the code in class Meta like:

                class Meta():

                        db_table='The name you want '

        )

        objects is the manager for database-web application interaction( objects usage tutorial         omitted).

        id is the field (the name of one column) in this table. So are username and password.

        They are created in the database, which you will see in the database workbench:

         Then register_page function will keep on the next code:

        if Users.objects.filter(username=username):
            return HttpResponse('该账户已被注册')
        else:
            user_info=Users(username=username, password=password)
            user_info.save()
            return redirect('forms:login_page')

  The Users.objects.filter() invokes the data in database and set these data in list type like:

        Users=[<Users: 00drdelius>,<Users: 123456>,<Users:1>,...]

  Which could also be translated in SQL language:

        SELECT id, username, password FROM forms_users;

        or

        SELECT * FROM forms_users;

( If it is Users.objects.get() should be: <Users:00drdelius>,etc.)

Then here in register_page function:

        if Users.objects.filter(username=username)

is to invoke the username field in forms_users table: SELECT username FROM forms_users

and analyse whether the username in form is identical to every username in username fieldm forms_users table.

        If they are identical, return HttpResponse('该账户已被注册').

        If it is new, then perform:

        user_info=Users(username=username, password=password)
        user_info.save()

        which means the username and password in form are saved in the database. It has been         shown at the upper picture.

        Then perform teh return statement to redirect to forms: login_page.

        Then Django will check the trial/forms/urls.py again:

        Let's analyse forms:login_page:

        forms is the app_name, indicate Django to search urls.py in app forms nor other app.

        login_page in forms:login_page is referred to the name which is writen in the path.

        This rule also could be invoked in html, templates folder. Like:

        <a href={%url ' forms: users_homepage' %}>...</a>

        Then Django will be indicated to the third path, and the current domain name should be: https://www.aens/login_page. And Django will keep on performing the next code in views.login_page.

       Thanks for reading.

</html>

        Delius, 戴御前, 08/08/2021  13:27

本文标签: djangoworkingprocedure