django表单存储模型的下拉列表 [英] django form dropdown list of stored models

查看:127
本文介绍了django表单存储模型的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我一直在尝试2种不同的方法,但没有一种他们满足我的要求。
一方面,遵循这个问题 django表单下拉列表中的数字我可以创建一个下拉列表,并使用如下代码在视图中获取选定的值:

  class CronForm( forms.ChoiceField(选项= [(x,x)为范围(1,32)中的x])

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

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



我尝试过的其他方法是从html模板中完成。在那里我创建了以下表单:

 < form> 
{%为列表中的书籍%}
< option value =name> {{book.name}}< / option>
{%endfor%}
< / form>

其中book是在视图中呈现的:

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

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

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

解决方案

您应该使用 ModelChoiceField
$ b

  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:
#重定向到url在那里你会处理输入
return HttpResponseRedirect(...)#insert reverse或url
errors = form.errors或None#form not submitted or it errors
return render(request,'path / to / template.html',{
'form':form,
'errors':errors,
})

要添加新书或编辑新书,您应该使用的ModelForm 。然后在这个视图中,你会检查它是否是一个新窗体。

pre $ book $ form $ BookForm()#这将创建一个新的book

  book = get_object_or_404(Book,pk = 1)
book_form = BookForm(instance = book)#这将创建一个表格,其中填充了id为1的书籍的数据


I am trying to create a form for a library where a user can perform 2 actions: add a new book or open the stored information of an existing one. Books have 2 fields (title and author). Every time a new book is created, it is stored at the database. Any previously created book is shown as an option at a dropdown list (only the name). I want that when a user selects an option from the dropdown list, the information of the selected book appears on screen.

I have been trying 2 different approaches, but none of them fulfills my requirements. On one hand, following this question django form dropdown list of numbers I am able to create a dropdown list, and get the selected value at views with some code like that:

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

But I want my options to be the previously stored books at the data base, and not pre-defined values.

An other approach I have tried is to do it from the html template. There I create the following form:

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

Where book is rendered at views from this:

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

In this second case the information shown at the dropdown list is the one I want, but I don't know how to get the selected value and use it at views. Perhaps using a javascript function?

So my 2 requirements are: show the correct info at the list (the stored at the DB by the user) and be able to know which one has been selected.

解决方案

You should use ModelChoiceField.

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

Then your views, it should look something like this:

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,
   })

To add a new book or edit one, you should use a ModelForm. Then in that view you'll check if it's a new form or not

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

or

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

这篇关于django表单存储模型的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆