2010-12-19 83 views
4

我有一个django格式的只读字段,有时我想编辑它。
我只希望具有正确权限的用户编辑该字段。在大多数情况下,该字段已被锁定,但管理员可以编辑该字段。如何在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)) 

回答

0

这将是很容易使用的管理对于任何领域的编辑和只呈现该页面模板中的学生ID。

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

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

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

相关问题