Form:https://docs.djangoproject.com/en/2.0/ref/forms/api/
ModelForm: https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/
Form
models.py
from django.db import models
class UserInfo(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=32)
roles = models.ManyToManyField(to='Role')
depart = models.ForeignKey('Department')
class Role(models.Model):
title = models.CharField(max_length=32)
def __str__(self):
return self.title
class Department(models.Model):
dep = models.CharField(max_length=32)
def __str__(self):
return self.dep
views.py
from django.shortcuts import render,HttpResponse
from django import forms
from django.forms import widgets
from . import models
class UserInfoForm(forms.Form):
name = forms.CharField(
required=True,
error_messages={'required':'Username cannot be null'},
widget=widgets.TextInput(attrs={'placeholder':'用户名','class':'form-control'})
)
password = forms.CharField(
required=True,
error_messages={'required':'Password cannot be null'},
widget=widgets.TextInput(attrs={'placeholder':'密码','class':'form-control'})
)
depart = forms.ModelChoiceField(queryset=models.Department.objects.all())
roles = forms.ModelMultipleChoiceField(queryset=models.Role.objects.all())
def user(request):
if request.method == 'GET':
form = UserInfoForm()
return render(request,'index.html',{'form':form})
form = UserInfoForm(data=request.POST)
if form.is_valid():
roles = form.cleaned_data.pop('roles') # when adding M2M fields, this has to be done first
user_obj = models.UserInfo.objects.create(**form.cleaned_data)
user_obj.roles.add(*roles)
return HttpResponse('添加成功')
return render(request,'index.html',{'form':form})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" novalidate>
{% csrf_token %}
<p>{{ form.name }} {{ form.errors.name.0 }}</p>
<p>{{ form.password }} {{ form.errors.password.0 }}</p>
<p>{{ form.depart }} {{ form.errors.depart.0 }}</p>
<p>{{ form.roles }} {{ form.errors.roles.0 }}</p>
<input type="submit" value="提交">
</form>
</body>
</html>
ModelForm
views.py
from django.shortcuts import render,HttpResponse
from django import forms
from django.forms import widgets
from . import models
class UserInfoForm(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = '__all__'
def user(request):
if request.method == 'GET':
form = UserInfoForm()
return render(request,'index.html',{'form':form})
form = UserInfoForm(data=request.POST)
if form.is_valid():
form.save() # the save method will save all kinds of fields
return HttpResponse('添加成功')
return render(request,'index.html',{'form':form})
ModelForm's save() method will be more efficient in some cases.
Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model.
Notice:
This save()
method accepts an optional commit
keyword argument, which accepts either True
or False
. If you call save()
with commit=False
, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save()
on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit
is True
by default.
Another side effect of using commit=False
is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False
when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.
To work around this problem, every time you save a form using commit=False
, Django adds a save_m2m()
method to your ModelForm
subclass. After you’ve manually saved the instance produced by the form, you can invoke save_m2m()
to save the many-to-many form data.