Reputation: 199
Here is my Django Model:
class InterviewAssessment(models.Model):
topics = models.ManyToManyField(AdvocacyTopic, verbose_name="Topics", blank=True)
They consist into a list of topics out of them one or several items can be selected.
Therefore, when I want to create an object InterviewAssessment
, I use this class:
class InterviewForm(models.Model):
class Meta:
model = Interview
fields = ['topics']
widgets = {
'topics': forms.CheckboxSelectMultiple(),
}
My workflow requires that another User, who conducts the interview, updates my form to make an assessment.
Therefore I have created a form dedicated to the assessment, as only some fields are to be updated.
I would like to display only the topics which have been checked. They are not to be updated.
However, if through a widget:
self.fields['topics'].widget.attrs.update({'disabled': 'true'})
All the items are displayed in grey, however the field in the database is reset to 0 (which is normal with Django)
readonly
with:self.fields['topics'].widget.attrs.update({'readonly': 'true'})
The items are selectable and are implemented in the DB, which is worse.
{{ form.topics }}
Of course, I get all the topics, which I don't want.
Therefore what would be the syntax to exclusively display the checked topics ?
Upvotes: 1
Views: 350
Reputation: 21812
Since you only want to display the selected choices and don't want to update them, don't have topics
as part of the form and instead just render them manually by using the instance wrapped by the form (you can style it using CSS, etc. as you wish):
{% for topic in form.instance.topics.all %}
{{ topic }}
{% endfor %}
Upvotes: 1