# Django的Form主要具有一下几大功能: # # 生成HTML标签 # 验证用户数据(显示错误信息) # HTML Form提交保留上次提交数据 # 初始化页面显示内容 # forms组件生成HTML标签格式 # class 表名Form(Form): # 字段名 = fields.字段类型( # 初始值, # widgets=widgets.插件(attrs={html属性标签 字典格式}) # )
1.urls.py
url(r'^student', student),
2.models.py
from django.db import models # Create your models here. class Class(models.Model): title = models.CharField(max_length=32) teachers = models.ManyToManyField("Teacher") def __str__(self): return self.title class Teacher(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name class Student(models.Model): username = models.CharField(max_length=16,unique=True) age = models.IntegerField() gender = models.BooleanField() classes = models.ForeignKey("Class") def __str__(self): return self.username
2.form.py
from .models import Student, Class, Teacher # Create your froms here. from django.forms import Form from django.forms import widgets from django.forms import fields class StudentForm(Form): username = fields.CharField()(
widget=widgets.TextInput(attrs={"style":"color:red;"},)
) age = fields.IntegerField() gender = fields.ChoiceField( choices=((1, "男"), (0, "女"),), initial=1, widget=widgets.Select ) classes = fields.IntegerField( initial=1, widget=widgets.Select() )
# 绑定动态数据 def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) self.fields["classes"].widget.choices = Class.objects.all().values_list("id", "title")
4.views.py
from .forms import StudentForm from .models import Student,Class,Teacher def student(request): if request.method == "GET": obj = StudentForm() return render(request, "t1/student.html", locals()) elif request.method == "POST": obj = StudentForm(request.POST) if obj.is_valid(): try: val = obj.clean() print(val) Student.objects.create(username=val["username"], age=val["age"], gender=val["gender"], classes_id=val["classes"]) return HttpResponse(val["username"] + "添加完成") except Exception as e: return HttpResponse("数据错误,请重新输入") else: print(obj.clean()) return HttpResponse("ERROR") else: return HttpResponse("error")
5.student.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/student/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <p>用户名:{{ obj.username }} {{ obj.username.errors }}</p> <p>年 龄:{{ obj.age }}{{ obj.age.errors }}</p> <p>性 别:{{ obj.gender }}</p> <p>班 级:{{ obj.classes }}</p> <input type="submit"value="添加用户"/> </form> </body> </html>