03.29Django registration, verification, login

package is a package with an init file

directory folder is not


Configure the path from the page to the views, the page is requested, and the views return the page data.

Is there a path from views to the page?

In settings, the root path blog1.urls-->enter blog.urls-->enter the regist path and call the views method-->views page: /blog/regist Inclusion relationship

views function: read database, page jump


Page return parameters:

views: return render(request, 'regist.html' ,{ 'mess' : 'username exists' })
Return page: {{mess}} #django comes with templates


The generated APP is added in the settings by itself


The pycharm command window opens: Ctrl+alt+R

1. makemigrations blog generates 0001 files

2.sqlmigrate bloguser 0001 use this to generate sql statements

3. migrate blog 0001 is executed to the database, there are tables


The page first accesses the background, when accessing the page, directly accessing the page does not work


Forwarding: 1. Refresh the browser and resubmit the form 2. You can only jump within the project 3. The address has not changed, with parameters in the past, rewrite.

Redirection: Take out the returned data and make a new method. Refresh the page, more than one request and response, the request address changes more than once.


1. Root path

path('blog/',include('blog.urls',namespace='user'))

2.
app_name='user'
urlpatterns = [path('show/<int:id>',views.show,name='blogShow'),
    
]
3.
 
 
def show(request,id):
    bloguser=BlogUser.objects.get(pk=id)
    return render(request,'suc.html',{'bloguser':bloguser})
 
 
def regist(request):
    if request.method=='GET':
        return render(request,'regist.html')
    else:
        uname=request.POST.get('username')
        pwd=request.POST.get('pwd')
        bloguser = BlogUser ()
        bloguser.userName=uname
        bloguser.pwd = pwd
        try:
            bloguser.save()
            print ( 'save ok...' )
             return redirect(reverse( 'user:blogShow' , args =[bloguser.id]))#redirect
         except :
             return render(request, 'regist.html' ,{ 'mess' : 'Username exists' })
       


Database username cannot be repeated:

Set unique=True in models.py to create a table or change it directly in the database

Then re-modify the table, first delete the duplicate data

If the input is repeated, save reports an exception, the system crashes, add try to capture the exception

def regist(requset):
    if requset.method=='GET':
        return render(requset,'regist.html')
    else:
        uname=requset.POST.get('username')
        pwd=requset.POST.get('pwd')
        bloguser = BlogUser ()
        bloguser.userName=uname
        bloguser.pwd = pwd
        try:
            bloguser.save()
            print ( 1 )
             return redirect(reverse( 'heihei:haha' , args =[bloguser.id]))   # app_name:name path: haha ​​under heihei is not a page, you can jump to the page, but it is not good to take parameters, write a New method,
             # args is to pass parameters, pass parameters to the past
 except :
             return render(requset, 'regist.html' ,{ 'mess2' : 'The user name has a pro!' })        
It's too late, and it's time to register to report a duplicate exception.



用ajax捕获重复异常:用jQuery实现,简单,用JavaScript也可以实现,麻烦

使用js文件,放在静态文件里。template里,是外面,所有app都能用,放blog2里,别的不能用。有mini版全是英文jQuery.min.js

创建文件夹static,不是package包,他会生成init文件。

在settings配置静态文件和路径:

STATICFILES_DIRS=[#这是目录,路径和目录建立映射关系,如果路径和目录是一样名字,容易看出来你的目录结构
    os.path.join(BASE_DIR, 'static')    
]
STATIC_URL='/static/'#路径   




STATIC_URL='/static/'   #前面有杠就是根路径,没杠是当前路径

http://127.0.0.1:8000/  是根路径
 
 

用ajax   把jQuery拿进来

AJAX传输数据格式有三种:HTML、json、xml

有$.ajax、$.post、$.get三种方式。

网站和后台交互基本都是ajax,很少用表单了。

 
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <script type="text/javascript" src="/static/js/jquery-1.11.1%20.js"></script>{% comment %}#放入jquery文件{% endcomment %}
    <script type="text/javascript">
        $(function () {{% comment %}ajax异步请求,实现鼠标移开的效果{% endcomment %}
            $('#username'){% comment %}或者'input[name="username"]'{% endcomment %}.blur(function () {{% comment %}光标划过用户名{% endcomment %}
                //失去光标获取用户名
                var uname=$(this).val();{% comment %}获取用户名的值{% endcomment %}
                var csrftoken=$("input[name='csrfmiddlewaretoken']").val(){% comment %}#获取token的值{% endcomment %}
                $.ajax({//用ajax或post实现都可以,因为有了光标移开,所以添加js,用ajax简单
                    url: '/blog2/hasname',//路径到后台
                    type: 'post',//请求方式

                    data: {'uname': uname,'csrfmiddlewaretoken':csrftoken},{% comment %}用的是json格式,将获取的用户名和token通过ajax以键值对形式将键和值传给后台{% endcomment %}
                    success:function (result) {
                        //alert(result)
                        $('#mess').html(result){% comment %}把ajax请求回来的值放在html里{% endcomment %}
                    }
                })
            })
        })
    </script>
</head>
<body>
<form method="post">
    {% csrf_token %}{% comment %}也可以在这加onblur{% endcomment %}
    用户名:<input type="text" name="username" id="username"><span id="mess">{{ mess2 }}</span><br>
    密码:  &nbsp;<input type="password" name="pwd"><br>
    <input type="submit" value="注册">
</form>
</body>
</html>

在后台创建hasname函数:


from django.views.decorators.csrf import csrf_protect#导入csrf
@csrf_protect
def hasname(request):
    username=request.POST.get('uname')#后台接受ajax发送过来的用户名
    bloguser=BlogUser.objects.filter(userName=username)#返回的是set集合,所以都不是none,筛选数据库用户名和输入用户名相同的,返回一个对象集合
    if len(bloguser)>0:#用长度
        return HttpResponse('<font color="red">用户名有啦!<font>')#返回结果
    else:
        return HttpResponse('<font color="blue">可用</font>')


登录:






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325522197&siteId=291194637