【问题标题】:Disable Django Form Field only in UpdateView仅在 UpdateView 中禁用 Django 表单字段
【发布时间】:2020-12-15 05:00:35
【问题描述】:

我在 forms.py 中有一个 UserForm,它在 RegisterEdit Profile 功能之间很常见,它的视图也很常见,因为两个视图中 90% 的功能相似。

我只想在Edit Profile 页面中从UserFormdisable EMailField,但应该在Register 页面中可编辑。这是我的代码:

forms.py

class UserForm(forms.ModelForm):
  password = None
  email = forms.EmailField(required=False, disabled=True)  #-- This will disable all the times
  salutation = forms.ChoiceField(choices=Choices.SALUTATIONS)
  blood_group = forms.ChoiceField(choices=Choices.BLOOD_GROUPS)

  class Meta:
    model = User
    fields = ('salutation', 'blood_group', 'email', 'first_name', 'middle_name', 'last_name', 
              'gender', 'birth_date', 'profile')

registeredit 视图中都呈现相同的表单。这是我的 urls.py。

path('register/', StudentView.as_view(), name='addview'), 
path('<int:pk>/edit/', StudentView.as_view(), name='editview'), 

在views.py中(详细views.py请查看accepted answer

userform = UserForm(request.POST or None, instance=self.object)

admission.html

<form class="form" name="admissionForm" id="admissionForm" method="post" 
            enctype="multipart/form-data" action="{% url 'editview' form.instance.id %}"> 
 {% csrf_token %}
  <div class="pages">
     <h4 class="mt-2 mb-3">Personal Information</h4>
      {% include "student_errors.html" %}                
      {{userform|crispy}}      
      ....
      <div class="btn_container">
          <button type="submit" class="btn btn-info float-right btn-next">Submit</button>  
      </div>
 </div>

【问题讨论】:

    标签: django django-forms disable emailfield


    【解决方案1】:

    在您的 update_views 中,您可以设置:
    form.fields['email'].disabled = True

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2017-05-04
      • 2013-08-22
      • 2017-01-02
      • 2018-12-27
      • 1970-01-01
      • 2023-02-10
      相关资源
      最近更新 更多