zoukankan      html  css  js  c++  java
  • DjangoWeb: 快速实现注册登录

    1.首先在Models创建用户表(设计数据库) 然后同步数据库

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

    2.创建视图(逻辑层)

    打开view文件在view中创建表单和view层方法

    #创建表单
    from django import forms
    from models import User
    class UserForm(forms.Form):
        username=forms.CharField(label='用户名:',max_length=100)
        password=forms.CharField(label='密码:',widget=forms.PasswordInput())
        email=forms.EmailField(label='电子邮件:')
    
    #Create your views here
    def register(request):
        if request.method=='POST':
            uf=UserForm(request.POST)
            if uf.is_valid():
                #获取表单信息
                username=uf.cleaned_data['username']
                password=uf.cleaned_data['password']
                email=uf.cleaned_data['email']
                #将表单写入数据库
                user=User()
                user.username=username
                user.password=password
                user.email=email
                user.save()
    
                return render_to_response('success.html',{'username':username})
        else:
            uf=UserForm()
            return render_to_response('register.html',{'uf':uf})

    在这个逻辑中主要做了几件事情,首页提供给用户一个注册的页面(register.html)UserForm类定义了表单在注册页面上的显示。接受用户填写的表单信息,然后将表单信息写入数据库,最后返回给用户一个注册成功的页面(success.html)

    3.创建前端页面(创建模板页面)

    register.html
    <!
    DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>用户注册</title> </head> <style type="text/css"> body{color:#efd; background:#435; padding:0 5em; margin:0} h1{padding:2em lem; background:#675} h2{color:#bf8; border-top:lpx dotted #fff; margin-top:2em} p{margin: lem 0} </style> <body> <h1>注册页面:</h1> <form method='post' enctype="multipart/form-data"> {{ uf.as_p }} <input type="submit" value="ok"/> </form> </body> </html>
    success.html
    <!
    DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <h1>恭喜{{username}},注册成功!</h1> </body> </html>

    4.设置模版路径

    5.设置URL

    遇到的问题,在注册界面进去之后出现类这样的问题:

    Forbidden (403)
    
    CSRF verification failed. Request aborted.
    Help
    
    Reason given for failure:
    
        CSRF token missing or incorrect.
        
    
    In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
    
        Your browser is accepting cookies.
        The view function uses RequestContext for the template, instead of Context.
        In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
        If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
    
    You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
    
    You can customize this page using the CSRF_FAILURE_VIEW setting.

    解决办法:http://www.xiaomastack.com/2014/08/04/djangoformerr/

    感谢这位大哥详细清晰的解答!!

    6.体验注册

    --------------------------------------------------------------------------

    再写一个登录的

    设用户登录的表单,方法和 前端模版

    # 登录
    #定义表单类型
    class UserLoginForm(forms.Form):
        username=forms.CharField(label='用户名',max_length=100)
        password=forms.CharField(label='密码',widget=forms.PasswordInput())
    #登录login
    def login(request):
        if request.method=='POST':
            print("post")
            uf=UserLoginForm(request.POST)
            if uf.is_valid():
                #获取表单信息
                username=uf.cleaned_data['username']
                password=uf.cleaned_data['password']
                #获得的表单和数据库比较
                try:
                    user=User.objects.get(username=username,password=password)
                    print("canget")
                    return render_to_response('success.html',{'username':username})
                except ObjectDoesNotExist:
                    return HttpResponseRedirect('/login/',{'uf':uf},context_instance=RequestContext(request))
        else:
            print("login")
            uf=UserLoginForm()
        return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(request))

    设计表单的前端模板

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>登录</title>
    </head>
    
         <style type="text/css">
             body{color:#efd; background:#435; padding:0 5em; margin:0}
             h1{padding:2em lem; background:#675}
             h2{color:#bf8; border-top:lpx dotted #fff; margin-top:2em}
             p{margin: lem 0}
         </style>
    
    <body>
    <h1>登录页面:</h1>
    <form method='post' enctype="multipart/form-data">
        {% csrf_token %}
        {{ uf.as_p }}
        <input type="submit" value="ok"/>
    </form>
    
    </body>
    </html>

    最后设置路径/配置URL/就OK拉拉

    http://www.xiaomastack.com/2014/08/04/djangoformerr/

  • 相关阅读:
    Java 老兵不死,Kotlin 蓄势待发
    程序员写代码时戴着耳机,在听什么?
    推荐 7 个提升前端编程效率的 VSCode 插件
    去掉烦人的 !=null
    透析!软件开发未来 10 年的 8 个趋势
    10月01日总结
    09月29日总结
    09月28日总结
    09月27日总结
    09月26日总结
  • 原文地址:https://www.cnblogs.com/zzblee/p/4722486.html
Copyright © 2011-2022 走看看