Answer the question
In order to leave comments, you need to log in
How to create a custom widget for a field?
Hello! Please help me figure it out.
I'm trying to create a custom widget for a field like in the picture below. There is a form with a function field (ModelMultipleChoiceField). I form the queryset for the field in the view and pass it through the constructor to the form. All Groups are passed to the queryset. Wrote a template for the widget. I want to give the user the opportunity to select several functions through checkboxes. I used the following code, but the form is empty, why is the render method in the custom widget not working? I think you need to pass groups to the tag that is in the widget, but how?
forms.py:
class RequirementForm(forms.ModelForm):
function = forms.ModelMultipleChoiceField(required=True, widget=CustomTreeWidget, queryset=Group.objects.none())
class Meta:
model = Requirement
fields = ('function',)
def __init__(self, all_groups, all_user_characteristics, *args, **kwargs):
super(RequirementForm, self).__init__(*args, **kwargs)
self.fields['function'].queryset = all_groups # Cписок всех Групп берутся из view
{% for group in groups %}
<p>{{ group }}</p>
{% for task in group.task_set.all %}
<p>{{ task }}</p>
{% for function in task.function_set.all %}
<input type="checkbox" name="option" value="{{ function }}">{{ function }}<br>
{% endfor %}
{% endfor %}
{% endfor %}
class CustomTreeWidget(Widget):
template_name = 'tree_widget.html'
def render(self, name, value, attrs=None):
template = loader.get_template(self.template_name)
return mark_safe(template)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question