我正在尝试在项目上显示用户的个人资料。我想呈现一个表单,但是将其禁用/无法更改(仅显示)。我不知道它的语法。帮助将不胜感激!
这是view.py:
@login_required
def profile(request):
user_form = UserForm(instance=request.user)
user_form.fields.disabled = True <------- HELP HERE
return render(request, 'rentadevapp/profile.html', {'user_form': user_form})
我本质上只想显示只读/禁用形式。然后,用户会有一个编辑按钮,可将他们带到个人资料编辑页面。
感谢您的帮助!
这里是html以防万一:
<form method="GET" action="/profile_edit">{% csrf_token %}
{{ user_form|crispy }}
<button type="submit" class="edit btn btn-default btn-block btn-lg">Edit</button><br>
</form>
Forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
答案 0 :(得分:2)
由于似乎您使用的是django-crispy-forms,我将使用以下内容:
class UserForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs, disable_fields=False):
super().__init__(*args, **kwargs)
if disable_fields:
form.fields['password'].disabled = True
form.fields['password2'].disabled = True
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
因此,当您要创建表单时,这应该可以使其起作用:
@login_required
def profile(request):
user_form = UserForm(instance=request.user, disable=True)
return render(request, 'rentadevapp/profile.html', {'user_form': user_form})
答案 1 :(得分:1)
Django 1.9添加了Field.disabled
属性:https://docs.djangoproject.com/en/stable/ref/forms/fields/#disabled
禁用的布尔参数设置为True时,将使用禁用的HTML属性禁用表单字段,以便用户无法对其进行编辑。即使用户篡改了提交给服务器的字段的值,也将忽略该字段,而使用表单的初始数据中的值。
您可以执行以下操作以禁用视图中所需的字段:
@login_required
def profile(request):
user_form = UserForm(instance=request.user)
for fieldname in user_form.fields:
user_form.fields[fieldname].disabled = True
return render(request, 'rentadevapp/profile.html', {'user_form': user_form})