2012-07-20 97 views
0

我試圖從查詢有一個Django的形式,但我一直在這樣做了錯誤的方式。查了幾個例子,但我做的有點不同。這裏是我的代碼,預填充Django表單

樂形式

class ItemForm(ModelForm): 

    class Meta: 
     model = Item 
     exclude = ('deleted') 

和視圖

def index(request): 
    user = User 
    try: 
     last_modified_list = ShoppingList.objects.filter(deleted='0').filter(owner=user).latest('date_modified') 
     items = Item.objects.filter(shopping_list=last_modified_list).filter(deleted='0') 
    except ObjectDoesNotExist: 
     items = Item.objects.filter(deleted='0') 

    last_used_currency = ExtendedUser.objects.filter(owner=user) 

    #currency = forms.CharField(initial=last_used_currency.last_currency) 
    try: 
     last_used_shoppinglist = ShoppingList.objects.filter(deleted='0').filter(owner=user).latest('date_modified') 
    except ObjectDoesNotExist: 
     last_used_shoppinglist = datetime.datetime.now() 

    item_form = ItemForm (request.POST or None) 
    item_form.fields["shopping_list"]=last_used_shoppinglist 




    if item_form.is_valid(): 
     name = item_form.cleaned_data['name'] 
     bought = item_form.cleaned_data['bought'] 
     currency = item_form.cleaned_data['currency'] 
     price = item_form.cleaned_data['price'] 
     date_added = item_form.cleaned_data['date_added'] 
     date_modified = item_form.cleaned_data['date_modified'] 
     date_bought = item_form.cleaned_data['date_bought'] 
     shopping_list = item_form.cleaned_data['shopping_list'] 
     quantity = item_form.cleaned_data['quantity'] 
     deleted = item_form.cleaned_data['deleted'] 

    return render_to_response ('base.html',{'user':user,'items':items,'item_form':item_form}, context_instance=RequestContext(request)) 

shopping_list線真的是導致許多錯誤的一部分。

回答

3

你想要的對象傳遞到形式"instance"。如果我沒有理解你的代碼,你有一個名爲「項」的單個項目:

ItemForm(request.POST or None, instance=item) 

在這種情況下,雖然,它看起來像你想有一個model formset這樣你就可以同時編輯多個項目。然後,您將傳遞您的items變量作爲「queryset」參數。

編輯:實際的解決方案是一個不同的問題,

item_form.fields["shopping_list"].initial = last_used_shoppinglist 
+0

不,不是創建模型的實例。我試圖讓shopping_list從查詢購物清單模型中獲取初始值,並且在找不到任何值時,使用今天的日期預填充該字段。 – 2012-07-21 11:33:48

+1

問題是你將'last_used_shoppinglist'分配給表單字段,這不是你想要的。嘗試item_form.fields [「shopping_list」]。initial = last_used_shoppinglist – Tom 2012-07-23 14:23:53