How to make optional read-only fields in django forms?

I have a read-only field in the form of django, which I sometimes want to edit.
I want the right user to have permission to edit the field. In most cases, the field is locked, but the administrator can edit this.

Using the init function, I can make the field read-only or not, but not necessary for reading. I also tried passing an optional argument to StudentForm. init , but it turned out to be much more complicated than I expected.

Is there any way to do this?

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)) 
+4
source share
2 answers

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.

+7
source

It would be quite easy to use the administrator to edit any field and simply display the student ID in the page template.

I am not sure if this answers your questions.

0
source

Source: https://habr.com/ru/post/1332702/


All Articles