Django user authentication and Onetoonefield

Source: Internet
Author: User

Django user authentication You can use Django's own authentication if you don't want to write it.

Preferred Import Module models.py

#!/usr/bin/env python#_*_ Coding:utf8 _*_from __future__ import unicode_literalsfrom django.db import Modelsfrom Django.core.exceptions import ValidationError fromdjango.contrib.auth.models import User

Each user is created in a

Class UserProfile (models. Model):    user = models. Onetoonefield (User)    name = models. Charfield (max_length=64)    school = models. ForeignKey (' School ')    def __unicode__ (self):        return Self.name

The Onetoonefield field is a one-to-one relationship that cannot be repeatedly associated

user authentication

The preferred implementation of a simple access

Major Item urls.py

From django.conf.urls import url,includefrom django.contrib import adminfrom app01 Import viewsurlpatterns = [    url (r ') ^admin/', admin.site.urls),    url (r ' ^$ ', Views.index),]

views.py views.py under APP01.

#!/usr/bin/env python
#_ *_ Coding:utf8 _*_
From django.shortcuts import Render,redirect
Import Models
From Django.core.paginator import Paginator, Emptypage, Pagenotaninteger


def index (Request): return render (Request, ' crm/index.html ')

Under CRM, create the following index.html code:

<! DOCTYPE html>

Visit http://127.0.0.1:8000

Authentication before you can see how the page information is implemented this is often encountered in the actual work how to achieve it step by step realization

views.py

#!/usr/bin/env python#_*_ Coding:utf8 _*_from django.shortcuts import render,redirectimport Modelsfrom Django.core.paginator import Paginator, emptypage, pagenotanintegerfrom app01 import Formsfrom Django.contrib.auth.decorators Import login_required@login_requireddef Index (Request):    return render (Request, ' Crm/index.html ')

Import Module login_required the decorator for validation under the function

Re-visit trial

Jump to http://127.0.0.1:8000/accounts/login/?next=/this link address

Okay, let's write a simple login page.

The URLs code is as follows

From django.conf.urls import url,includefrom django.contrib import adminfrom app01 Import viewsurlpatterns = [    url (r ') ^admin/', admin.site.urls),    url (r ' ^$ ', views.index),    url (r ' ^accounts/login/$ ', views.acc_login), ]

 

The views.py code is as follows:

#!/usr/bin/env python
#_ *_ Coding:utf8 _*_
From django.shortcuts import Render,redirect,httpresponseredirect
Import Models
From Django.core.paginator import Paginator, Emptypage, Pagenotaninteger
From APP01 Import Forms
From django.contrib.auth.decorators import login_required
From Django.contrib.auth Import authenticate,login,logout

@login_requireddef Index (Request): return render (Request, ' crm/index.html ') def acc_login (request): if Request.method = = ' POST ': print (Request. POST) user = Authenticate (username=request. Post.get (' username '), password=request. Post.get (' password ')) if user is not None: login (request,user) return Httpresponseredirect ('/') else: Login_err = "wrong username or password!" return render (Request, ' crm/login.html ', {' Login_err ': Login_err}) return render (Request, "crm/login.html")

  

Create template HTML index.html

The index.html code is as follows

<! DOCTYPE html>

The login.html code is as follows

{% extends ' crm/index.html '%} {% block Page-container%}    <form action= "" method= "post" > {% csrf_token%}   Username: <input type= "text" name= "Username" >   Password: <input type= "Password" name= "Password" >            <input type= "Submit" value= "Log Me in" >    {% if Login_err%}    <div style= "color:red" >{{login_err}}</div>    #前端判断错误 If the contents of the views are displayed incorrectly    {% ENDIF% }    </form>{% endblock%}]

Okay, we've implemented Access user restrictions

http://127.0.0.1:8000 automatically jumps to

We enter the correct username and password to jump to the index.html page

user = Authenticate (username=request. Post.get (' username '),                            password=request. Post.get (' password '))        if user is not None:            login (request,user)            return Httpresponseredirect ('/')

Show user name login successful name how to display and exit the system

Show login successful name needs to be displayed on the front

<! DOCTYPE html>{% if request.user.is_authenticated%}<span>{{request.user.userprofile.name}}</span>{% Else %} <span> Login/register </span> {% endif%}</div><div><a href= "/accounts/logout/" > Exit system </a></div>{% Endblock%}</body>

Look at the Red Display section

Exit the system code look at the yellow part of the front

The URL code is as follows

From django.conf.urls import url,includefrom django.contrib import adminfrom app01 Import viewsurlpatterns = [    url (r ') ^admin/', admin.site.urls),    url (r ' ^$ ', views.index),    url (r ' ^accounts/login/$ ', views.acc_login),    URL (r ' ^accounts/logout/$ ', views.acc_logout),]

The views.py code is as follows:

def acc_logout (Request):    logout (Request)    return Httpresponseredirect ('/')

Click to exit the system to jump to

<a href= "/accounts/logout/" > Exit system </a>

def acc_logout (Request):    logout (Request)    return Httpresponseredirect ('/') Jump to login page


Django user authentication and Onetoonefield

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.