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