refactor: add person update form fields to initial

This commit is contained in:
James Graham
2021-01-15 17:45:55 +00:00
parent f94627e4c8
commit 4cfee6362d
3 changed files with 64 additions and 12 deletions

View File

@@ -190,5 +190,50 @@ class PersonAnswerSet(AnswerSet):
#: Longitude for displaying location on a map
longitude = models.FloatField(blank=True, null=True)
def as_dict(self):
"""Get the answers from this set as a dictionary for use in Form.initial."""
exclude_fields = {
'id',
'timestemp',
'replaced_timestamp',
'person_id',
'question_answers',
'themes',
}
def field_value_repr(field):
"""Get the representation of a field's value as required by Form.initial."""
attr_val = getattr(self, field.attname)
# Relation fields need to return PKs
if isinstance(field, models.ManyToManyField):
return [obj.pk for obj in attr_val.all()]
if isinstance(field, models.ForeignKey):
return attr_val.pk
return attr_val
answers = {
field.attname: field_value_repr(field)
for field in self._meta.get_fields()
if field.attname not in exclude_fields
}
for answer in self.question_answers.all():
question = answer.question
field_name = f'question_{question.pk}'
if question.is_multiple_choice:
if field_name not in answers:
answers[field_name] = []
answers[field_name].append(answer.pk)
else:
answers[field_name] = answer.pk
return answers
def get_absolute_url(self):
return self.person.get_absolute_url()