2010-12-19 82 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)) 

所以事情是檢查的意見級別的權限,然後通過參數您的表單在初始化時。現在,如果員工/管理員登錄,字段將是可寫的。如果不是,則只有類常量的字段將更改爲只讀。

相關問題