Hello, everyone. This is the latest edition of Learning Python. What can YOU do? Django tutorials from scratch to finally successfully deploy live projects. In this section, we’ll implement the login page.

Peekpa.com official address: Peekpa.com

In the previous section we designed the PeekpaUser model, and we inherited the Dashboard and Login page from AdminLTE, so in this section we’ll look at how to use the Login page to Login and then jump to the Dashoboard page.

To realize the login

First of all, we want to implement a Login in PeekpaUser function, before the Login method in http://127.0.0.1:8000/admin, is called the Django system method, but because we want to be in writing your own Login page for the Login logic, So we need to write the login logic in PeekpaUser.

The first step is to create the views.py file under Peekpauser. We will write the view function in this file:

Because our Login page Login, is required to enter limited and password:

And the Form should send a POST request, so we’ll write a POST request login function in views.py:

@require_POST
def login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password')
        remember = form.cleaned_data.get('remember')
        user = authenticate(request, email=email, password=password)
        if user:
            if user.is_active:
                login(request, user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                print("login success")
                return redirect(reverse('cms:dashboard'))
            else:
                return restful_response.unauth(message="The account has been suspended.")
        else:
            # return restful_response.params_error(message=" wrong phone or password ")
            return redirect(reverse('index'))
    else:
        errors = form.get_errors()
        return restful_response.params_error(message=errors)
Copy the code

The method is first decorated to handle POST requests with the @require_POST decorator.

Then use the Django form LoginForm in the forms.py file to clean up the Post data:

class LoginForm(forms.Form, FormMixin):
    email = forms.CharField(max_length=11)
    password = forms.CharField(max_length=20, min_length=6, error_messages={"max_length":"Face must not exceed 20 characters."."min_length":"Password must be at least 6 characters long."})
    remember = forms.IntegerField(required=False)
Copy the code

Here we create a base class for the Form in the Base folder to make it easy to handle error messages.

We then get the email and password and call the authenticate method of Django.contrib. auth to do the authentication. If the login is successful, it will automatically jump to CMS: Dashboard page, which is the dashboard page of the CMS we integrated before. If it fails, an error message is returned.

Next, we need to create a urls.py file under the Peekpauser directory to write the URL mapping for the current application:

urlpatterns = [
    path("login/", views.login_view, name="login"),]Copy the code

The final configuration step is to configure the URL mapping in the root URL file of the project, so we need to add peekpauser’s URL mapping path to urls.py under the Peekpa path:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('account/', include('apps.peekpauser.urls')), Add PeekpaUser to the url
    path(' ', index, name='index')]Copy the code

At this point, our login POST request is complete.

Jump after login is complete

After the login is successful, the page should jump to CMS: Dashboard page. Since we want to do this jump, we must introduce the URL of dashboard page into the system.

Start by creating an application called CMS through startApp in the Run Manage.py Task.

Then move the CMS application to the apps directory:

Now that we’re mapping the dashboard.html we wrote earlier to our CMS application, let’s create a CMS folder in front/ Templates/and map Dashboard and login to it.

Map login page

First, the login page needs to be mapped to the CMS page. To integrate a page into an application, there are several steps:

  • Write a good web page;
  • Create view functions in views.py
  • URL mapping authoring

So that’s three steps, so we’re done with step one here, and then step two, creating the view function for Login.

We need to go to the views.py file of our CMS and create our Login view function:

def cms_login(request):
    return render(request, 'cms/login.html')
Copy the code

Yes, it’s that simple, just two lines, then create a urls.py file under the CMS and write the URL mapping in it, just as you wrote the URL in peekpauser above: write the URL under the app and integrate the CMS URL into the main URL.

# urls.py file for CMS
urlpatterns = [
    path("login/", views.cms_login, name="login"),]# main urls file
urlpatterns = [
    ...
    path('cms/', include('apps.cms.urls')),... ]Copy the code

At this point, our integration work is over, want to see whether the integration is successful, only need to restart the server, and then enter the correct address in the browser can: http://localhost:8000/cms/login/

When we open the Chrome console, we see a bunch of red errors:

This error indicates that the resource file did not load successfully.

The reason for this is that our page resource file path should be changed to a Django template type, not a path file.

How to modify it? Let’s take the Login page as an example and change the resource path:

First, modify Settings

The first step is to change the TEMPLATES variable in settings.py. Add the builtins variable to it and change it to the following:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates'.'DIRS': [os.path.join(BASE_DIR, 'front'.'templates')].'APP_DIRS': True.'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug'.'django.template.context_processors.request'.'django.contrib.auth.context_processors.auth'.'django.contrib.messages.context_processors.messages',].# Builtins is a new addition
            'builtins': [
                'django.templatetags.static']]}},Copy the code

After that, we can use the static keyword in the template HTML file. Next, we go to the login page and change the previous one to.. /.. / relative path to resource files from:

<! -- Font Awesome -->
<link rel="stylesheet" href=".. /.. /dist/adminlte/plugins/fontawesome-free/css/all.min.css">
<! -- icheck bootstrap -->
<link rel="stylesheet" href=".. /.. /dist/adminlte/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
<! -- Theme style -->
<link rel="stylesheet" href=".. /.. /dist/adminlte/dist/css/adminlte.min.css">
<! -- jQuery -->
<script src=".. /.. /dist/adminlte/plugins/jquery/jquery.min.js"></script>
<! -- Bootstrap 4 -->
<script src=".. /.. /dist/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<! -- AdminLTE App -->
<script src=".. /.. /dist/adminlte/dist/js/adminlte.min.js"></script>
Copy the code

Is amended as:

<! -- Font Awesome -->
<link rel="stylesheet" href="{% static 'adminlte/plugins/fontawesome-free/css/all.min.css' %}">
<! -- icheck bootstrap -->
<link rel="stylesheet" href="{% static 'adminlte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}">
<! -- Theme style -->
<link rel="stylesheet" href="{% static 'adminlte/dist/css/adminlte.min.css' %}">
<! -- jQuery -->
<script src="{% static 'adminlte/plugins/jquery/jquery.min.js' %}"></script>
<! -- Bootstrap 4 -->
<script src="{% static 'adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<! -- AdminLTE App -->
<script src="{% static 'adminlte/dist/js/adminlte.min.js' %}"></script>

Copy the code

When we look at the Login page in the browser page and see that they all have static filters added:

As you can see, we’ve got it exactly right. Next, we had to change Dashboard’s resource path as well, and integrate the same Login integration method into CMS. The specific operation will not repeat, the steps have been written in Login.

Integration, open http://localhost:8000/cms/dashboard/ page will appear our Dashboard page:

Next, we need to get through the logic of the Login jump in the Login page.

We first need to configure the action on the Login Form in the Login page.

<form action="{% url 'peekpauser:login' %}" method="post">
Copy the code

We then enter our email address and password on the login page, and the assassin will see the error message pop up:

This is because Django’s default Form submission requires a CSRF Form validation. This validation is not available on the AdminLTE page. It is as simple as adding a line of code to the Form of the Login page:

<form action="{% url 'peekpauser:login' %}" method="post">
        <! -- Add new code -->
          {% csrf_token %}    
        <div class="input-group mb-3">
Copy the code

Reload the page, enter SuperUser’s email and password, and the Dashboard page will be redirected to:

Error message indicating email and password This field is required.

This is because the input tag in our Form does not have a name attribute, so we just need to complete the name attribute in the input:

.<input type="email" class="form-control" placeholder="Email" name="email" >.<input type="password" class="form-control" placeholder="Password" name="password">.Copy the code

Run it again this time and everything is fine:

Perfect, but cautious but students must be found, the Dashboard page you path not login in time can also visit http://localhost:8000/cms/dashboard/? Don’t worry about this, in later chapters, we will add permissions to the page, if you do not log in, it will automatically jump to the login page. What I want to do in this video is run through the logon logic.

Technical summary

So just to conclude,

Design login jump:

  1. Firstly, the Login page and Dashboard page are integrated into the CMS application.
  2. Write the Action address of the Login page as the URL of the Login mapping in PeekpaUser.
  3. Don’t forget to add the name attribute to the Input tag. The value of name is the corresponding field;
  4. The completion of

The only way to get the code: follow “PI Ye Lu code” and reply “code” to get it.

Long press the two-dimensional code below to pay attention to, if the article is inspiring to you, welcome to look at and forward.