Monk L
Monk L

Reputation: 3368

show form data in template

In my application,i am keeping some choices in forms.The choices are check box input and user can click and save the choices.In database saved choice are stored as integer like 1,2,3.How to query the saved value from database and show it in template as their corresponding options.

forms.py

OPTIONS = (
    ('1', 'Today'),
    ('2', 'This Week'),
    ('3', 'This Month'),
    ('4', 'This Year'),
    ('5', 'All'),
 )

class ReporForm(forms.ModelForm):
    optons = forms.ChoiceField(widget=forms.Select(), choices=OPTIONS,required=False, initial=0)

template

{{ reportform.as_p}}

Here,if user selected "This week" as their option,then in database the value of "This week" "2" will be saved.

In usual if i query the data from table,it is rendering the value as "2".But i want it to display "This week" in template.I don't see any tutorial or blog in this way.

I don't know how to do this in Django.

Upvotes: 0

Views: 607

Answers (1)

JcKelley
JcKelley

Reputation: 1984

In order to retrieve the value of your dictionary in django, you can use the following syntax:

ReporForm.get_optons_display()

So for example, if you wanted to check if the database query was 'All' or the key '5' you could simply do:

if ReporForm.get_optons_display() == 'ALL':
    #do something

Django Docs

An excerpt for an example:

Views.py

    #Query your database to retrieve your instance of 'ReporForm'
    #I will assume there is a primary key of some type (Reportcode)
    foo = ReporForm.objects.get(ReportCode = 1234)

#Pass foo to the context
context = {'foo':foo}
#Send this context to your render_to_response so it goes to template

reportform.html

<b>You have selected the option :</b> '{{ foo.get_optons_display }}'

Upvotes: 4

Related Questions