Django在创建密码时需要用户,编辑时不需要

时间:2014-03-19 13:50:21

标签: django django-forms

我的ModelForm定义如下所示:

class UserForm(ModelForm):

    password = forms.CharField(required=True, label="Password", widget=forms.PasswordInput)

因此,在创建新用户时需要密码。但是我想在编辑用户时不要求它。我的编辑/添加按照以下方式在views.py中处理

@user_passes_test(lambda u: u.is_superuser)
def add(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'])
            new_user.save()
            messages.success(request, "User '%s' created" % new_user.username)
            return HttpResponseRedirect('/user')
    else:
        form = UserForm()
    return render(request, 'user/add.html', {"form": form})

@user_passes_test(lambda u: u.is_superuser)
def edit(request, id):
    user = User.objects.get(id=id)
    if request.method == 'POST':
        f = UserForm(request.POST, instance=user)
        if f.is_valid():
            f.save()
            messages.success(request, "User '%s' altered" % user.username)
            return HttpResponseRedirect('/user')
    else:
        form = UserForm(instance=user)
        return render(request, 'user/edit.html', {"form": form, "user": user})

感谢您的回答。

米甲

1 个答案:

答案 0 :(得分:0)

这就是我要做的事情:

class UserForm(ModelForm):
    def __init__(self, *args, **kwargs):
        is_edit = kwargs.get('is_edit', False)
        if 'is_edit' in kwargs:
            del kwargs['is_edit']
        super(UserForm, self).__init__(*args, **kwargs)
        if is_edit:
            self.fields['password'].required = False

然后,在你的edit()函数中:

f = UserForm(request.POST, instance=user, is_edit=True)

我在代码库中经常使用这种类型的东西。