从数据库填充 Django Dropdown [英] Django Dropdown populate from database
问题描述
如果我通过视图将项目传递给模板,并且我希望用户选择提交给用户记录的值之一,那么我只会在模板中使用 for 循环,对吗?
If I pass items to the template through the view, and I want the user to select one of the values that gets submitted to a user's record, I would only have dun a for loop in the template right?
那会是什么样子?在模板中:
What would that look like? In the template:
<form method="POST"
<select>
</select>
</form>
型号:
class UserItem(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
class Item(models.Model):
name = models.CharField(max_length = 50)
condition = models.CharField(max_length = 50)
查看:
def selectview(request):
item = Item.objects.filter()
form = request.POST
if form.is_valid():
# SAVE
return render_to_response (
'select/item.html',
{'item':item},
context_instance = RequestContext(request)
)
推荐答案
如果我正确理解了您的需求,您可以执行以下操作:
If I understood your need correctly, you can do something like:
<form method="POST">
<select name="item_id">
{% for entry in items %}
<option value="{{ entry.id }}">{{ entry.name }}</option>
{% endfor %}
</select>
</form>
顺便说一下,你应该给items而不是item命名,因为它是一个集合(但它只是一个备注;)).
By the way, you should give the name items instead of item, since it's a collection (but it's just a remark ;)).
这样做,您将获得数据库中所有项目的列表.
Doing so, you will have a list of all the items in the database.
然后,在帖子中,这里你需要做的是:
Then, in the post, here what you need to do:
def selectview(request):
item = Item.objects.all() # use filter() when you have sth to filter ;)
form = request.POST # you seem to misinterpret the use of form from django and POST data. you should take a look at [Django with forms][1]
# you can remove the preview assignment (form =request.POST)
if request.method == 'POST':
selected_item = get_object_or_404(Item, pk=request.POST.get('item_id'))
# get the user you want (connect for example) in the var "user"
user.item = selected_item
user.save()
# Then, do a redirect for example
return render_to_response ('select/item.html', {'items':item}, context_instance = RequestContext(request),)
当然,不要忘记包含 get_object_or_404一个>
这篇关于从数据库填充 Django Dropdown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!