Django framework develops blog system at a high speed in a week

In the last article, we created a DjangoBlog project and created an atile app, in which we realized the functions of creating, updating, deleting and displaying blog management system articles.

https://blog.csdn.net/agelee/article/details/120429578https://blog.csdn.net/agelee/article/details/120429578 In this article, we will continue to develop and implement the registration and login function module of blog.

Login page:

  Registration page:

 

Create app

The functions of user management and blog posts are different, so you need to create a special app.

python manage.py startapp userprofile

Register APP

Find installed in settings.py_ Under apps, add the newly created article to the App list of the project, as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'article',     
    'userprofile',     # Add this item
]

Define model

The user information of the blog is relatively simple. In order to develop quickly, we directly use the user model provided by Django without establishing our own model.

Define form

When users log in, they need to fill in Form data such as account password, and Django has a special Form class to process Form data.

Forms form class

In HTML, forms are some elements in < form >... < / form >, which allow visitors to do actions such as entering text, selecting options, manipulating objects or spaces, and then send these information to the server. Some form interface elements (text boxes or check boxes) are very simple and built into HTML, while others are more complex: operation controls such as pop-up date selection.

Dealing with forms is a complex thing. Think about Django's admin. Many different types of data may need to be prepared and displayed in a form, rendered into HTML, edited with a convenient interface, transmitted to the server, verified and cleaned up the data, and then saved or skipped for the next step.

Django's form function can simplify most of the above work, and it can be more secure than most programmers write their own code to implement it.

The core component of Django Form system is the Form class, which can describe a Form and determine how it works and renders.

  In this article, we need to implement two function pages: login and registration, so we define two form classes:

userprofile/forms.py

# Import form class
from django import forms
# Introduce User model
from django.contrib.auth.models import User

# The login form inherits the forms.Form class
class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

# Register user form
class UserRegisterForm(forms.ModelForm):
    # Duplicate User's password
    password = forms.CharField()
    password2 = forms.CharField()

    class Meta:
        model = User
        fields = ('username', 'email')

    # Check whether the passwords entered twice are consistent
    def clean_password2(self):
        data = self.cleaned_data
        if data.get('password') == data.get('password2'):
            return data.get('password')
        else:
            raise forms.ValidationError("Inconsistent password input,Please try again.")

Define view functions

In the process of registration and login, we generally involve three functions: login, logout and registration.

Therefore, we create three view functions in the userprofile/views.py file, corresponding to three function modules:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login,logout
from django.http import HttpResponse
from .forms import UserLoginForm,UserRegisterForm

# Create your views here.
def user_login(request):
    if request.method == 'POST':
        user_login_form = UserLoginForm(data=request.POST)
        if user_login_form.is_valid():
            # .cleaned_data cleaning out legal data
            data = user_login_form.cleaned_data
            # Check whether the account and password correctly match a user in the database
            # If both match, the user object is returned
            user = authenticate(username=data['username'], password=data['password'])
            if user:
                # The login action is realized by saving the user data in the session
                login(request, user)
                return redirect("article:article_list")
            else:
                return HttpResponse("Incorrect account or password input. Please re-enter~")
        else:
            return HttpResponse("Illegal account or password input")
    elif request.method == 'GET':
        user_login_form = UserLoginForm()
        context = { 'form': user_login_form }
        return render(request, 'userprofile/login.html', context)
    else:
        return HttpResponse("Please use GET or POST Request data")

def user_logout(request):
    logout(request)
    return redirect("article:article_list")

# User registration
def user_register(request):
    if request.method == 'POST':
        user_register_form = UserRegisterForm(data=request.POST)
        if user_register_form.is_valid():
            new_user = user_register_form.save(commit=False)
            # Set password
            new_user.set_password(user_register_form.cleaned_data['password'])
            new_user.save()
            # Log in and return to the blog list page immediately after saving the data
            login(request, new_user)
            return redirect("article:article_list")
        else:
            return HttpResponse("The registration form is entered incorrectly. Please re-enter~")
    elif request.method == 'GET':
        user_register_form = UserRegisterForm()
        context = { 'form': user_register_form }
        return render(request, 'userprofile/register.html', context)
    else:
        return HttpResponse("Please use GET or POST Request data")

  Configure access route URL

Add login, exit and registered routes in userprofile/urls.py:

from django.urls import path
from . import views

app_name = 'userprofile'

urlpatterns = [
    # User login
    path('login/', views.user_login, name='login'),
    # User exit
    path('logout/', views.user_logout, name='logout'),
    # User registration
    path('register/', views.user_register, name='register'),

Add the URL of the corresponding app in DjangoBlog/url.py:

from django.conf.urls import url
from django.contrib import admin
# Remember to introduce include
from django.urls import path, include
# List of mapping relationships
from article import views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.article_list),
    # Add a new code to configure the url of the app
    path('article/', include('article.urls', namespace='article')),
    #Add this item
    path('userprofile/', include('userprofile.urls', namespace='userprofile')),   
]

Create front end template

Create a new userprofile folder under the templates folder to store the template files related to registration and login.

Then create two new HTML templates under the templates/userprofile folder to realize the function modules of login and registration.

Login page template:

templates/userprofile/login.html

{% extends "base.html" %} {% load static %}
{% block title %} Sign in {% endblock title %}
{% block content %}
<div class="container">
  <div class="row justify-content-md-center">
    <div class="col-6">
      <br>
      <form method="post" action=".">
        {% csrf_token %}
        <!-- account number -->
        <div class="form-group">
          <label for="username">account number</label>
          <input type="text" class="form-control" id="username" name="username">
        </div>
        <!-- password -->
        <div class="form-group">
          <label for="password">password</label>
          <input type="password" class="form-control" id="password" name="password">
        </div>
        <!-- Submit button -->
        <button type="submit" class="btn btn-primary">Sign in</button>
        <div class="form-group">
        <br>
        <h5>No account yet?</h5>
        <h5>click<a href='{% url "userprofile:register" %}'>Registered account</a>Join us!</h5>
        <br>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock content %}

Login page template:

templates/userprofile/register.html

{% extends "base.html" %} {% load static %}
{% block title %} register {% endblock title %}
{% block content %}
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-6">
            <br>
            <form method="post" action=".">
                {% csrf_token %}
                <!-- account number -->
                <div class="form-group">
                    <label for="username">nickname</label>
                    <input type="text" class="form-control" id="username" name="username" required>
                </div>
                <!-- mailbox -->
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="text" class="form-control" id="email" name="email">
                </div>
                <!-- password -->
                <div class="form-group">
                    <label for="password">Set password</label>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>
                <!-- Confirm password -->
                <div class="form-group">
                    <label for="password2">Confirm password</label>
                    <input type="password" class="form-control" id="password2" name="password2" required>
                </div>
                <!-- Submit button -->
                <button type="submit" class="btn btn-primary btn-block">Submit</button>
            </form>
        </div>
    </div>
</div>
{% endblock content %}

Run the server to test the effect

On the Windows command line, enter:

python manage.py runserver run server

Enter the URL corresponding to our previously configured login or registration in the browser:

http://127.0.0.1:8000/userprofile/register/

  You can view our registration login page.

  So far, we have achieved

1. Blog management system article creation, update, delete and display functions.

2. User registration and login functions

Next, we will continue to update the comment management function.

Tags: Python Django

Posted on Tue, 19 Oct 2021 21:54:37 -0400 by markszy