Abhay
Abhay

Reputation: 137

Radio Button with default selection in Django

I had the same doubt of radio button in model file.

I want it to be a compulsory/required field with default selection to "No".

Fields available would be - Yes/No. Any suggestions.

B_CHOICES = [('P','Positive'),('N','Negative')]
Tag_Type = models.CharField(choices=B_CHOICES, max_length=128) 

Here's my form and model code-

Form -

<form id="ant_form" name="ant_form" method="POST" action="#">{% csrf_token %}

<input name="r_user" type="checkbox" value="{{user.id}}" />  {{user.username}}      

<input type="radio" name="txt{{user.id}}" value="P" > </input>      
    P Comment
<input type="radio" name="txt{{user.id}}" value="N" > </input>              
    N Comment

<textarea style="height: auto" rows="1" id="txt{{user.id}}" name="comment_{{user.id}}" cols="50">
</textarea>
<br>
</li>
{% endfor %}
</ul>
</div>

{% endif %} {# users #}

</form>

Model -

class r(models.Model):

BCHOICES = [('P','P'),('N','N'),] 

tag_type = models.CharField(max_length=2, default=Negative, choices=BCHOICES) 

Upvotes: 1

Views: 1308

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477891

You can set the default to 'N':

from django.db import models

B_CHOICES = [('P','Positive'),('N','Negative')]

class MyModel(models.Model):
    tag_type = models.CharField(choices=B_CHOICES, max_length=128, default='N')

When you render a ModelForm for the given MyModel, then the HTML will look like:

<select name="tag_type" id="id_tag_type">
  <option value="P">Positive</option>
  <option value="N" selected>Negative</option>
</select>

Upvotes: 1

Related Questions