Ive created a form which users fill out, then it uses reportlab to create a pdf of their answers.
It works well except for a charfield (preferred_topics) which contains a list. Data is saved like this:
['ANI', 'EDU', 'ENV']
I think that might be a problem as id exect it to save the data like this:
[['ANI'], ['EDU'], ['ENV']]
However it works fine on the website.
So to print human readable data to the pdf im using get_FOO_display()
, but this doesnt work for preferred_topics. If i call (user.personalinformation.get_preferred_topics_display()
i get:
AttributeError at /enrolment/final_question/
'PersonalInformation' object has no attribute 'get_preferred_topics_display'
Here is my other relevant code:
model.py
preferred_topics = models.CharField(max_length=200, default='')
utils.py
# generate pdf
def generate_pdf(request):
# get user
user = request.user
# data that will be printed to the pdf
page_contents = [
['Personal Information'],
['Name:', '%s %s' %(user.personalinformation.first_name, user.personalinformation.surname)],
['E-mail:', '%s' %(user.email)],
['Gender:', '%s' %(user.personalinformation.get_gender_display())],
# this field is causing grief
['Preferred Topics:', '%s' %(user.personalinformation.preferred_topics)]
]
forms.py
TOPICS = (
('ANI', 'Animals'),
('ART', 'Art'),
('COM', 'Communication'),
('CRI', 'Crime'),
)
preferred_topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple())
Im expecting to be told that the data is being saved wrongly in my db, but dont know how to change it, and wanted confirmation before i started changing previously working stuff as im sure i will break currently working things in the process.
SUMMARY - i want to use user.personalinformation.get_preferred_topics_display()
but its not working and i suspect its because the data is being saved wrongly in the db but would like confirmation before i go wrecking stuff.
Thank you.
You are saving multiple choices as single string which is not good idea as you would have hard time filtering and working with this kind of data ( rather use Arrayfield of choices)
There is no get_FOO_display() without choices on models field so you would need to write your own converter
# create dict of options
options = dict((y,x) for y,x in PersonalInformationForm.TOPICS)
# evaluate string to list
selected_choices = ast.literal_eval(testobj2.preferred_topics)
# find choices in dict
selected values = [option.get(key) for key in selected_choices]