如何在下拉列表中显示对象(django)?

时间:2017-08-08 16:06:41

标签: python django python-2.7 django-models django-views

python = 2.7,django = 1.11.13

在我的html中,我无法从models.py中显示我的条件选择 填写表单时,用户无法选择条件,因为它们不会显示。

models.py

class Books(models.Model):
    book_name = models.CharField(max_length=100)
    book_condition = models.ForeignKey('Condition')

    def __unicode__(self):
        return self.book_name


class Condition(models.Model):
    NEW = 'new'
    USED = 'used'
    COLLECTIBLE = 'collectible'
    CONDITION_CHOICES = (
        (NEW, 'New'),
        (USED, 'Used'),
        (COLLECTIBLE, 'collectible'),
    )
    book = models.ForeignKey(Books)
    condition = models.CharField(max_length=10, choices=CONDITION_CHOICES)

    def __unicode__(self):
        return self.condition

views.py

def add_book(request):
    if request.method == 'GET':
        context = {
            'form': BookForm()
        }

    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
             form.save()
        context = {
            'form': form,
        }

    return render(request, 'add_book_form.html', context=context)

add_book_form.html

{% extends 'base.html' %}
{% block body %}

<h3>Add Book </h3>
<form action="" method="post">
    {% csrf_token %}
    {{ form}}

    <br/>
    <input class="button" type="submit" value="Submit"/>
</form>

{% endblock %}

这是我的表格,我不确定我错过了什么。

形式

from django.forms import ModelForm
from .models import Books, Condition


class BookForm(ModelForm):
    class Meta:
        model = Books
        fields = '__all__'


class ConditionForm(ModelForm):
    class Meta:
        model = Condition
        fields = '__all__'

2 个答案:

答案 0 :(得分:0)

尝试使用Django widgets。例如:

class BookForm(forms.Form):
categories = (('Adventure', 'Action'),
              ('Terror', 'Thriller'),
              ('Business', 'War'),)
description = forms.CharField(max_length=9)
category = forms.ChoiceField(required=False,
                             widget=forms.Select,
                             choices=categories)

答案 1 :(得分:0)

您传递给视图的表单是BookForm,BookForm包含Condition模型的ForeignKey字段,因此select中的选项将是Condition模型的实例。

您需要通过管理界面或shell抢先创建Condition模型实例,然后您可以在select上看到条件,但这无济于事,因为您的Condition实例需要与a关联预订,这让我觉得你的软件设计得很糟糕。

让我提出一个解决方案:

class Book(models.Model):
    """
    This model stores the book name and the condition in the same
    table, no need to create a new table for this data.
    """
    NEW = 0
    USED = 1
    COLLECTIBLE = 2
    CONDITION_CHOICES = (
        (NEW, 'New'),
        (USED, 'Used'),
        (COLLECTIBLE, 'Collectible'),
    )
    name = models.CharField(max_length=100)
    condition = models.SmallIntegerField(choices=CONDITION_CHOICES)

    def __unicode__(self):
        return "{0} ({1})".format(self.book_name, self.condition)

class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = '__all__'

现在条件保存为整数(就像使用外键一样),您的软件更容易理解和开发。