2017-08-08 73 views
0

蟒蛇= 2.7,则Django = 13年1月11日如何在下拉列表(django)中显示对象?

在我的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__' 
+0

你可以显示“窗体”? – zaidfazil

+0

当然!我只是添加了代码,谢谢! – superrtramp

回答

0

你传递给视图的形式是BookForm,该BookForm包含一个ForeignKey场条件的模式,所以在选择的选项将是条件模型的实例。

您需要通过管理界面或shell抢先创建Condition模型实例,然后才能看到select上的条件,但这无济于事,因为您的Condition实例需要关联到一本书,这让我觉得你的软件设计不好。

让我提出一个解决方案:

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

现在的条件保存为一个整数(如这将是,如果你使用外键),你的软件更容易理解和发展。

+0

它的工作原理!天才解决方案,谢谢! – superrtramp

+0

我很高兴你喜欢它。这是常见的礼节来标记解决方案与绿色票证标志一起工作:-)不用客气。 – fixmycode

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) 
相关问题