Answer the question
In order to leave comments, you need to log in
How to make a django form field "disabled" directly in the template?
Dobrechka, gentlemen.
The task is as follows: it is necessary, depending on the presence / non-availability of a certain right for the user, to show him active / inactive fields.
Tell me, can I make the form field "disabled" on the run, in the template?
<div class="col-md-12">
{% if perms.foo.change_datasettings %}
{% for field in setting_form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
{% else %}
{% for field in form %}
{{ field.label_tag }} {{ field.disabled }}
{% endfor %}
{% endif %}
</div>
Answer the question
In order to leave comments, you need to log in
I use widget-tweaks ( https://pypi.python.org/pypi/django-widget-tweaks)
Look at the attr template tag there. They can set any field attribute
This can be done in a form. And even then, the logic itself should be written in view. First, pass an argument to the form that specifies whether to make the fields disabled. And then, already in the form, put down the attributes of the fields.
class MyView(...):
form_class = MyForm
def get_form_kwargs(self, ...): # название метода условно, не уверен, что он так называется в generic views и даже что он есть :)
kwargs = super(MyView, self).get_form_kwargs(...)
kwargs.update({'disabled': not self.request.user.has_perm(...)})
return kwargs
class MyForm(...):
def __init__(self, *args, **kwargs):
is_disabled = kwargs.pop('disabled')
super(MyForm, self).__init__(*args, **kwargs)
if is_disabled:
self.fields['foo'].widget.attrs.update({'disabled': 'disabled'})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question