django - 如何在 Django 表单中创建可选的只读字段?

标签 django django-forms

我在 django 表单中有一个只读字段,有时我想编辑它。
我只想要具有正确权限的正确用户来编辑该字段。在大多数情况下,该字段被锁定,但管理员可以对其进行编辑。

使用 初始化 功能,我可以将该字段设为只读或不设为只读,但不能选择设为只读。我还尝试将可选参数传递给 StudentForm。 初始化 但这比我预期的要困难得多。

有没有合适的方法来做到这一点?

模型.py

 class Student():
   # is already assigned, but needs to be unique
   # only privelidged user should change.
   student_id = models.CharField(max_length=20, primary_key=True) 
   last_name = models.CharField(max_length=30)
   first_name = models.CharField(max_length=30)
   # ... other fields ...

表格.py
 class StudentForm(forms.ModelForm):
   class Meta:
     model = Student
     fields = ('student_id', 'last_name', 'first_name', 
     # ... other fields ...


   def __init__(self, *args, **kwargs):
       super(StudentForm, self).__init__(*args, **kwargs)
       instance = getattr(self, 'instance', None)
       if instance: 
          self.fields['student_id'].widget.attrs['readonly'] = True

View .py
 def new_student_view(request):
   form = StudentForm()
   # Test for user privelige, and disable 
   form.fields['student_id'].widget.attrs['readonly'] = False
   c = {'form':form}
   return render_to_response('app/edit_student.html', c, context_instance=RequestContext(request))

最佳答案

这就是你要找的吗?通过稍微修改您的代码:

表格.py

class StudentForm(forms.ModelForm):

    READONLY_FIELDS = ('student_id', 'last_name')

    class Meta:
        model = Student
        fields = ('student_id', 'last_name', 'first_name')

    def __init__(self, readonly_form=False, *args, **kwargs):
        super(StudentForm, self).__init__(*args, **kwargs)
        if readonly_form:
            for field in self.READONLY_FIELDS:
                self.fields[field].widget.attrs['readonly'] = True

View .py
def new_student_view(request):

    if request.user.is_staff:
        form = StudentForm()
    else:
        form = StudentForm(readonly_form=True)

    extra_context = {'form': form}
    return render_to_response('forms_cases/edit_student.html', extra_context, context_instance=RequestContext(request))

所以事情是检查 View 级别的权限,然后在初始化时将参数传递给您的表单。现在,如果员工/管理员登录,字段将是可写的。如果不是,则只有类常量中的字段将更改为只读。

关于django - 如何在 Django 表单中创建可选的只读字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4485561/

相关文章:

javascript - Django 中的 Google TTS : Create Audio File in Javascript from base64 String

python - GeoDjango 查询 : all point that are contained into a multi polygon

python - Django:如何在不提交给数据库的情况下将模型表单数据从一页传送到另一页,然后再返回?

python - 将 Django 应用程序部署到 Heroku 时出现收集静态错误

Django 尝试在 save() 上插入而不是更新

python - 从 Django 表单集中删除表单

python-3.x - 为什么我的模型字段不读取其 ForeignKey 的值,而是返回其对象编号?

python - Django:如何自定义表单ChoiceField显示?

python - DRF 上传多个文件

Django modelform 根据其他字段选择删除 "required"属性