Django窗体存储模型下拉列表

2024-09-28 22:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我尝试了两种不同的方法,但没有一种能满足我的要求。 一方面,根据这个问题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函数?

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


Tags: 方法用户nameform视图信息数据库表单
1条回答
网友
1楼 · 发布于 2024-09-28 22:09:20

你应该用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

相关问题 更多 >