Files
penracourses/survey/forms.py
T
2026-06-29 09:04:28 +01:00

83 lines
3.4 KiB
Python

from django import forms
from django.forms import ModelMultipleChoiceField
from django.contrib.auth.models import User
from generic.widgets import UserSearchWidget
from .models import Survey, SurveyQuestion, SurveyResponse, SurveyAnswer
class SurveyForm(forms.ModelForm):
author = ModelMultipleChoiceField(
queryset=User.objects.all(),
widget=UserSearchWidget(),
required=False,
help_text="Users who can view and manage this survey when it is set to private."
)
class Meta:
model = Survey
fields = ["name", "description", "active", "anonymous", "authors_only", "author"]
class SurveyQuestionForm(forms.ModelForm):
class Meta:
model = SurveyQuestion
fields = ["text", "question_type", "choices", "required", "position"]
widgets = {
"choices": forms.Textarea(attrs={"rows": 4, "placeholder": "Enter each choice on a new line"}),
}
class SurveyTakeForm(forms.Form):
def __init__(self, *args, **kwargs):
self.survey = kwargs.pop("survey")
self.questions = list(self.survey.questions.all())
super().__init__(*args, **kwargs)
for q in self.questions:
field_name = f"question_{q.pk}"
if q.question_type == SurveyQuestion.QuestionType.TEXT:
self.fields[field_name] = forms.CharField(
label=q.text,
required=q.required,
widget=forms.Textarea(attrs={"rows": 3, "class": "form-control"})
)
elif q.question_type == SurveyQuestion.QuestionType.CHOICE:
choices = [(c, c) for c in q.get_choices_list()]
self.fields[field_name] = forms.ChoiceField(
label=q.text,
required=q.required,
choices=[("", "Select an option")] + choices,
widget=forms.Select(attrs={"class": "form-select"})
)
elif q.question_type == SurveyQuestion.QuestionType.RATING:
self.fields[field_name] = forms.ChoiceField(
label=q.text,
required=q.required,
choices=[(str(i), str(i)) for i in range(1, 6)],
widget=forms.RadioSelect(attrs={"class": "form-check-input"}),
)
def save(self, user=None, cid=None, content_type=None, object_id=None, pre_or_post='GENERAL'):
response_user = None if self.survey.anonymous else user
response_cid = None if self.survey.anonymous else cid
response = SurveyResponse.objects.create(
survey=self.survey,
user=response_user,
cid=response_cid,
content_type=content_type,
object_id=object_id,
pre_or_post=pre_or_post
)
for q in self.questions:
field_name = f"question_{q.pk}"
val = self.cleaned_data.get(field_name)
if val is not None and val != "":
ans = SurveyAnswer(response=response, question=q)
if q.question_type == SurveyQuestion.QuestionType.TEXT:
ans.text_answer = val
elif q.question_type == SurveyQuestion.QuestionType.CHOICE:
ans.choice_answer = val
elif q.question_type == SurveyQuestion.QuestionType.RATING:
ans.rating_answer = int(val)
ans.save()
return response