Django中的自定义UserChangeForm

时间:2018-07-20 10:17:04

标签: python django forms

我正在尝试设置一个页面,以允许用户更改其名字和姓氏。问题是我不想在表单中包含密码,但是如果我不包含密码,则用户将无法更新信息。

我已经从UserChangeForm创建了自己的表单,只包含名字,姓氏和密码:

class UserForm(UserChangeForm):
    password = auth_forms.ReadOnlyPasswordHashField(label="Password",
                                                help_text="Para cambiar la contraseña por favor pulsa "
                                                          "<a href=\"change-password/\">en este link</a>.")
    class Meta:
        model = User
        fields = (
            'first_name',
            'last_name',
            'password'
        )

我的HTML很简单:

    <form method="post" >
        {% csrf_token %}
        {{ user_form.as_p }}
        <button type="submit">Actualizar</button>
    </form>

我考虑过在HTML中仅包含类似以下内容的输入:

> <div class="form-group">
>     <input type="text" class="form-control" name="first_name" id="inputFirstName" placeholder="First_name">
> </div>

,但不会显示名字的当前值。

我该怎么办?

非常感谢

编辑:

视图是:

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        #profile_form = ProfileForm(request.POST, instance=request.user.profile)
        #if user_form.is_valid() and profile_form.is_valid():
        if user_form.is_valid():
            user_form.save()
            #profile_form.save()
            return redirect('/user')
        else:
            #print(user_form.errors, profile_form.errors)
            print(user_form.errors)

    elif request.method == "GET":
        user_form = UserForm(instance=request.user)
        #profile_form = ProfileForm(instance=request.user.profile)
        #return render(request, 'user_data.html', {'user_form': user_form, 'profile_form': profile_form})
        return render(request, 'user_data.html', {'user_form': user_form})

错误:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/user

Django Version: 2.0.5
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'profiles',
 'portfolios',
 'django_extensions']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\contextlib.py" in inner
  52.                 return func(*args, **kwds)

File "C:\Users\AlbertoCarmona\Desktop\ibotics\chimpy\profiles\views.py" in update_profile
  91.         if user_form.is_valid():

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\forms.py" in is_valid
  179.         return self.is_bound and not self.errors

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\forms.py" in errors
  174.             self.full_clean()

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\forms.py" in full_clean
  376.         self._clean_fields()

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\forms.py" in _clean_fields
  397.                     value = getattr(self, 'clean_%s' % name)()

File "C:\Users\AlbertoCarmona\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\forms.py" in clean_password
  150.         return self.initial["password"]

Exception Type: KeyError at /user
Exception Value: 'password'

3 个答案:

答案 0 :(得分:0)

自己创建解决方案,就像将字段作为HiddenInput一样简单。

password = auth_forms.ReadOnlyPasswordHashField(label="Password", widget=forms.HiddenInput(),
                                                help_text="Para cambiar la contraseña por favor pulsa "
                                                          "<a href=\"change-password/\">en este link</a>.")

答案 1 :(得分:0)

问题在父类中。您可以阅读父类的以下代码(对于Django 2.0是实际的)以了解您的问题:

class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField(
        label=_("Password"),
        help_text=_(
            "Raw passwords are not stored, so there is no way to see this "
            "user's password, but you can change the password using "
            "<a href=\"{}\">this form</a>."
        ),
    )
class Meta:
    model = User
    fields = '__all__'
    field_classes = {'username': UsernameField}

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['password'].help_text = self.fields['password'].help_text.format('../password/')
    f = self.fields.get('user_permissions')
    if f is not None:
        f.queryset = f.queryset.select_related('content_type')

def clean_password(self):
    # Regardless of what the user provides, return the initial value.
    # This is done here, rather than on the field, because the
    # field does not have access to the initial value
    return self.initial["password"]

在方法clean_password中,您的应用程序尝试返回键password。如您所见,字段passwordfields外部声明,并在该类的所有方法中使用。据我所知,您无需对此领域做任何事情。 在我看来,在这种情况下,最好的解决方案不是固有的UserChangeForm形式。像这样:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name',
        )

答案 2 :(得分:0)

尝试排除密码和分配密码均为“无”。 一件事对我有用,即将UserChangeForm更改为forms.ModelForm

    class EditProfileForm(forms.ModelForm):
    first_name = forms.CharField(max_length=250, required=True, label='',
      widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}))
    last_name = forms.CharField(max_length=250, required=True, label='',
      widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}))
    email = forms.EmailField(max_length=250, required=True, label='',
      widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'}))

  class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')