我有一個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))