我正在做一个上传图片的应用程序。我需要验证两个字段之一。按文件或URL。我写了这样的代码,但是view方法不会在forms.py中调用clean_image。感谢您的帮助(对不起我的英语不好)
class UploadForm(forms.ModelForm):
image = forms.ImageField(required=False)
url = forms.CharField(max_length=64, required=False)
class Meta:
model = Image
fields = (
'image',
'url'
)
def clean_image(self):
image = self.cleaned_data.get('image')
url = self.cleaned_data.get('url')
if (image != None and url != '') or (image == None and url == ''):
raise forms.ValidationError('Fill one field')
def save(self):
self.clean_image()
new_image = Image.objects.create(
image=self.cleaned_data.get('image'),
url=self.cleaned_data.get('url')
)
return new_image
def upload(request):
if request.method == 'POST':
upload_form = UploadForm(request.POST, request.FILES)
if upload_form.is_valid():
upload_form.save()
return redirect('/')
else:
upload_form = UploadForm()
context = {
'form': upload_form,
}
return render(request, 'upload_page.html', context)
答案 0 :(得分:0)
也许您可以使用clean()
方法:
def clean(self):
cleaned_data = super().clean()
image = cleaned_data.get('image')
url = cleaned_data.get('url')
if not image and not url:
raise forms.ValidationError('Fill either url or image field')
return cleaned_data
并更新模板以显示错误:
{% if form.errors %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}