Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement simple login with Django

Shulou Source: shulou.com Published: 2022-06-01 09:46:31 10月16日 Update

This article mainly shows you "Django how to achieve simple login", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Django how to achieve simple login" this article.

Create a django project

Command line statement to create a project: django-admin startproject newsManage

Putting the templates file in the template will be more concise, so I'll create the template first.

Command line statement: django-admin startapp newsModel

Create the model and add the model name to the INSTALLED_APPS under the setting file, otherwise you will mistakenly report that you can't find it.

Create a templates directory to store html,js,css and other files. Under the setting file, TEMPLATES configures the file path of templates' DIRS': [os.path.join (BASE_DIR, 'templates')]

In the end, this is the general directory structure.

Use the url.py of the model

When you create a project, you will bring a urls.py file, which is used to configure the path. It will look messy if it is written in a urls. Putting it in the template will solve this problem perfectly.

Path: newsManage/newsManage/urls.py

Urlpatterns = [path ('admin/', admin.site.urls), path ('', include ('newsModel.urls'))]

Create the urls.py file path under the newsModel template: newsManage/newsModel/urls.py

From django.urls import pathfrom. Import viewsurlpatterns = [path ('', views.login, name='login')]

Path: newsManage/newsModel/views.py

Def login (request): return render (request, 'login.html')

Create a login.html file under templates, and then write a login page (it smells good with a template)

Run the startup server python manage.py runserver

Load static files

Static is to put static files like css,js loading static files also need to be configured, the last line of setting plus

STATICFILES_DIRS = [os.path.join (BASE_DIR, "static")]

If you quote it in html, you need to add {% load static%} before it.

And then you can quote it.

Page jump

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

Like the registered url above, you can jump through the path or name.

Sign up

Click this link to jump to the registration page.

Create a database model

Configure pymysql in newsManage/newsManage/init.py. If there is no download, you need to download pymysql.

Import pymysqlpymysql.install_as_MySQLdb ()

Path: newsManage/newsModel/models.py (class name is table name)

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

Run the command line to generate the table structure

Python manage.py migratepython manage.py makemigrationspython manage.py migrate newsModel

The database table name is the model name _ class name (newsModel_user)

The admin/ path can manipulate the database directly on the browser.

Submit

Form submission

The background determines whether the login is successful or not

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) ajax submission

Data = eval ("(" + data + ")"); it's very important to remember to change it, otherwise you can't get it, but it seems that others don't have to turn it. $.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 picture to none}, 3000) / / set 3000 milliseconds, that is, 3 seconds}} Error: function () {console.log ("somewhere is wrong")}) 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": "login succeeded!"} return JsonResponse (message) message = {"code": 400, "msg": "login failed Wrong username or password! "} return JsonResponse (message)

You can successfully log in to the home page (home.html)!

The above is all the contents of the article "how to achieve simple login in Django". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Files paths logins models templates that is configuration success content commands data databases articles static pages projects passwords users user names directories Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Huawei NVidia Redmi Microsoft