Django Dropdown从数据库填充

编程入门 行业动态 更新时间:2024-10-25 00:32:16
本文介绍了Django Dropdown从数据库填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我通过视图将项目传递到模板,并且希望用户选择要提交到用户记录的值之一,那么我只会在模板中弄一个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>

顺便说一句,您应该命名项目而不是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从数据库填充

本文发布于:2023-08-05 20:50:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   Django   Dropdown

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!