[Django]-About Django RadioSelect initial value

4đź‘Ť

According to this Question here: default value for django choice field

you have to do the following:
https://stackoverflow.com/a/22257696/659900

Use the default attribute:

display = models.CharField(..., default=FRIENDS)

or

display = models.CharField(..., default=CHOICES[1][1])

* UPDATE *

I have taken your code and I have tried to reproduce your error. But unfortunately your code does work.

Here is what I’ve done

models.py

class Order(models.Model):

    WEIGHT_UNIT_CHOICES = (
        ('KG', 'kg'),
        ('TN', 't'),
    )

    weight_units = models.CharField(
        max_length=2,
        choices=WEIGHT_UNIT_CHOICES,
        default="TN"
    )

forms.py

class OrderRegisterForm(ModelForm):

    class Meta:
        model = Order
        widgets = {
            'weight_units': RadioSelect,
        }

I have used the shell to see what HTML was produced:

>> from playground.test_app.forms import OrderRegisterForm

>> o = OrderRegisterForm()
>> o.as_p()

which gave me the following output (formatted for clarity):

<p>
  <label for="id_weight_units_0">Weight units:</label> 
  <ul>\n
    <li>
      <label for="id_weight_units_0">
       <input type="radio" id="id_weight_units_0" value="KG" name="weight_units" />
         kg</label>
     </li>\n
     <li>
       <label for="id_weight_units_1">
         <input checked="checked" type="radio" id="id_weight_units_1" value="TN" name="
weight_units" /> 
         t</label>
      </li>\n
    </ul>
  </p>  

I have set the default to “TN” on purpose, to make sure django doesn’t use the first element by accident. See the checked="checked" attribute, that Django actually does use the right default value. Do you have some funny Javascript in place that might alter your output?

So could you please provide the output of your .as_p() method?

This might clarify a lot of things.

👤Dr.Elch

1đź‘Ť

So, I found the solution. The thing was I’m passing request.GET as is into form constructor and it seems to completely override initial values for fields. So, if you do

f = Form(request.GET)

the issue above happens. To avoid it, possible proper code is:

if request.method == "GET":
    form = Form()
    for key in request.GET:
        if key in form.fields:
            form.fields[key].initial = request.GET[key]
👤Enchantner

Leave a comment