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

时间:2010-12-19 22:47:22

标签: django django-forms

我有一个django形式的只读字段,我有时想要编辑 我只希望拥有正确权限的合适用户编辑该字段。在大多数情况下,该字段已被锁定,但管理员可以对其进行编辑。

使用 init 功能,我可以将字段设置为只读,但不能选择只读。我也尝试将一个可选参数传递给StudentForm。 init ,但这比我预期的要困难得多。

有没有正确的方法来完成这项工作?

models.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 ...

forms.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

views.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))

2 个答案:

答案 0 :(得分:7)

这是你在找什么?通过稍微修改代码:

forms.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

views.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))

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

答案 1 :(得分:0)

使用管理员进行任何字段编辑都很容易,只需在页面模板中呈现学生ID。

我不确定这是否能回答你的问题。