Advertisement
horozov86

Read-only fields

Feb 23rd, 2024
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. Read-Only 1 way
  2.  
  3. class ReadOnlyAlbumForm(ModelForm):
  4.     class Meta:
  5.         model = Album
  6.         fields = ('name', 'artist_name', 'genre', 'description', 'image_url', 'price')
  7.         widgets = {
  8.             'name': TextInput(attrs={'readonly': 'readonly'}),
  9.             'artist_name': TextInput(attrs={'readonly': 'readonly'}),
  10.             'genre': TextInput(attrs={'readonly': 'readonly'}),
  11.             'description': Textarea(attrs={'readonly': 'readonly'}),
  12.             'image_url': TextInput(attrs={'readonly': 'readonly'}),
  13.             'price': NumberInput(attrs={'readonly': 'readonly'}),
  14.         }
  15.  
  16. class DeleteAlbumView(views.DeleteView):
  17.     queryset = Album.objects.all()
  18.     template_name = 'albums/album-delete.html'
  19.     success_url = reverse_lazy('index')
  20.     form_class = ReadOnlyAlbumForm
  21.  
  22.  
  23.     def get_form_kwargs(self):
  24.         kwargs = super().get_form_kwargs()
  25.         kwargs["instance"] = self.object
  26.         return kwargs
  27.  
  28. Read-only 2 way
  29.  
  30. class ReadonlyViewMixin:
  31.     def get_form(self, form_class=None):
  32.         form = super().get_form(form_class=form_class)
  33.  
  34.         for field in form.fields.values():
  35.             field.widget.attrs["readonly"] = "readonly"
  36.  
  37.         return form
  38.  
  39. class DeleteAlbumView(ReadonlyViewMixin, views.DeleteView):
  40.     queryset = Album.objects.all()
  41.     template_name = "albums/album-delete.html"
  42.     success_url = reverse_lazy("index")
  43.     form_class = modelform_factory(
  44.         Album,
  45.         fields=("name", "artist_name", "genre", "description", "image_url", "price"),
  46.     )
  47.  
  48.     def get_form_kwargs(self):
  49.         kwargs = super().get_form_kwargs()
  50.         kwargs["instance"] = self.object
  51.         return kwargs
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement