Learn Django Learning super hard, recently made a simple user login and registration interface is so difficult, at present is basically realized, although the function is particularly simple but to do a record, after learning in depth to add:
First create the project to the directory where the project is located: django-admin startproject demo0414_userauth
Enter the project: cd demo0414_userauth
Create the appropriate app:django-admin startapp account
The entire project's structure chart
.
├──account
│├──admin.py
│├──admin.pyc
│├──apps.py
│├── init . PY
│├── init . PYc
│├──migrations
││├──0001_initial.py
││├──0001_initial.pyc
││├── in It . 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.py C
│├──wsgi.py
│└──wsgi.pyc
├──manage.py
└──templates
├──register.html
├──success.html └──userlogin.html
4 directories, files
then add the app account in the Installed_app of the setting file;
Creates a templates folder that can be placed under the project's root directory or in the app's directory. In general, the promotion is placed in the app's directory. If you drop the root of the project you need to set ' DIRS ' in the setting file templates: [Os.path.join (Base_dir, ' templates ')], you cannot use the template.
In addition, because of the problem of page jump in this project, in order to prevent CSRF attacks, a template has the relevant settings. I'm not using this at the moment, and it's said that adding the label {% Csrf_token%} to the form form can be done, but I didn't succeed. So let's not think about this, put the middleware in seeting ' Django.middleware.csrf.CsrfViewMiddleware ', comment out
and create the appropriate database in model:
class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField()
Add the appropriate program to the view. The PDB was used for breakpoint debugging, and I like it very much. If you're not interested, just comment directly.
#coding =utf-8 fromDjango.shortcutsImportRender,render_to_response fromDjangoImportForms fromDjango.httpImportHttpresponse,httpresponseredirect fromDjango.templateImportRequestContext fromDjango.contribImportAuth fromModelsImportUserImportPdb def login(Request): ifRequest.method = ="POST": UF = userformlogin (Request. POST)ifUf.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):returnRender_to_response (' success.html ',{' Operation ':"Login"})Else:returnHttpResponse ("The user does not exist")Else: UF = Userformlogin ()returnRender_to_response ("Userlogin.html",{' uf ': UF}) def Register(Request):Curtime=time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ());ifRequest.method = ="POST": UF = UserForm (Request. POST)ifUf.is_valid ():#获取表单信息Username = uf.cleaned_data[' username ']#pdb. Set_trace () #try:Filterresult = User.objects.filter (username = username)ifLen (Filterresult) >0:returnRender_to_response (' register.html ',{"Errors":"User name already exists"})Else: Password1 = uf.cleaned_data[' Password1 '] Password2 = uf.cleaned_data[' Password2 '] Errors = []if(Password2! = Password1): Errors.append ("two times the password entered is inconsistent!")returnRender_to_response (' register.html ',{' Errors ': Errors})#return HttpResponse (' Two input password inconsistent!, please re-enter the password ')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 ()#返回注册成功页面 returnRender_to_response (' success.html ',{' username ': Username,' Operation ':"Register"})Else: UF = UserForm ()returnRender_to_response (' register.html ',{' uf ': UF}) class UserForm(forms. Form):Username = forms. Charfield (label=' User name ', max_length= -) Password1 = forms. Charfield (label=' Password ', Widget=forms. Passwordinput ()) Password2 = forms. Charfield (label=' Confirm password ', Widget=forms. Passwordinput ()) email = forms. Emailfield (label=' Email ') class userformlogin(forms. Form):Username = forms. Charfield (label=' User name ', max_length= -) Password = forms. Charfield (label=' Password ', Widget=forms. Passwordinput ())
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>User Registration</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>Registration page:</H1><form method = 'post' enctype= 'multipart/form-data ' >{{uf.as_p}}{{errors}} </br><input type="Submit" value = " ok"/></form></body></ HTML>
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>User Registration</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>Login page:</H1><form method = 'post' enctype= 'multipart/form-data ' >{{uf.as_p}} <input type="Submit" value = "ok"/></ Form></body></html>
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 = 'post' > <H1>Congratulations{{operation}}Success! </H1> </form> </body> </html>
Update Database:
To run the server:
Registration page:
If the registered user has not registered, then can register successfully click OK to enter the success interface
Login page:
Click OK to go to the success page
Django User Login and Registration-Small white tutorial