tags:

views:

28

answers:

1

I've tried 3 different approaches, and nothing seems to work. Here's my view:

def my_view(request):
    if request.method == 'POST':
        form = DealershipForm(request.POST)
        if form.is_valid():
            dealership = form.save(commit=False)
            dealership.entered_by = User(id=2)
            dealership.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})

I've also tried modifying the cleaned_data just after form.is_valid, I've tried setting initial, and instance, nothing seems to work!

+2  A: 
DealershipForm(request.POST, instance=Dealership(my_field="my_value"))

Should work.

EDIT:

Your code after modification:

def my_view(request):
    if request.method == 'POST':
        form = DealershipForm(request.POST, instance=Dealership(entred_by=User(id=2))
        if form.is_valid():
            form.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})

Edit after your comment:

def my_view(request):
    if request.method == 'POST':
        instance = Dealership()
        instance.entered_by_id = 2
        form = DealershipForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            messages.success(request, 'Dealership added.')
    else:
        form = DealershipForm()
    return response(request, template='misc/my_template.html',
                    vars={'form':form})
Tomasz Wysocki
If I do `DealershipForm(request.POST, instance=Dealership(entered_by=User.objects.get(id=2)))` then it works, but then I'm hitting the DB to look up the user object, no? Why should I need to do that when I'm just saving the ID?
Mark
What about now?
Tomasz Wysocki
Ah...yes, the `_id` trick makes it work. Thank you so much!
Mark