django实现登陆注册功能

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

大笑

学习了好久django,今天才把登陆注册总结一下,不足之处还希望多多指出哦!

先把我实现的效果截图给大家:

1.基础创建步骤不多讲,最终的框架结构如下:

2.在settings.py中写好相对应的代码,例如数据库的设置,模板文件的设置等等。

3.urls.py

from django.conf.urls import urlfrom django.contrib import adminfrom blog import views urlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'^$',views.index),    url(r'^regist/$',views.regist),    url(r'^login/$',views.login),    url(r'^logout/$',views.logout),    url(r'^article/$',views.article),    url(r'^(?P<id>\d+)/$',views.detail,name='detail'), ]

4.views.py(部分笔记已在代码中给出)

# -*- coding:utf-8 -*-from django.shortcuts import render,redirectfrom django.http import HttpResponse,Http404from .models import *from django.contrib import authfrom django import forms    #导入表单from django.contrib.auth.models import User   #导入django自带的user表 class UserForm(forms.Form):    username = forms.CharField(label='用户名',max_length=100)    password = forms.CharField(label='密_码',widget=forms.PasswordInput())# Django的form的作用:# 1、生成html标签# 2、用来做用户提交的验证# Form的验证思路# 前端:form表单# 后台:创建form类,当请求到来时,先匹配,匹配出正确和错误信息。def index(request):    return render(request,'index.html') def regist(request):    if request.method == 'POST':        uf = UserForm(request.POST)  #包含用户名和密码        if uf.is_valid():            #获取表单数据            username = uf.cleaned_data['username']  #cleaned_data类型是字典,里面是提交成功后的信息            password = uf.cleaned_data['password']            #添加到数据库            # registAdd = User.objects.get_or_create(username=username,password=password)            registAdd = User.objects.create_user(username=username, password=password)            # print registAdd            if registAdd == False:                return render(request,'share1.html', {'registAdd': registAdd, 'username': username})             else:                # return HttpResponse('ok')                return render(request,'share1.html', {'registAdd': registAdd})                # return render_to_response('share.html',{'registAdd':registAdd},context_instance = RequestContext(request))    else:        # 如果不是post提交数据,就不传参数创建对象,并将对象返回给前台,直接生成input标签,内容为空        uf = UserForm()    # return render_to_response('regist.html',{'uf':uf},context_instance = RequestContext(request))    return render(request,'regist1.html', {'uf': uf})   def login(request):    if request.method == 'POST':        username = request.POST.get('username')        password = request.POST.get('password')        print username,password        re = auth.authenticate(username=username,password=password)  #用户认证        if re is not None:  #如果数据库里有记录(即与数据库里的数据相匹配或者对应或者符合)            auth.login(request,re)   #登陆成功            return redirect('/',{'user':re})    #跳转--redirect指从一个旧的url转到一个新的url        else:  #数据库里不存在与之对应的数据            return render(request,'login.html',{'login_error':'用户名或密码错误'})  #注册失败    return render(request,'login.html')  def logout(request):    auth.logout(request)    return render(request,'index.html')  def article(request):    article_list = Article.objects.all()    # print article_list    # print type(article_list)    #QuerySet是一个可遍历结构,包含一个或多个元素,每个元素都是一个Model实例    #QuerySet类似于Python中的list,list的一些方法QuerySet也有,比如切片,遍历。    #每个Model都有一个默认的manager实例,名为objects,QuerySet有两种来源:通过manager的方法得到、通过QuerySet的方法得到。mananger的方法和QuerySet的方法大部分同名,同意思,如filter(),update()等,但也有些不同,如manager有create()、get_or_create(),而QuerySet有delete()等    return render(request, 'article.html',{'article_list': article_list}) def detail(request,id):    # print id    try:        article = Article.objects.get(id=id)        # print type(article)    except Article.DoesNotExist:        raise Http404    return render(request,'detail.html',locals())  

5.models.py

# -*- coding:utf-8 -*-from __future__ import unicode_literalsfrom django.db import models class Article(models.Model):    title = models.CharField(u'标题',max_length=256)    content = models.TextField(u'内容')    pub_date = models.DateTimeField(u'发表时间', auto_now_add=True, editable = True)    update_time = models.DateTimeField(u'更新时间',auto_now=True, null=True)      def __unicode__(self):  # 在Python3中用 __str__ 代替 __unicode__        return self.title  # Create your models here.

6.这里,我用的django自带的user表,所以在models.py中就没有另外创建user表

7.index.html

<html lang="en"><head>    <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content="A layout example that shows off a blog page with a list of posts.">     <title>小说库</title>    <link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/pure-min.css">    <link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/grids-responsive-min.css">    <link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/blog.css"> </head><body><div id="layout" class="pure-g">    <div class="sidebar pure-u-1 pure-u-md-1-4">        <div class="header">            <h1 class="brand-title"><a href="#"> wuli 小说</a></h1>            <h2 class="brand-tagline">Life is short and I need Python</h2>            <nav class="nav">                <ul class="nav-list">                    <li class="nav-item">                            {% if user.is_authenticated %}                                <a class="button-success pure-button" href="/article/">{{ user.username }}</a>                                <a class="button-success pure-button" href="/logout/">退出</a>                            {% else %}                                <a class="button-success pure-button" href="/regist/">注册</a>                                <a class="button-success pure-button" href="/login/">登录</a>                            {% endif %}                    </li>                 </ul>            </nav>        </div>    </div>      <div class="content pure-u-1 pure-u-md-3-4">        <div>             {% block content %}            {% endblock %}         </div>    </div></div>  </body></html>

8.regist1.html

{% extends 'index.html' %} {% block content %}    <h1>注册页面</h1>{#    # Django的form的作用:#}{## 1、生成html标签#}{## 2、用来做用户提交的验证#}    <form method="POST" enctype="multipart/form-data">{#        <!--{% csrf_token %}-->#}        {{uf.as_p}}        <input type="submit" value="OK" />    </form>{#    <a href="http://127.0.0.1:8000/login">登陆</a>#}{% endblock %}

9.login.html

{% extends 'index.html' %} {% block content %} <div>        <form action="/login/" method="POST">            <h2>Please sign in </h2>            <input type="text" name="username" />            <input type="password" name="password" />            <button type="submit">Sign in </button>            <p style="color: red">{{ login_error }}</p>        </form></div> {% endblock %} 

10.share1.html

{% extends 'index.html' %} {% block content %} {{registAdd}} <br>================<br>{% if username %}注册失败{{ username }}已存在<a href="http://127.0.0.1:8000/regist">注册</a>{% else %}注册成功!<a href="http://127.0.0.1:8000/login">登陆</a>{% endif %} {% endblock %}

11.article.html

{% extends 'index.html' %} {% block content %} <h2>小说列表</h2>{% for article in article_list %}    <h3><a href="{% url 'detail' id=article.id %}">{{ article.title }}</a></h3>{% endfor %} {% endblock %}

12.detail.html

{% extends 'index.html' %} {% block content %} <h2>{{ article.title }}</h2> {{ article.content }} {% endblock %}

13.自己在数据库中插入的article

14.django自带的user表注意事项:

15.OK!

点这里可以跳转到人工智能网站