[英]Custom UserChangeForm in Django
我正在嘗試設置一個頁面,以允許用戶更改其名字和姓氏。 問題是我不想在表單中包含密碼,但是如果我不包含密碼,那么用戶將無法更新信息。
我已經從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'
自己找到解決方案,就像將字段作為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
您的表單。 像這樣:
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
)
嘗試排除密碼和分配密碼均為無。 對我有用的一件事,即將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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.