Python 3.x 如何让这些性别选择显示为单选按钮
我对Django比较陌生,我不知道如何让我的模型中的性别选择进入我的视图,然后进入我的模板。 下面是my Models.py:Python 3.x 如何让这些性别选择显示为单选按钮,python-3.x,django-models,django-forms,django-templates,Python 3.x,Django Models,Django Forms,Django Templates,我对Django比较陌生,我不知道如何让我的模型中的性别选择进入我的视图,然后进入我的模板。 下面是my Models.py: from django.db import models from django.forms import ModelForm from model_utils import Choices class Country(models.Model): ''' define a table in the database called Country with s
from django.db import models
from django.forms import ModelForm
from model_utils import Choices
class Country(models.Model):
''' define a table in the database called Country with several variables.'''
name = models.CharField(max_length = 50, unique = True)
officiallang = models.CharField(max_length = 50)
size = models.IntegerField()
# TODO: Find out how to defined this relationship
# representative = models.OneToOneField(UNrepresentative)
class UNrepresentative(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
name = models.CharField(max_length = 100, unique = True)
gender = models.CharField(max_length = 1,choices = GENDER_CHOICES,)
country = models.OneToOneField(Country, on_delete = models.CASCADE, )
class CountryForm(ModelForm):
class Meta:
model = Country
fields = ['name', 'officiallang', 'size']
class UNrepresentativeForm(ModelForm):
class Meta:
model = UNrepresentative
fields = ['name', 'gender', 'country']
下面是我的Forms.py:
from django import forms
from app1.models import Country, UNrepresentative
class CountryForm(forms.Form):
name = forms.CharField(max_length = 50,)
officiallang = forms.CharField(max_length = 50)
size = forms.IntegerField()
class UNrepresentativeForm(forms.Form):
name = forms.CharField(max_length = 100,)
gender = forms.ChoiceField(
choices = UNrepresentative.GENDER_CHOICES,)
最后,这里是create_representative.html,其中包含模板代码:
{% extends 'base.html' %}
{% block content %}
<form method = 'POST' action = "{% url 'create_representative' %}">
{% csrf_token %}
<div class="form-row">
<div class="col-4">
<input type="text" class="form-control" placeholder="name" value = "" name = 'name'>
</div>
<div class="col-4">
<div>
<label>Male</label>
<input type="radio" placeholder="gender" value="male" name='gender'>
</div>
<div>
<label>Female</label>
<input type="radio" placeholder="gender" value="female" name='gender'>
</div>
</div>
<div class = 'col-4'>
<label for="country">Choose a country:</label>
<select name="country_id">
{% for items in all_items %}
<option value="{{items.id}}">{{items.name}}</option>
{% endfor %}
</select>
</div>
<div class = 'col'>
<button type="submit" class="btn btn-outline-secondary">Create rep</button>
</div>
</div>
</form>
{% endblock content %}
{%extends'base.html%}
{%block content%}
{%csrf_令牌%}
男性
女性
选择一个国家:
{所有_项%中的项的百分比}
{{items.name}
{%endfor%}
创建代表
{%endblock内容%}
我已经手动添加了男性和女性的值,但理想情况下,我想要的是一个下拉列表,带有单选按钮,可以选择其中一种性别。任何帮助都将不胜感激。谢谢。@spaghettibaguett谢谢您的编辑。@spaghettibaguett谢谢您的编辑。