Select choice from models.py in html form DJANGO

Viewed 32

I have model in models.py with field living_countries:

LIVING_COUNTRIES = [
    ('AFGANISTAN', 'Afganistan'),
    ('ALBANIA', 'Albania'),
    ('ALGERIA', 'Algeria'),
    ('ANGORRA', 'Andorra')]

class Employee(models.Model):
    user                =               models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
    first_name          =               models.CharField(max_length=100, blank=True)
    last_name           =               models.CharField(max_length=100, blank=True)
    username            =               models.CharField(max_length=30, blank=True)
    email               =               models.EmailField(max_length=140, blank=True)
    phone_number        =               PhoneNumberField(null=True)
    date_of_birth       =               models.DateField(blank=True, default='1929-22-22')
    education           =               models.CharField(max_length=50, blank=True)
    country_living      =               models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='AFGANISTAN', blank=True)
    created_at          =               models.DateTimeField(auto_now_add=True, blank=True)
    password            =               models.CharField(max_length=30, blank=True)

I want user who has html form in front of him to be able to choose one of those choices.

I've tried:

in view:

living_countries = models.Employee.objects.all()

in html:

<select name="category" id="id_category">
   {% for category in living_countries %}
      <option value="{{ category }}">{{ category }}</option>
   {% endfor %}
</select>

It just makes weird shape like: shape. I can click it but it doesn't do anything.

I want user to see dropdown menu or something like this. Thanks:)

1 Answers

You'll want to pass the living_countries variable to the template using context. Let's assume that your view in views.py has something like this:

template = loader.get_template('app/page.html')

# You'll want to create a context variable that is a dictionary
context = {}
# Then, instantiate your variable you want to pass to the view
living_countries = models.Employee.objects.all()

# Now pass that variable to context
context['living_countries'] = living_countries

# Now render your view
return HttpResponse(template.render(context, request))

You can now access the variable in your template the way you had in your question:

<select name="category" id="id_category">
   {% for category in living_countries %}
      <option value="{{ category }}">{{ category }}</option>
   {% endfor %}
</select>
Related