Reputation: 109
I would like to show a combobox with a OneToOneField
:
models.py:
class Aliment(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
type_aliment_id = models.OneToOneField(type_aliment)
mesurande_id = models.OneToOneField(mesurande)
calories = models.IntegerField(default=0)
proteines = models.IntegerField(default=0)
class type_aliment(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
forms.py:
class AlimentForm(ModelForm):
class Meta:
model=Aliment
field = ('name','type_aliment_id','mesurande_id','calories','proteines')
views.py:
def add_aliment(request):
add_aliment = AlimentForm()
return render_to_response("add_aliment.html",
{'form_aliment':add_aliment,},RequestContext(request))
And I Would like to show all columns of "Aliment" but for "type_aliment_id" i would like to have a combobox with all names in "type_aliment" : And it doesn't work but i don't know why :
<form id="myForm" action="" method="post">{% csrf_token %}
<select name="select_type" id="id_select_type">
{% for type_aliment in form_aliment.type_aliment_id %}
<option value="{{ type_aliment.id }}">{{ type_aliment.name}}</option>
{% endfor %}
</select>
Upvotes: 1
Views: 67
Reputation: 59228
You don't need to construct your combobox manually. It will automatically be created by Django. Just use
<form id="myForm" action="" method="post">
{% csrf_token %}
{{ form_aliment }}
<button type="submit">Submit</button>
</select>
as the basis for your template.
You also have to implement the __unicode__
method in your class to see their names in the combo box:
class type_aliment(models.Model):
...
def __unicode__(self):
return self.name
PS: Your naming convention is confusing. Try to stick with Python/Django standards. Use CamelCase for class names; for example, instead of
class type_aliment(...)
use
class TypeAliment(...)
and don't add the _id
suffix to your field names. Instead of
type_aliment_id = models.OneToOneField(type_aliment)
use
type_aliment = models.OneToOneField(TypeAliment)
it will help fellow coders (like here on Stack Overflow) read your code more easily.
Upvotes: 2