This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

Creating a Django project

Command line statement to create a project: Django-admin startProject newsManage

It’s a little cleaner to put the templates file inside the templates, so I’ll create the templates first. Command line statement: Django-admin startApp newsModel

Create the model and add the model name to the INSTALLED_APPS file under the setting file, otherwise it will report an error saying that it cannot be found

Add (BASE_DIR, ‘templates’)] to the templates file ‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)]

This is the final rough directory structure

Use the model’s url.py

When you create a project, you come with a urls.py file, which is used to configure the path. It is messy to write all of urls in one url, but it is perfectly solved in a template

Path: newsManage newsManage/urls. Py

urlpatterns = [
    path('admin/', admin.site.urls),
    path(' ', include('newsModel.urls')))Copy the code

Under the newsModel templates to create urls. Py file path: newsManage newsModel/urls. Py

from django.urls import path
from . import views

urlpatterns = [
    path(' ', views.login, name='login')]Copy the code

Path: newsManage newsModel/views. Py

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

Create a login. HTML file under Templates, write the login page (templates are awesome) and run python manage.py runServer to start the server

Loading a static file

Static files_dirs = [os.path.join(BASE_DIR, “static”)] static files_dirs = [os.path.join(BASE_DIR, “static”)]

Page jump

path('/register', views.register, name='register')

Sign up Click this link to go to the register page

Creating a database model

In newsManage/newsManage/init. Py configuration pymysql, no download pymysql need to download

import pymysql
pymysql.install_as_MySQLdb()
Copy the code

Path: newsManage newsModel/models. Py (class name is the name of the table)

class user(models.Model) :username = models.CharField(max_length=30)
    password = models.CharField(max_length=30)
    email = models.EmailField(unique=True, blank=False)
Copy the code

Run the command line, Python manage.py Migrate Python manage.py Makemigbar Python manage.py Migrate newsModel Table names, Names, and rations Python manage.py Migrate newsModel NewsModel_user) admin/ path is a database that can be manipulated directly from the browser

submit

The form submission

The background checks whether the login is successful

def toLogin(request):
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        users = user.objects.all()
        for u in users:
            if u.username == username and u.password == password:
                return redirect("home")
        context = {"msg": "Wrong username or password!"}
        return render(request, "login.html", context)
Copy the code

The ajax submit

data = eval(“(” + data + “)”); Ash is often important, remember to change, otherwise can not get, but it seems that others can not turn…

$.ajax({
    type: 'POST'.url: "{% url 'toLoginByAjax' %}".data: {
        'username': $("#username").val(),
        'password': $("#password").val()
    },
    dataType: 'text'.success: function (data) {
        data = eval("(" + data + ")");
        if (data.code == 0) {window.location.href = "{% url 'home' %}"
        } else{$(".msg").html(data.msg);
                setTimeout(function(){/ / timer
                $(".msg").css("display"."none");// Set the display property of the image to None
            },3000);// Set 3000 milliseconds to 3 seconds}},error: function () {
        console.log("somewhere is wrong")}})Copy the code
def toLoginByAjax(request):
    username = request.POST.get("username")
    password = request.POST.get("password")
    users = user.objects.all()
    for u in users:
        if u.username == username and u.password == password:
            message = {"code": 0."msg": "Successful landing!"}
            return JsonResponse(message)
    message = {"code": 400."msg": "Login failed, wrong username or password!"}
    return JsonResponse(message)
Copy the code

Now you have successfully logged in to the home page (home.html). 🤸 🏻 ♀ ️ 🤸 🏻 ♀ ️ 🤸 🏻 ♀ ️