1.7 ModelForm
-
使用Form
-
创建Form类 + 定义字段
class LoginForm(forms.Form):user = forms.CharField(label="用户名", widget=forms.TextInput)pwd = forms.CharField(label="密码", widget=forms.TextInput)
-
视图
def login(request):if request.method == "GET":form = LoginForm()return render(request, "login.html", {"form": form})form = LoginForm(data=request.POST)if not form.is_valid():# 校验失败return render(request, "login.html", {"form": form})print(form.cleaned_data)# ...return HttpRespon("OK")
-
前端
<form>{% for field in form %}<p>{{ field.label }} {{ field }} {{ field.errors.0 }}</p>{% endfor %} </form>
-
-
使用ModelForm
-
models.py
class UserInfo(models.Model):name = models.CharField(verbose_name="用户名", max_length=32)age = models.IntegerField(verbose_name="年龄")email = models.CharField(verbose_name="邮箱", max_length=128)
-
创建ModelForm
class LoginForm(forms.ModelForm):mobile = forms.CharFiled(label="手机号")class Meta:model = models.UserInfofileds = ["name","age", "mobile"]
-
视图使用
def login(request):form = LoginModelForm()return render(request, "login.html", {"form": form})
-
页面
<form>{% for field in form %}<p>{{ field.label }} {{ field }} {{ field.errors.0 }}</p>{% endfor %} </form>
注意:
-
后续进行增伤改查是基于数据库Models中的某个表,推荐使用:ModelForm;
-
如果要进行表单校验是与数据库的表无关直接使用Form。
-
1.8 ModelForm两个好的地方
1.8.1 初始化数据
-
Form
class LoginForm(BootStrapForm, forms.Form):user = forms.CharField(label="用户名", widget=forms.TextInput)pwd = forms.CharField(label="密码", widget=forms.TextInput)
def login(request):form = LoginForm(initial={"user": "武沛齐", "pwd": "123"})return render(request, "login.html", {"form": form})
-
ModelForm
class LoginModelForm(BootStrapForm, forms.ModelForm):mobile = forms.CharField(label="手机号", widget=forms.TextInput)class Meta:model = models.UserInfofields = ["name", "age", "mobile"]widgets = {"age": forms.TextInput,}labels = {"age": "x2",}def clean_name(self):value = self.cleaned_data['name']# raise ValidationError("....")return value
def login(request):user_object = models.UserInfo.objects.filter(id=1).first()form = LoginModelForm(instance=user_object, initial={"mobile": "武沛齐"})return render(request, "login.html", {"form": form})
1.8.2 新建数据
-
Form组件
def login(request):if request.method == "GET":form = LoginForm(initial={"user": "武沛齐", "pwd": "123"})return render(request, "login.html", {"form": form})form = LoginForm(data=request.POST)if not form.is_valid():return render(request, "login.html", {"form": form})# form.cleaned_data# 手动读取字典,保存至数据库# models.UserInfo.objects.create(name=form.cleaned_data['xx'], pwd=form.cleaned_data['yy'])return HttpResponse("成功")
-
ModelForm组件
def login(request):if request.method == "GET":form = LoginForm()return render(request, "login.html", {"form": form})form = LoginForm(data=request.POST)if not form.is_valid():return render(request, "login.html", {"form": form})form.save() # 自动将数据新增到数据库return HttpResponse("成功")
1.8.3 更新数据
-
Form组件
def login(request):if request.method == "GET":form = LoginForm(initial={"user": "武沛齐", "pwd": "123"})return render(request, "login.html", {"form": form})form = LoginForm(data=request.POST)if not form.is_valid():return render(request, "login.html", {"form": form})# form.cleaned_data# 手动读取字典,保存至数据库# models.UserInfo.objects.create(name=form.cleaned_data['xx'], pwd=form.cleaned_data['yy'])# models.UserInfo.objects.filter(id=1).update(name=form.cleaned_data['xx'], pwd=form.cleaned_data['y'])return HttpResponse("成功")
-
ModelForm组件
def login(request):if request.method == "GET":form = LoginModelForm()return render(request, "login.html", {"form": form})user_object = model.UserInfo.object.filter(id=1).first()form = LoginModelForm(data=request.POST, instance=user_object)if not form.is_valid():return render(request, "login.html", {"form": form})form.save() # 更新id=1return HttpResponse("成功")