chuck_sum
chuck_sum

Reputation: 111

django clean method on model form

I've only used the out-of-the box Django forms API. I'm now trying to validate form field data on a django model form - update_profile. My model contains the validators, where (and why) do I perform a clean or save in order to provide field level messaging for the end-user? Currently, my error dict is empty.

class CustomUser(AbstractBaseUser):
    email = models.EmailField(_('email'), max_length=254, unique=True)
    username = models.CharField(_('username'),max_length=15, unique=True,
        validators=[RegexValidator('^[_a-z0-9]+$', message= '15 characters max. Username must be a-z(lowercase), 0-9, can contain underscore', code='invalid_username')])
    about_me = models.CharField(_('about me'),max_length=140)
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=50, blank=True)
        phone_regex = RegexValidator(regex='^\+?1?\d{9,15}$', message='Phone number must be between 9 and 15 digits')
    phone_number = models.CharField(_('phone_number'),max_length=15,  blank=True,
        validators=[phone_regex])
    is_active = models.BooleanField(_('active'), default=False)
    is_staff = models.BooleanField(_('staff'), default=False)

views.py

def update_profile(request):
    user=request.user
    if user.is_authenticated == True:
    if request.method == 'POST':
        form = CustomUserChangeForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, 'Your profile was successfully updated.')
            return redirect('update profile')
        else:
            messages.error(request, "Please correct the error below.")

    form = CustomUserChangeForm(instance=user)
    return render(request, 'profile.html', {'form': form})

forms.py

class CustomUserChangeForm(forms.ModelForm):

class Meta:
    model = CustomUser
    fields = ('email', 'first_name', 'last_name', 'about_me','phone_number')

Upvotes: 0

Views: 300

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You need to return the invalid form to the user. You should put your instantation of the empty form into an else block so it only happens on GET.

if request.method == 'POST':
    form = CustomUserChangeForm(request.POST, instance=user)
    if form.is_valid():
        ...
else:
    form = CustomUserChangeForm(instance=user)
return render(request, 'profile.html', {'form': form})

Now in the template {{ form.errors }} will display your validation errors.

Upvotes: 1

catavaran
catavaran

Reputation: 45575

The problem is in this code. You discard previously validated form, create new form and pass it to the template.

form = CustomUserChangeForm(instance=user)
return render(request, 'profile.html', {'form': form})

Upvotes: 1

Related Questions