Python 如何从以对象为前缀的窗体中排除字段
如何将视图中创建的表单中的某些字段从实例中排除? 我想允许用户编辑他们的属性,如用户名或电话,但在这种形式下,他们不应该更改密码 我试过这个:Python 如何从以对象为前缀的窗体中排除字段,python,django,django-models,django-forms,Python,Django,Django Models,Django Forms,如何将视图中创建的表单中的某些字段从实例中排除? 我想允许用户编辑他们的属性,如用户名或电话,但在这种形式下,他们不应该更改密码 我试过这个: del user_profile_form.fields['telephone'] 但当我这样做时,它会引发CSRF令牌丢失或不正确。 @login_required def edit_profile(request): user = request.user user_form = UserForm(instance=user)
del user_profile_form.fields['telephone']
但当我这样做时,它会引发CSRF令牌丢失或不正确。
@login_required
def edit_profile(request):
user = request.user
user_form = UserForm(instance=user)
user_profile_form = UserProfileForm(instance=user.userprofile)
context = {'user_form': user_form,
'user_profile_form': user_profile_form}
return render(request, 'auth/profiles/edit-profile.html', context=context)
FORMS.PY
class UserForm(forms.ModelForm):
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password1','password2', 'first_name', 'last_name')
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return self.cleaned_data
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('telephone','marital_status','how_do_you_know_about_us')
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile')
# ATRIBUTY KTORE BUDE MAT KAZDY
telephone = models.CharField(max_length=40,null=True)
HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
('coincidence',u'It was coincidence'),
('relative_or_friends','From my relatives or friends'),
)
how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True)
MARITAL_STATUS_CHOICES = (
('single','Single'),
('married','Married'),
('separated','Separated'),
('divorced','Divorced'),
('widowed','Widowed'),
)
marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True)
# OD KIAL STE SA O NAS DOZVEDELI
# A STAV
def __unicode__(self):
return '{} {}'.format(self.user.first_name,self.user.last_name)
def __str__(self):
return '{} {}'.format(self.user.first_name,self.user.last_name)
型号.PY
class UserForm(forms.ModelForm):
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password1','password2', 'first_name', 'last_name')
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return self.cleaned_data
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('telephone','marital_status','how_do_you_know_about_us')
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile')
# ATRIBUTY KTORE BUDE MAT KAZDY
telephone = models.CharField(max_length=40,null=True)
HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
('coincidence',u'It was coincidence'),
('relative_or_friends','From my relatives or friends'),
)
how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True)
MARITAL_STATUS_CHOICES = (
('single','Single'),
('married','Married'),
('separated','Separated'),
('divorced','Divorced'),
('widowed','Widowed'),
)
marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True)
# OD KIAL STE SA O NAS DOZVEDELI
# A STAV
def __unicode__(self):
return '{} {}'.format(self.user.first_name,self.user.last_name)
def __str__(self):
return '{} {}'.format(self.user.first_name,self.user.last_name)
新视图
@login_required
def edit_profile(request):
user = request.user
if request.method == 'POST':
user_form = UserForm(request.POST)
user_profile_form = UserProfileForm(request)
if user_form.is_valid() and user_profile_form.is_valid():
user_form.save()
user_profile_form.save()
return HttpResponseRedirect('/logged-in')
else:
print user_form.errors
print user_profile_form.errors
else:
user_form = UserForm(instance=user)
user_profile_form = UserProfileForm(instance=user.userprofile)
temp_user_profile_form = deepcopy(user_profile_form)
del temp_user_profile_form.fields['password1']
del temp_user_profile_form.fields['password2']
context = {'user_form': user_form,
'user_profile_form': temp_user_profile_form}
return render(request, 'auth/profiles/edit-profile.html', context=context)
错误
Exception Type: KeyError
Exception Value:
'password1'
看起来您正在
Meta
类中为UserForm
模型表单引用password1
和password2
。应该删除这些字段,因为它们不是用户模型中的字段。因此,更改后,您的UserForm
应该是:
class UserForm(forms.ModelForm):
# These 2 fields are unbound fields...
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
# These fields are your User model's fields
fields = ('username', 'email', 'first_name', 'last_name')
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return self.cleaned_data
您不需要在视图中删除它们。只需在模板中排除它们
此外,如果愿意,您可以在表单的
\uuuu init\uuuu
方法中隐藏表单字段输入。我推荐这种方法。您是否在模板中包含了{%csrf\u token%}
?如果您发布模板代码,这可能会有所帮助。另外,请将您的表格张贴到.pycode@CurtisOlson这只是一次,从那时起,它就起作用了——电话删除起作用了,但当我试图删除密码1(添加的代码)时,它引发了一个例外。谢谢,但这种方法并没有从编辑配置文件中排除密码1或密码2。它还在那里。我已经尝试了迁移和迁移,但仍然存在相同的问题。