1

I'm trying to have a Django Form from a query, but I keep doing it the wrong way. Checked out a few examples, but I'm doing it a bit different. Here's my code,

Le Form

class ItemForm(ModelForm):

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

And part of the view

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

The shopping_list line is really leading to many errors.

Dennis Kioko
  • 741
  • 4
  • 13
  • 27

1 Answers1

3

You want to pass the object into the form as "instance". If I understand your code correctly and you had a single Item named "item":

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

In this case though, it looks like you want a model formset so you can edit multiple items at once. Then you would pass your items variable in as the "queryset" parameter.

EDIT: Actual solution is for a different problem,

item_form.fields["shopping_list"].initial = last_used_shoppinglist
Tom
  • 22,301
  • 5
  • 63
  • 96
  • Nope, not creating instance of a model. I am trying to have shopping_list take initial values from querying the shopping list model and when no values are found, pre populate the field with today's date. – Dennis Kioko Jul 21 '12 at 11:33
  • 1
    The problem is you're assigning `last_used_shoppinglist` to the form field, which is not what you want. Try item_form.fields["shopping_list"].initial = last_used_shoppinglist – Tom Jul 23 '12 at 14:23