2011-05-19 210 views
6

如果我通過視圖將項目傳遞給模板,並且我希望用戶選擇提交給用戶記錄的值之一,那麼我只需要在模板中設置for循環?從數據庫中填充Django下拉列表

會是什麼樣子? 在模板:

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

請提供更多的信息,比如它的型號,傳輸數據到模板等 – 2011-05-19 17:54:54

+0

添加了信息。請參閱修改。謝謝 – Eva611 2011-05-19 18:07:32

+1

首先,我不能推薦您使用Django Forms(http://docs.djangoproject.com/en/1.3/topics/forms/) - 特別是,請參閱「模型的表單」部分。看起來你可能會這樣做(我在你的示例代碼中看到了「if form.is_valid」),但是你發佈的代碼瘋狂地被破壞了。 – 2011-05-19 18:17:02

回答

18

如果我明白你的需要正確的話,你可以這樣做:

<form method="POST"> 
<select name="item_id"> 
{% for entry in items %} 
    <option value="{{ entry.id }}">{{ entry.name }}</option> 
{% endfor %} 
</select> 
</form> 

順便說一句,你呢d給名稱項目而不是項目,因爲它是一個集合(但它只是一個註釋;))。

這樣做,您將擁有數據庫中所有項目的列表。

然後,在後,在這裏你需要做什麼:

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