数据模型
from django.db import models class userinfo(models.Model): username = models.CharField(max_length=10,unique=True) password = models.CharField(max_length=50) def __str__(self): return self.username
视图
from django.shortcuts import render,render_to_response from django.http import HttpResponse from .models import * # Create your views here. def index(request): return render(request,'index.html') def register(request): return render(request,'register.html') def adduser(requset): uname = requset.POST['user'] upwd = requset.POST['pwd'] try: usr = userinfo() usr.username=uname usr.password=upwd usr.save() #userinfo.objects.get_or_create(username=uname,password=upwd) msg='user create success!' all = userinfo.objects.all() return render(requset, 'info.html', {'msg': msg, 'all': all}) except Exception as e: #return render(requset,'info.html',{'msg':e,'all':all}) return HttpResponse({'<html>数据重复了<a href="/"><h2>返回</h2></a></html>'},e)
项目的url
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'',include('person.urls')), ]
APP的url
from django.conf.urls import include, url from django.contrib import admin from . import views as vv urlpatterns = [ url(r'^register/$',vv.register), url(r'^adduser/$',vv.adduser), url(r'',vv.index), ]
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> <h1>Welcome</h1> <a href="/register/"><h2>注册</h2></a> </body> </html>
register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> <form action="/adduser/" method="POST"> {% csrf_token %} 账号:<input type="text" name="user"><br> 密码:<input type="password" name="pwd"><br> <input type="submit" value="提交"> </form> </body> </html>
info.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Info</title> </head> <body> <h2>{{ msg }}</h2> <p>到目前为止所有的注册用户列表为:</p> <li> {% for i in all %} <ol>{{ i.username }}</ol> {% endfor %} </li> <a href="/">点击跳转</a> </body> </html>
index主页截图
register注册页截图
正确提交截图
错误提交截图
(比如用户重复),实现主要在视图中的adduser方法中,通过except Exception as e:return HttpResponse实现