我正在尝试对表单进行自定义验证。但是,clean_
方法不起作用(无论我尝试什么)。这就是我目前所拥有的 -
from django.forms import ModelForm
from django import forms
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
avatar = models.ImageField(upload_to='images/%Y/%m/%d', blank=True)
class ProfilePictureForm(ModelForm):
class Meta:
model = UserProfile
fields = ('avatar',)
def clean_avatar(self):
try:
raise # this is just to see if the clean_ is working
except:
raise
并在views
-
def getting_started_pic(request):
if request.method == 'POST':
profile.avatar = request.FILES['avatar']
profile.save()
return render_to_response (...)
为了让clean_avatar
方法“工作”,我缺少什么? (目前,好像它不在那里)。谢谢。
答案 0 :(得分:1)
我没有在任何地方看到您的ProfilePictureForm的实例?我假设个人资料是你的实例。如果是这种情况,您需要在ModelForm实例上调用is_valid()以便调用clean_avatar:
def getting_started_pic(request):
if request.method == 'POST':
profile.avatar = request.FILES['avatar']
if profile.is_valid():
profile.save()
return render_to_response (...)
答案 1 :(得分:0)
通常的模型表单工作流程是::
def some_view(request):
profile = request.user.profile # or some other way to get user's profile
if request.method == 'POST':
form = ProfilePictureForm(request.POST, request.FILES, instance=profile)
else:
form = ProfilePictureForm(instance=profile)
if form.is_valid():
form.save()
# Redirect somewhere
# Return failed form