Home > other >  Django - how to return human readable from an enum (for multicheckbox forms)
Django - how to return human readable from an enum (for multicheckbox forms)

Time:03-04

I have this code, but it only returns the shorter variable values, 'Plan 1', 'Plan 2', not their longer human-readable forms which I have defined in the model.

I generate checkboxes in a HTML template from a form.py and view.py by calling and passing in the variable

(correct instance).student_loan_plan.all(), 

and passing that through the 'context' variable in the 'render' function

MODEL

# U.K. STUDENT LOAN PLAN MODEL
class UK_Student_Loan_Plan(models.Model):

STUDENT_LOAN_PLANS = [
    ('Plan 1', 'Plan 1: English or Welsh student'),
    ('Plan 2', 'Plan 2: English or Welsh who started on 1 September 2012'),
    ('Plan 4', 'Plan 4: Scottish student who started on 1 September 1998'),
    ('Postgraduate', 'Postgraduate: English or Welsh student'),
]
student_loan_plan_id = models.BigAutoField(verbose_name='Student Loan Plan ID', primary_key=True, serialize=False, auto_created=True)
student_loan_plan    = models.CharField(verbose_name='Student Loan Plan', max_length=12, choices=STUDENT_LOAN_PLANS, blank=True, unique=True, null=True) 

def __str__(self):
    return self.student_loan_plan

QUESTION

Q1. How do I get the full human readable form returned?

I've tried this, but no success

def __str__(self):
    return self.student_loan_plan.choice

CodePudding user response:

self.get_student_loan_plan_display() # on views.py

{{object.get_student_loan_plan_display}} # on templates
  • Related