Django entry diary Day3

User registration

1. I nitializing a Django App

From the command line, cd to the project folder, and then:

>python manage.py startapp users

Register a new app in settings.py. Add the following to the installed? APS list:

    'users.apps.UsersConfig',

Add a path for the new app in urls.py. Add the following code:

from users import views as user_views
urlpatterns = [
    path('register/', user_views.register, 
]

II. views.py

Django's UserCreationForm method has the initialization form layout registered by the user (but excluding the submit button), which does not need to be customized. It is assigned to the variable form here.
The render() method returns the rendered HttpResponse object and passes the form variable to register.html. (create a new register.html under users > Templates > users)

from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm

def register(request):
	form = UserCreationForm()
    return render(request, 'users/register.html', {'form': form})

III. register.html

  1. Also inherit the layout of base.html.
  2. The two most commonly used HTTP methods are GET and POST. GET - requests data from the specified resource. POST - submits the data to be processed to the specified resource. The user registration information is submitted to the server, so the POST method is used.
  3. In the html template of the form form form using the POST method, you need to add csrf_token in the < form > element:
    <form method="post">{% csrf_token %}
    
    Explanation of CSRF in Django document:

    Cross Site Request Forgery protection
    The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries.
    register.html:

{% extends "blog/base.html" %}
{% block content %}

<div class="content-section">
    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom ml-0">Join Today !</legend>
            {{ form }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Sign Up</button>
        </div>
    </form>
    <div class="border-top pt-3">
        <small class="text-muted">
            //Already have an account?<a class="ml-2" href="#">Sign In</a>
        </small>
    </div>
</div>

{% endblock content %}

In order to beautify the style, you can change {form}} to {form.as_p}}}, which means to display the form in sections; or use crsipy package, which will be introduced later.

4. Add page response for successful registration

In views.py,

  1. Add code so that when the request of POST method is received, the data will be stored in variable form through UserCreationForm() method, otherwise the form will be empty.

  2. If the input data is valid, get the user name (referred to when registering the success notification) through the cleaned_data_get() method.

  3. Import the messages framework of Django, and send the messages using the messages. Suits method.
    The common messsages methods are as follows:

    messages.debug(request, '%s SQL statements were executed.' % count)
    messages.info(request, 'Three credits remain in your account.')
    messages.success(request, 'Profile details updated.')
    messages.warning(request, 'Your account expires in three days.')
    messages.error(request, 'Document deleted.')
    

    There are five Message tags: debug, info, success, warning, error.

  4. Import Django's redirect module and go to the blog home page through the redirect() method after successful registration.

Add a layout for the registration success message in base.html: if the messages variable is not empty, each message will be displayed in turn. Determine the bootstrap style of alert by referencing messages.tags.
The code is as follows:
views.py:

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for { username } !')
            return redirect('blog-home')
    else:
        form = UserCreationForm()

    return render(request, 'users/register.html', {'form': form})

base.html:

			<div class="col-md-8">
                {% if messages %}
	                {% for message in messages %}
		                <div class="alert alert-{{ message.tags }}">
		                    {{ message }}
		                </div>
	                {% endfor %}
                {% endif %}
                {% block content %}{% endblock %}
            </div>

5. Save new user to server

If the form submitted by the user is valid, execute form.save()
The modified code fragment in views.py is as follows:

		if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for { username } !')
            return redirect('blog-home')

6. Create a new mailbox domain in the registration form

After that, the new user can be saved to the server after registration and can be viewed in the admin page.
But it lacks Email information, because the default UserCreationForm() method does not contain EmailField. You can customize a new method that inherits the UserCreationForm method and add EmailField on this basis.

  1. Create a new forms.py file in the user directory
  2. Import the forms, User and UserCreationForm framework of Django
  3. Define the class UserRegisterForm, inherit the UserCreationForm method, and define the class Meta, which is not well understood here, to be solved.
  4. Import the UserRegisterForm method in views.py and replace the UserCreationForm with this method.

The code is as follows:
forms.py:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
	
class UserRegisterForm(UserCreationForm)
	email = forms.EmailField()
	
	class Meta:
		model = User
	    fields = ['username','email','password1','password2']

views.py:

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for { username } !')
            return redirect('blog-home')
    else:
        form = UserRegisterForm()

    return render(request, 'users/register.html', {'form': form})

7. Beautify registration interface with free third-party Django application crispy

  1. Download the crispy package: PIP install Django crispy forms.

  2. In settings.py, add the item "crispy forms" in installed apps, and at the end of the file, add:

    CRISPY_TEMPLATE_PACK = 'bootstrap4'
    

    Make crispy use the Bootsrap4 style (Bootsrap2 by default).

  3. In register.html, {% load crispy ﹤ forms ﹤ tags%}, and use crispy to filter the registration interface form: {form|crispy}}

register.html final code:

{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

<div class="content-section">
    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom ml-0">Join Today !</legend>
            {{ form|crispy }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Sign Up</button>
        </div>
    </form>
    <div class="border-top pt-3">
        <small class="text-muted">
            //Already have an account?<a class="ml-2" href="#">Sign In</a>
        </small>
    </div>
</div>

{% endblock content %}
Published 3 original articles, praised 0 and visited 16
Private letter follow

Tags: Django Python SQL Fragment

Posted on Tue, 14 Jan 2020 02:43:45 -0800 by purpendicular