【问题标题】:django form dropdown list of stored modelsdjango表单存储模型的下拉列表
【发布时间】:2013-04-09 23:10:29
【问题描述】:

我正在尝试为图书馆创建一个表单,用户可以在其中执行 2 项操作:添加新书或打开现有书的存储信息。书籍有 2 个字段(标题和作者)。 每次创建新书时,都会将其存储在数据库中。任何以前创建的书都显示为下拉列表中的一个选项(只有名称)。我希望当用户从下拉列表中选择一个选项时,所选书籍的信息会出现在屏幕上。

我一直在尝试 2 种不同的方法,但它们都不能满足我的要求。 一方面,遵循这个问题django form dropdown list of numbers 我可以创建一个下拉列表,并使用类似这样的代码在视图中获取选定的值:

class CronForm(forms.Form):
    days = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)])

def manage_books(request):
    d = CronForm()
    if request.method == 'POST':
        day = request.POST.get('days')

但我希望我的选项是以前存储在数据库中的书籍,而不是预定义的值。

我尝试过的另一种方法是从 html 模板中进行。在那里我创建了以下表单:

<form>
    {% for book in list %} 
        <option value="name">{{ book.name }}</option>
    {% endfor %}   
</form>

书籍在此视图中呈现的位置:

l = Books.objects.all().order_by('name')

在第二种情况下,下拉列表中显示的信息是我想要的,但我不知道如何获取所选值并在视图中使用它。也许使用 javascript 函数?

所以我的两个要求是:在列表中显示正确的信息(用户存储在数据库中)并能够知道选择了哪一个。

【问题讨论】:

    标签: python html django forms


    【解决方案1】:

    你应该使用ModelChoiceField

    class CronForm(forms.Form):
        days = forms.ModelChoiceField(queryset=Books.objects.all().order_by('name'))
    

    那么你的视图应该是这样的:

    def show_book(request):
       form = CronForm()
       if request.method == "POST":
          form = CronForm(request.POST)
          if form.is_valid:
             #redirect to the url where you'll process the input
             return HttpResponseRedirect(...) # insert reverse or url
       errors = form.errors or None # form not submitted or it has errors
       return render(request, 'path/to/template.html',{
              'form': form,
              'errors': errors,
       })
    

    要添加一本新书或编辑一本,您应该使用ModelForm。然后在该视图中,您将检查它是否是新表单

    book_form = BookForm() # This will create a new book
    

    book = get_object_or_404(Book, pk=1)
    book_form = BookForm(instance=book) # this will create a form with the data filled of book with id 1
    

    【讨论】:

    • 非常感谢,这正是我所需要的! :)
    • 这个下拉列表表单怎么放在html中,和普通表单一样吗?
    【解决方案2】:

    补充 J. Ghyllebert 的回答,以解决 cmets 中的渲染问题。 模板渲染:

    <form action="" class="YourFormClass" method="post">
        {% csrf_token %}
        {{ form.as_p }}
    </form>
    

    或单个字段:

    <form action="" class="YourFormClass" method="post">
        {% csrf_token %}
        <label class="YourLabelClass">{{ form.days.label }}</label>
        <div class="YourSelectClass">
            {{ form.days }}
        </div>
    </form>
    

    文档:https://docs.djangoproject.com/en/3.1/topics/forms/#the-template

    【讨论】:

      猜你喜欢
      • 2013-06-16
      • 2021-11-29
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2016-02-23
      • 1970-01-01
      相关资源
      最近更新 更多