Home > database >  Django - possible to pass Model Enums into Template Javascript?
Django - possible to pass Model Enums into Template Javascript?

Time:03-04

Is it possible in Django to pass in enum values from a model

Django HTML Template - JS at bottom

E.g. Can I in JS, do something like

`var enumValue1 = "{{employment_ukrightowork_form.right_to_work_selection.UKRightoWorkSelection.PASSPORT}}"

Django MODEL

If my model in model.py looks like:

# U.K. RIGHT TO WORK MODEL
class UK_Right_To_Work(models.Model):

    class UKRightoWorkSelection(models.TextChoices):
        PASSPORT = 'Passport', _('U.K. or Irish - Passport')
        BIRTHCERT = 'Birth Certificate & N.I. Number', _('U.K. or Irish - Birth or Adoption Certificate   Proof of National Insurance Number')
        CERTOFREG = 'Certificate of Registration & N.I. Number', _('U.K. or Irish - Certificate of Registration or Naturalisation   Proof of National Insurance Number')

    right_to_work_id        = models.BigAutoField(verbose_name='U.K. Right to Work ID', primary_key=True, serialize=False, auto_created=True)
    right_to_work_selection = models.CharField(verbose_name='U.K. Right to Work selection', max_length=41, choices=UKRightoWorkSelection.choices, blank=False, null=False, default=UKRightoWorkSelection.PASSPORT)

CodePudding user response:

Why not pass these in as context variables?

views.py

from . import models

def render_template(request):

    context = {
        "options" : models.UK_Right_To_Work.UKRightoWorkSelection
    }

    return render(request, "template.html", context=context)

Then in your template:

var enumValue1 = "{{options.PASSPORT}}";
...
  • Related