我试图为一个库创建一个表单,用户可以在其中执行两个操作:添加一本新书或打开一本现有图书的存储信息。书籍有两个字段(标题和作者)。 每创建一本新书,它都存储在数据库中。以前创建的任何书籍都会在下拉列表中显示为一个选项(仅显示名称)。我希望当用户从下拉列表中选择一个选项时,所选书籍的信息会出现在屏幕上。
我尝试了两种不同的方法,但没有一种能满足我的要求。 一方面,根据这个问题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个要求是:在列表中显示正确的信息(用户存储在数据库中),并且能够知道选择了哪一个。
你应该用ModelChoiceField。
你的观点应该是这样的:
要添加新书或编辑新书,应使用ModelForm。然后在这个视图中,您将检查它是否是一个新表单
或者
相关问题 更多 >
编程相关推荐