私は時々編集したいdjango形式の読み取り専用フィールドを持っています。
フィールドを編集するための適切な権限を持つ適切なユーザーのみが必要です。ほとんどの場合、フィールドはロックされていますが、管理者がこれを編集できます。djangoフォームでオプションで読み取り専用フィールドを作成するには?
の機能を使用すると、フィールドを読み取り専用にするかどうかを指定できますが、オプションで読み取り専用にすることはできません。私はまた、StudentFormにオプションの引数を渡そうとしました。 でも、それは私が予想していたよりはるかに難しいものでした。
これを行う適切な方法はありますか?
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))