Is this what you are looking for? Changing the code a bit:
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))
So, you need to check permissions at the viewing level, and then pass the argument to the form when it is initialized. Now, if the user / administrator is registered, the fields will be recorded. If not, only the fields from the class constant will be read-only modified.
source share