Hi guys,

i am working on user CRUD. I am using one form for user creation and update. When user is initially created it is ok to perform password validation - users must have password, but in my edit form i want to have a logic like: when nothing is entered don't do anything, when user enters something in password field override old password. The problem is that password field is always mandatory. Is there some way to disable validation according to my logic.

This is my form

from django import forms
from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

class Meta:
    model = User
    exclude = ('last_login', 'date_joined')

def save(self, commit=True):
    user = super(UserForm, self).save(commit=False)
    password = self.cleaned_data["password"]
    if user.pk:
        if password:
            user.set_password(self.cleaned_data["password"])
    else:
        user.set_password(self.cleaned_data["password"])
    if commit:
        user.save()
    return user

and my view

@login_required
@user_passes_test(lambda u: u.groups.filter(name='Users').count() == 1, login_url='/access-denied/')
def form(request, pk=None):
    if request.POST:
        if pk:
            target = User.objects.get(pk=pk)
            form = UserForm(request.POST, instance=target)
        else:
            form = UserForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/user/list')
    else:
        if pk:
            target = User.objects.get(pk=pk)
            form = UserForm(instance=target)
        else:
            form = UserForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('users/form.html', args, context_instance=RequestContext(request))

asked 05 Sep '13, 08:36

Domagoj%20Kova%C4%8D's gravatar image

Domagoj Kovač
12
accept rate: 0%

edited 05 Sep '13, 08:39

Be the first one to answer this question!
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×46
×1
×1

Asked: 05 Sep '13, 08:36

Seen: 1,259 times

Last updated: 05 Sep '13, 08:39

powered by OSQA