而不是显示我的表单错误,我得到错误页面说“异常值:列project_id,employee_id不是唯一的”。如何才能显示我的表单错误? (应该显示类似的内容:项目和员工组合已存在于成员资格中“)
模型:
class Project(models.Model):
projecttype = models.ForeignKey(Projecttype)
department = models.ForeignKey(Department)
members = models.ManyToManyField(Employee, through='Membership')
def __unicode__(self):
return self.projecttype.name
class Membership(models.Model):
project = models.ForeignKey(Project)
department = models.ForeignKey(Department)
employee = models.ForeignKey(Employee)
role = models.ManyToManyField(Role, blank=True, null=True)
class Meta:
unique_together = (("program", "employee",),)
查看:
def employee_edit(request, employee_id):
i = get_object_or_404(Employee, pk=employee_id)
MembershipForm = make_membership_form(i)
MembershipFormSet = modelformset_factory(Membership, form=MembershipForm)
f = MembershipFormSet(queryset=Membership.objects.filter(employee=i),)
if request.method == "POST":
f = MembershipFormSet(request.POST)
m = f.save(commit=False)
for instances in m:
instances.employee = i
instances.department = i.department
if f.is_valid():
instances.save()
f.save_m2m()
return render_to_response('testdb/edit.html', {'item': i, 'formset': f, }, context_instance=RequestContext(request))
def make_membership_form(i):
class MembershipForm(forms.ModelForm):
project = forms.ModelChoiceField(queryset=Project.objects.filter(department=i.department))
class Meta:
model = Membership
exclude = ('department', 'employee')
unique_together = (("project", "employee",),)
return MembershipForm
答案 0 :(得分:0)
在返回表单之前,您可以捕获save
对表单的调用和inject a custom error中抛出的异常。像这样(非常未经测试):
from django.db import IntegrityException
...
formset = MembershipFormSet(request.POST)
for form in formset:
try:
form.save(commit=False)
catch IntegrityException:
errors = form._errors.setdefault("field", ErrorList())
errors.append(u"error")