0
我想使用具有自定義窗體的模型窗體集。我對GET使用了不同的視圖,對POST函數使用了不同的視圖,導致我的html頁面由三個不同的模型構成。我的模型是一個模型Formset驗證錯誤
class Image(models.Model):
customer = models.ForeignKey(Customer)
doctor = models.ForeignKey(Doctor)
date = models.DateField()
desc = models.CharField(max_length=30)
type = models.CharField(choices=TITLE,max_length=20)
image = models.ImageField(upload_to='/pictures/', verbose_name='Image')
XRAY=[
('---------','---------'),
('PA Ceph', 'PA Ceph'),
('Lateral Ceph', 'Lateral Ceph'),
('Panoramic', 'Panoramic'),
]
class XrayImageForm(ModelForm):
desc = forms.ChoiceField(choices=XRAY,required=True, widget=Select(attrs={"class":"form-control input-sm"}))
class Meta:
model = Image
exclude = ('customer', 'date','type', 'doctor',)
widgets = {
'desc':Select(attrs={'class':'form-control input-sm'}),
'date': TextInput(attrs={'class':'form-control input-sm datepicker input-append date',
'readonly':''}),
}
def save(self, commit=True):
model = super(XrayImageForm, self).save(commit=False)
model.desc = self.cleaned_data['desc'];
if commit:
model.save()
return model
class InternalImageForm(ModelForm):
desc = form.ChoiceField(....) # I have to do this cause different ModelForm has different choices in the desc field
class Meta:
model = Image
exclude = ('customer',)
我GET觀點如下
def images(request, customer_id):
images = Image.objects.all().order_by('date')
pictures = {}
for image in images:
date = image.date.stformat("%d/%M/%Y")
if not pictures.has_key(date):
pictures[date] = {image.title:[image,]}
else:
if pictures[date].has_key(image.title):
pictures[date][image.title].append(image)
else:
pictures[date] = {image.title:[image,]}
xray_formset = modelformset_factory(Image, form=XrayImageForm,extra=4)
xray_formset(queryset=Image.objects.none())
internal_form = InternalImageForm()
external_form = ExternalImageForm()
args = dict(pictures=pictures, xray_formset=xray_formset, internal_form=internal_form, external_form=external_form, customer_id=customer_id)
return render_to_response('customer/images.html', args, context_instance=RequestContext(request))
我希望讓他們按日期過濾,並通過一個標題中各個日期(不同的圖像可能有相同的標題,和同日)
我的帖子觀點
def upload_xray(request, customer_id):
customer = Customer.objects.get(pk=customer_id)
if request.method == 'POST':
XrayFormSet = modelformset_factory(Image, form=XrayImageForm, extra=4)
xray_formset = XrayFormSet(request.POST, request.FILES)
print xray_formset
return redirect('customer-images', customer_id=customer_id)
但是當我發佈的數據,我收到了
ValidationError
Exception Value:[u'ManagementForm data is missing or has been tampered with']
我沒有做任何實際的保存,只是想看看它是否工作。此外,所有字段都是必填字段,但我並未填充頁面中的所有字段(假設用戶可以上傳4張圖片,但他可能不想)。希望我有點感覺...爲什麼是這個錯誤?
謝謝你的作品。但它現在不會驗證。我呈現5個表單formset,但只有一個被使用時,其他人不會驗證。這是假定的行爲? – Apostolos
如果發佈的數據與初始數據匹配,那麼Django將允許空表單。如果空表單的值發生了變化,那麼Django會驗證它們。 – Alasdair
初始值爲空仍然不會讓我 – Apostolos