Djang中的自定义UserChangeForm

2024-09-30 08:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我从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很简单:

^{pr2}$

我想在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'

Tags: djangoinpyformrequestlocalformsprofile
3条回答

尝试将“排除密码”和“分配密码”设置为“无”。 有一件事对我有效,即将UserChangeForm更改为窗体.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')

我自己找到了解决方案,简单到包括一个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>.")

问题出在父类中。您可以阅读下面的父类代码(对于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。如您所见,字段password是在fields之外声明的,并在类的所有方法中使用。我知道,你不需要对这个领域做任何事情。 在我看来,在这种情况下,最好的解决方案不是从UserChangeForm中固有的形式。像这样:

^{pr2}$

相关问题 更多 >

    热门问题