Table of Contents
注册页面:
登录页面:
恭喜,{{operation}}成功!
Home Backend Development Python Tutorial Django tutorial: Django user registration and login method

Django tutorial: Django user registration and login method

Mar 10, 2017 pm 01:49 PM

This article mainly introduces the relevant information on the Django user registration and login method of the Django tutorial. Friends in need can refer to it

Django is a free open source website framework developed by Python, which can be used Quickly build a high-performance, elegant website!

Learning Django is super hard. It has been so difficult to create the simplest user login and registration interface recently. It has been basically implemented at present. Although the function is very simple, I will make a record and come back later when I learn more deeply. Supplement:

First create the project, go to the directory where the project is located: django-admin startproject demo0414_userauth

Enter the project: cd demo0414_userauth

Create the corresponding app:django-admin startapp account

The structure diagram of the entire project is as shown in the figure

├── account
│ ├── admin.py
│ ├── admin.pyc
│ ├── apps.py
│ ├── init.py
│ ├── init.pyc
│ ├── migrations
│ │ ├ ── 0001_initial.py
│ │ ├── 0001_initial.pyc
│ │ ├── init.py
│ │ └── init.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── demo0414_userauth
│ ├── init.py
│ ├── init.pyc
│ ├── settings.py
│ ├ ── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
├─ ─ manage.py
└── templates
├── register.html
├── success.html
└── userlogin.html

4 directories, 29 files

Then add the app account in the installed_app of the setting file;

Django tutorial: Django user registration and login method

Create a templates folder, which can be placed in the root directory of the project or in the app directory. Generally, it is recommended to place it in the app directory. If you put it in the root directory of the project, you need to set 'DIRS' in TEMPLATES in the setting file: [os.path.join(BASE_DIR,'templates')], otherwise the template cannot be used.

Django tutorial: Django user registration and login method

In addition, because this project has page jump problems, in order to prevent CSRF attacks safely, there are relevant settings in the template. I don't know how to use this thing yet. It is said that adding the tag {% csrf_token %} to the form can be achieved, but I have not succeeded. So don't consider this problem first, comment out the middleware 'django.middleware.csrf.CsrfViewMiddleware' in the seeing

Django tutorial: Django user registration and login method

and then create the corresponding one in the model Add the corresponding program to the database:

class User(models.Model):
 username = models.CharField(max_length=50)
 password = models.CharField(max_length=50)
 email = models.EmailField()
Copy after login

view. Pdb was used for breakpoint debugging. I liked it very much. I liked it very much. If you are not interested, just comment directly.

#coding=utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django.contrib import auth
from models import User

import pdb

def login(request): 
 if request.method == "POST":
  uf = UserFormLogin(request.POST)
  if uf.is_valid():
   #获取表单信息
   username = uf.cleaned_data['username']
   password = uf.cleaned_data['password']   
   userResult = User.objects.filter(username=username,password=password)
   #pdb.set_trace()
   if (len(userResult)>0):
    return render_to_response('success.html',{'operation':"登录"})
   else:
    return HttpResponse("该用户不存在")
 else:
  uf = UserFormLogin()
return render_to_response("userlogin.html",{'uf':uf})
def register(request):
 curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime());
 if request.method == "POST":
  uf = UserForm(request.POST)
  if uf.is_valid():
   #获取表单信息
   username = uf.cleaned_data['username']
   #pdb.set_trace()
   #try:
   filterResult = User.objects.filter(username = username)
   if len(filterResult)>0:
    return render_to_response('register.html',{"errors":"用户名已存在"})
   else:
    password1 = uf.cleaned_data['password1']
    password2 = uf.cleaned_data['password2']
    errors = []
    if (password2 != password1):
     errors.append("两次输入的密码不一致!")
     return render_to_response('register.html',{'errors':errors})
     #return HttpResponse('两次输入的密码不一致!,请重新输入密码')
    password = password2
    email = uf.cleaned_data['email']
   #将表单写入数据库
    user = User.objects.create(username=username,password=password1)
    #user = User(username=username,password=password,email=email)
    user.save()
    pdb.set_trace()
   #返回注册成功页面
    return render_to_response('success.html',{'username':username,'operation':"注册"})
 else:
  uf = UserForm()
return render_to_response('register.html',{'uf':uf})
class UserForm(forms.Form):
 username = forms.CharField(label='用户名',max_length=100)
 password1 = forms.CharField(label='密码',widget=forms.PasswordInput())
 password2 = forms.CharField(label='确认密码',widget=forms.PasswordInput())
 email = forms.EmailField(label='电子邮件')
class UserFormLogin(forms.Form):
 username = forms.CharField(label='用户名',max_length=100)
 password = forms.CharField(label='密码',widget=forms.PasswordInput())
Copy after login

There are a total of 3 pages under the Tempaltes folder:

Register.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>用户注册</title>
</head>
 <style type="text/css">
 body{color:#efd;background:#453;padding:0 5em;margin:0}
 h1{padding:2em 1em;background:#675}
 h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
 p{margin:1em 0}
 </style>
<body>
<h1 id="注册页面">注册页面:</h1>
<form method = &#39;post&#39; enctype="multipart/form-data">
{{uf.as_p}}
{{errors}}
</br>
<input type="submit" value = "ok" />
</form>
</body>
</html>
Copy after login

Userlogin.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>用户注册</title>
</head>
 <style type="text/css">
 body{color:#efd;background:#453;padding:0 5em;margin:0}
 h1{padding:2em 1em;background:#675}
 h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
 p{margin:1em 0}
 </style>
<body>
<h1 id="登录页面">登录页面:</h1>
<form method = &#39;post&#39; enctype="multipart/form-data">
{{uf.as_p}}
<input type="submit" value = "ok" />
</form>
</body>
</html>
Copy after login

Success.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title></title>
</head>
<body>
<form method = &#39;post&#39;>
 <h1 id="恭喜-operation-成功">恭喜,{{operation}}成功!</h1>
</form>
</body>
</html>
Copy after login

Update database:

Django tutorial: Django user registration and login method

Run server:

Django tutorial: Django user registration and login method

Registration page:

Django tutorial: Django user registration and login method

If the registered user has not registered before, you can register successfully and click OK to enter the success interface

Log in page:

Django tutorial: Django user registration and login method

Click OK to enter the success page

This is the end of the tutorial on Django user registration and login. I hope it will be helpful to everyone!

The above is the detailed content of Django tutorial: Django user registration and login method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

See all articles