开发者

Validation on ModelForm

开发者 https://www.devze.com 2023-03-09 08:57 出处:网络
I am trying to do custom validation on a form. However, the clean_ method is not working (no matter what I try). This is what I currently have --

I am trying to do custom validation on a form. However, the clean_ method is not working (no matter what I try). This is what I currently have --

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    

And in views --

def getting_started_pic(request):
    if request.method == 'POST':
        profile.avatar = request.FILES['avatar']
        profile.save()
        return render_to_response (...)

What am I missing in order to get the clean_avatar method to 'work'? (Currently, it is as开发者_StackOverflow社区 if it weren't there). Thank you.


I don't see an instance of your ProfilePictureForm anywhere? I'll assume profile is your instance. If that is the case, you need to call is_valid() on your ModelForm instance for your clean_avatar to get called:

def getting_started_pic(request):
  if request.method == 'POST':
    profile.avatar = request.FILES['avatar']
    if profile.is_valid():
        profile.save()
    return render_to_response (...)


Usual model forms workflow is::

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
0

精彩评论

暂无评论...
验证码 换一张
取 消