Form validation using an instance
I am validating an ImageField
in a modelform. What I currently have is working --
# in model
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', 'headline')
def clean_avatar(self):
if not self.cleaned_data['avatar']:
raise forms.ValidationError('Oops, looks like you forgot to attach an image!')
else:
return self.cleaned_data['avatar']
# in views
def getting_started_pic(request):
username = request.session.get('username')
profile = UserPr开发者_JAVA技巧ofile.objects.get(user=username)
if request.method == 'POST':
form = ProfilePictureForm(request.POST, request.FILES)
if form.is_valid():
form = ProfilePictureForm(request.POST, request.FILES, instance = profile)
form.save()
return render_to_response (...)
Note that I am setting the form variable twice, first without the instance and then with the instance. When I defined the form only once (including the instance = profile
) the form world never return None, and thus the form would not properly validate (i.e., self.cleaned_data['avatar'] was always non-empty).
I have two questions related to this:
1 - Why does the (...instance = profile) affect the self.cleaned_data['avatar'] portion?
2 - How could I remove redundancy in this view function?
I don't know if you already checked this, but if your profile instance already has a valid avatar then cleaned_data will show this value if the user didn't enter another value.
精彩评论