简体   繁体   English

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

[英]How to display objects in a drop down list (django)?

python=2.7, django=1.11.13 python = 2.7,django = 1.11.13

In my html I am not able to display my condition choices from my models.py When filling the form, the user is not able to choose a condition because they are not displayed. 在我的html中,我无法从我的models.py中显示我的条件选择。填写表格时,用户无法选择条件,因为它们没有显示。

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 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 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 %}

And this is my form, I'm not sure what I am missing. 这是我的表格,我不确定我缺少什么。

form 形成

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__'

Try to use Django widgets . 尝试使用Django 小部件 For example: 例如:

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)

The form you're passing to the view is a BookForm, the BookForm contains a ForeignKey field to the Condition model, so the options in the select will be instances of the Condition model. 您传递给视图的表单是BookForm,BookForm包含Condition模型的ForeignKey字段,因此select中的选项将是Condition模型的实例。

You would need to preemptively create the Condition model instances, via the admin interface or the shell, and then you could see the conditions on the select, but that won't help, because your Condition instance needs to be associated to a Book, and that makes me think your software is badly designed. 您需要通过管理界面或Shell抢先创建Condition模型实例,然后可以在select上看到条件,但这无济于事,因为您的Condition实例需要与Book关联,并且这让我觉得您的软件设计不当。

Let me propose a solution: 让我提出一个解决方案:

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__'

Now the conditions are saved as an integer (like it would be if you used foreign keys) and your software is easier to understand and develop. 现在条件被保存为整数(就像使用外键一样),并且软件更易于理解和开发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM