当我正在编辑我的表单/ formset并删除一个ContestForm时,在大多数情况下它根本不会改变并且我看到错误“此字段是必需的” 即G。有“Form XYZ”,我将其更改为“----”(空白),提交后显示“此字段为必填项”,如截图所示 Views.py:
def contest_admin(request, contest_slug):
contest = get_object_or_404(Contest, slug=contest_slug)
ontestFormsFormSet = inlineformset_factory(Contest,
ContestForms,
fields=('form', 'main_entry', 'user_modifiable',),
extra=2,
)
contest_desc = ContestDescForm(request.POST or None, instance=contest)
contest_forms = ContestFormsFormSet(request.POST or None, instance=contest)
if request.method == 'POST':
if contest_desc.is_valid() and contest_forms.is_valid():
contest_desc.save()
contest_forms.save()
context = {
...
}
template_name = "contests/admin/_admin.html"
return render(request, template_name, context)
Models.py:
class Contest(models.Model):
name = models.CharField('Contest Name', max_length=100)
slug = models.SlugField(unique=True)
capacity = models.IntegerField('Capacity')
team_size = models.IntegerField('Team size', default=1)
description = models.CharField('Description', max_length=1000)
date_opened = models.DateField('Date opened')
date_registration_closed = models.DateField('Date registration closed')
date_closed = models.DateField('Date closed')
forms = models.ManyToManyField(FormEntry, through='ContestForms')
class ContestForms(models.Model):
contest = models.ForeignKey(Contest, on_delete=models.CASCADE)
form = models.OneToOneField(FormEntry)
main_entry = models.BooleanField('Main entry')
user_modifiable = models.BooleanField('Modifiable')
class Meta:
verbose_name_plural = "ContestForms"
Forms.py:
class ContestDescForm(forms.ModelForm):
widget_attrs = {
'class': "form-control",
'type': 'date',
}
description = CharField(widget=forms.Textarea)
date_opened = DateField(widget=DateInput(attrs={'type': 'date'}))
date_registration_closed = DateField(widget=DateInput(attrs={'type': 'date'}))
date_closed = DateField(widget=DateInput(attrs={'type': 'date'}))
class Meta:
model = Contest
exclude = ('slug', 'forms',)
class ContestFormsForm(forms.ModelForm):
form = ModelChoiceField(required=False, queryset=FormEntry.objects.all())
class Meta:
model = ContestForms
exclude = ()
修改 模板:
<form method="post" action="">
{% csrf_token %}
{{ contest_desc|bootstrap }}
<table>
{{ contest_forms|bootstrap_inline }}
</table>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
答案 0 :(得分:1)
您是否尝试添加空白= True?
class Contest(models.Model):
name = models.CharField('Contest Name', max_length=100,blank=True)
class ContestForms(models.Model):
contest = models.ForeignKey(Contest, on_delete=models.CASCADE,blank=True,null=True)