Django Dropdown populated from database

If I pass the elements to the template through the view, and I want the user to select one of the values โ€‹โ€‹that falls into the user record, would I just start the for loop in the template correctly?

How will it 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) ) 
+8
source share
2 answers

If I understand 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 specify name elements instead of item, since this is a collection (but this is just a note;)).

This way you will have a list of all the items in the database.

Then, in the message, here is 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, be sure to include get_object_or_404

+22
source

I have a question. where should i post the following code in my project

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

Source: https://habr.com/ru/post/888568/


All Articles