Reputation: 11
For example I have a EntryUpdateForm that inherits from UpdateView that updates some data on a model. Now I'd like to disable certain fields. From the Django documentiation I'm not sure where exatcly to put the Field.disable attribute to disable a certain field on a form.
forms.py
class EntryUpdateForm(UpdateView):
class Meta:
model = Entry
fields = ["material", "shape", "diameter", "taken_from", "moved_to", "quantity"]
views.py
class EntryUpdateView(LoginRequiredMixin, EntryUpdateForm):
model = Entry
fields = ["material", "shape", "diameter", "taken_from", "moved_to", "quantity"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
I'm not even sure if it's possible to do this if I'm inheriting from the UpdateView, at least easly.
Upvotes: 0
Views: 864
Reputation: 11
Thanks to a comment from mursalin I managed to get it to work.
forms.py
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ["material", "shape", "diameter", "taken_from", "moved_to", "quantity"]
material = forms.ChoiceField(disabled=True)
shape = forms.ChoiceField(disabled=True)
diameter= forms.CharField(disabled=True) # add whichever field you want to disable
class EntryUpdateForm(UpdateView):
class Meta:
model = Entry
views.py
class EntryUpdateView(LoginRequiredMixin, EntryUpdateForm):
model = Entry
form_class = EntryForm # pass the form in the view to get it to change
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Upvotes: 0
Reputation: 1394
class EntryUpdateForm(UpdateView):
material = forms.CharField(widget=forms.TextInput(attrs={'readonly':'True'}))
class Meta:
model = Entry
fields = ["material", "shape", "diameter", "taken_from", "moved_to", "quantity"]
Replace material with whichever field you want to disable and use the appropriate widget
Upvotes: 0