Django Dropdown populate from database

南笙酒味 提交于 2020-01-10 08:31:07

问题


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>

Model:

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)

View:

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

回答1:


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>

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

Of course, don't forget to include get_object_or_404



来源:https://stackoverflow.com/questions/6062742/django-dropdown-populate-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!