jdango使用ModelForm表单提交和表单验证
标签: jdango使用ModelForm表单提交和表单验证
2024-08-13 16:49:10 246浏览
jdango使用ModelForm表单提交和表单验证,链接数据库,app注册,修改中文
settings.xml修改中文
LANGUAGE_CODE = 'zh-hans'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',#引入自己的app模块
]
#数据库 DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'python_emp',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
urls.xml
from django.urls import path
from app01 import views as app01views
urlpatterns = [
path('users/list', app01views.users_list),
path('users/toadd', app01views.to_users_add),
path('users/save', app01views.users_save ),
path('users/del/<int:id>', app01views.users_del ),
]
models.xml
from django.db import models # Create your models here. ''''部门''' class Dep(models.Model): #id默认自动生成自增长 dname=models.CharField(max_length=255,verbose_name='部门名称') def __str__(self): return self.dname '''员工''' class Users(models.Model): #id默认自动生成自增长 realname=models.CharField(max_length=255,verbose_name='姓名') uname=models.CharField(max_length=255,verbose_name='用户名') upass=models.CharField(max_length=255,verbose_name='密码') age=models.IntegerField(verbose_name='年龄') money=models.DecimalField(verbose_name='余额',max_digits=10,decimal_places=2,default=0) cts=models.DateField(verbose_name='创建时间') # 部门外键自动加_id就是dep_id, # on_delete=models.CASCADE级联删除 dep=models.ForeignKey(to='Dep' ,to_field='id',on_delete=models.CASCADE,verbose_name='部门' ) #on_delete=models.SET_NULL的是删除外键置空 # dep=models.ForeignKey(to='Dep' ,to_field='id',on_delete=models.SET_NULL,null=True,blank=True) #自动将dep对象封装了,获取.dep.dname sexitems=( (1,'男'), (2,'女') ) sex=models.SmallIntegerField(verbose_name='性别',choices=sexitems) #获取sex男女字符串使用.get_sex_display()方法获取男女
#执行命令生成数据库表 python manage.py makemigrations python manage.py migrate页面
views.xml
from django.shortcuts import render,redirect,HttpResponse from app01.models import Dep,Users from django import forms # Create your views here. def dep_list(request): list=Dep.objects.all() return render(request,"dep_list.html",{'list':list}) def to_dep_add(request): id=request.GET.get('id') if id: obj=Dep.objects.filter(id=id).first() return render(request,"dep_add.html" ,{'obj':obj}) return render(request,"dep_add.html" ) def dep_save(request): dname=request.POST.get('dname') id=request.POST.get('id') print(id,'-'*100) if id: Dep.objects.filter(id=id).update(dname=dname) else: Dep.objects.create(dname=dname) return redirect('/dep/list') def dep_del(request,id): Dep.objects.filter(id=id).delete() return redirect('/dep/list') def users_list(request): list=Users.objects.all() return render(request,"users_list.html",{'list':list}) class UsersModelForm(forms.ModelForm): realname=forms.CharField(max_length=20,required=True,label='姓名') #render_value=True编辑回显密码 upass=forms.CharField( required=True,label='密码',widget=forms.PasswordInput(render_value=True)) class Meta: model=Users #显示全部字段 # fields="__all__" # 排除不显示的字段 # exclude=['upass'] fields=[ 'uname','upass','realname','sex','age','dep','cts','money'] def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for name,field in self.fields.items(): field.widget.attrs={"class":"form-control","required":"required" } def to_users_add(request): id=request.GET.get('id') if id: obj=Users.objects.filter(id=id).first() form= UsersModelForm(instance=obj) return render(request,"users_add.html" ,{'form':form,'id':id}) form= UsersModelForm() return render(request,"users_add.html" ,{'form':form}) def users_save(request ): id=request.POST.get('id') form=None if id: obj=Users.objects.filter(id=id).first() form= UsersModelForm(instance=obj,data=request.POST) else: form= UsersModelForm(data=request.POST) if form.is_valid(): form.save() return redirect('/users/list') return render(request,"users_add.html" ,{'form':form}) def users_del(request,id): Users.objects.filter(id=id).delete() return redirect('/users/list')
表单add.html
{% extends 'layout.html' %}
{% block content %}
<form class="form-horizontal" role="form" method="post" action="/users/save" novalidate>
{% csrf_token %}
<input name="id" value="{{id}}" type="hidden">
{% for t in form %}
<div class="form-group">
<label class="col-sm-2 control-label">{{t.label}}</label>
<div class="col-sm-10">
{{t}}
<p style="color: red">{{t.errors.0}}</p>
</div>
</div>
{% endfor %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">提交</button>
</div>
</div>
</form>
{% endblock %}
list.html
{% extends 'layout.html' %}
{% block content %}
<div>
<a href="/users/toadd" class="btn btn-success">添加</a>
</div>
<table class="table table-striped">
<caption>用户管理</caption>
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>性别</th>
<th>余额</th>
<th>注册日期</th>
<th>部门</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for t in list %}
<tr>
<td>{{t.id}}</td>
<td>{{t.realname}}</td>
<td>{{t.uname}}</td>
<td>{{t.upass}}</td>
<td>{{t.age}}</td>
<td>{{t.get_sex_display }}</td>
<td>{{t.money}}</td>
<td>{{t.cts|date:'Y-m-d'}}</td>
<td>{{t.dep.dname}}</td>
<td>
<a href="/users/toadd?id={{t.id}}" class="btn btn-success">编辑</a>
<a href="/users/del/{{t.id}}" class="btn btn-danger">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
layout.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://cdn.staticfile.net/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.staticfile.net/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.staticfile.net/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <nav class=" navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="#">员工管理系统</a> </div> <div> <ul class="nav navbar-nav"> <li ><a href="/dep/list">部门管理</a></li> <li><a href="/users/list">用户管理</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> 个人中心 <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="#">jmeter</a></li> <li><a href="#">EJB</a></li> </ul> </li> </ul> </div> </div> </nav> <div class="container" style="margin-top:70px;"> {% block content %} {% endblock %} </div> </body> </html>
好博客就要一起分享哦!分享海报
此处可发布评论
评论(0)展开评论
暂无评论,快来写一下吧
展开评论
您可能感兴趣的博客
他的专栏
他感兴趣的技术