2

I am building a dashboard which will have some information about users. I am trying to set value to select tag using Django but the value never get assigned. Here is my code.

My model look something like this

class User(models.Model):
    first_name
    last_name
    reg_status

I need to fill in the template with the reg_status. The reg_status can contain three options, they are as mentioned below:

  • mailed
  • register
  • not register

The value of reg_status is dynamic. For example, if I pass in reg_status = mailed from my view, I need the <option value='mailed'> to be selected. However, if I pass in the reg_status = register from my view, I need the <option value='register'> to be selected.

Here is how I am trying to render the content in the template:

{% for u in user %}
 <input type='text' value={{u.first_name}}/>
 <input type='text' value={{u.last_name}}/>
 <select value={{u.reg_status}>
  <option value='mailed'>mailed</option>
  <option value='register'>register</option>
  <option value='not register'>not register</option>
 </select>
{% endfor %}

The output give 'mailed' as selected for all instance even if the value is set to 'registered' or 'not registered'.

wcarhart
  • 2,685
  • 1
  • 23
  • 44
skid
  • 958
  • 4
  • 13
  • 29

1 Answers1

1

You can use a Jinja ternary operator. It's a little greedy because you're doing the same operation 3 times. You could also look into setting a global variable with Jinja (see the documentation, scroll down to Scoping Behavior).

<select value='{{ u.reg_status }}'>
  <option value='mailed' {{ "selected='selected'" if u.reg_status == 'mailed' else "" }}>mailed</option>
  <option value='register' {{ "selected='selected'" if u.reg_status == 'register' else "" }}>register</option>
  <option value='not register' {{ "selected='selected'" if u.reg_status == 'not register' else "" }}>not register</option>
 </select>
wcarhart
  • 2,685
  • 1
  • 23
  • 44
  • When you set selected='selected' for the first option it override the value which you pass under select tag – skid Sep 13 '19 at 18:40
  • @skid Ah, I misunderstood what you were asking. Is the value of `u.reg_status` going to be one of `mailed`, `register`, or `not register`? If so, I might suggest updating your question to make that a bit clearer. I'll update my answer in just a sec – wcarhart Sep 13 '19 at 18:43
  • yes the value of u.reg_status will be either mailed,registered,not registerd i am trying to render the existing data from the database to my template inorder to make a dashboard kind of view. – skid Sep 13 '19 at 18:47
  • @skid Updated my answer. – wcarhart Sep 13 '19 at 19:03