I've have a view that uses the formset factory
but I'm trying to style the rendered html form. But the usual styling for forms doesn't work and im not sure what i need to do to apply the CSS stytles.
My View
def get_questionnaire(request, project_id, questionnaire_id):
# Get the Response object for the parameters
response = Response.objects.get(
project_name_id=project_id, questionnaire_id=questionnaire_id
)
AnswerFormSet = modelformset_factory(Answer, fields=('answer',), extra=0)
answer_queryset = Answer.objects.filter(response=response
).order_by('question__sequence'
).select_related('question')
if request.method == 'POST':
# to be completed
pass
else:
# Get the list of questions for which no Answer exists
new_answers = Question.objects.filter(
questionnaire__response=response
).exclude(
answer__response=response
)
# This is safe to execute every time. If all answers exist, nothing happens
for new_answer in new_answers:
Answer(question=new_answer, response=response).save()
answer_formset = AnswerFormSet(queryset=answer_queryset)
return render(request, 'pages/formset.html', {'formset': answer_formset})
for the moment im just trying to style a single field by applying the widgets in forms.py. But this isn't working.
class answer_formset(ModelForm):
class Meta:
model = Answer
fields = ('answer',)
widgets = {
'answer': forms.Select(attrs={'class': 'form-select'}),
}
HTML
{{ formset.management_form }}
{% for form in formset %}
{{ form.id }} {{ form.instance.question.question }}
{{ form.answer }}
<br>
{% endfor %}
Thanks
CodePudding user response:
You need to tell the factory which ModelForm
to use:
AnswerFormSet = modelformset_factory(Answer, form=answer_formset, fields=('answer',), extra=0)
From docs:
You can optionally pass a form argument to use as a starting point for constructing the ModelForm.
more info: https://docs.djangoproject.com/en/4.0/ref/forms/models/#modelform-factory