views:

117

answers:

1

I have an object Task and a form that saves it. I want to automatically asign created_by field to the currently logged in user. So, my view is this:

def new_task(request, task_id=None):
    message = None
    if task_id is not None:
        task  = Task.objects.get(pk=task_id)
        message = 'TaskOK'
        submit = 'Update'

    else:
        task = Task(created_by = GPUser(user=request.user))
        submit = 'Create'

    if request.method == 'POST': # If the form has been submitted...
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=False);
            task.created_by = GPUser(user=request.user)
            task.save()
            if message == None:
                message = 'taskOK'
            return tasks(request, message)
    else:
        form  = TaskForm(instance=task)
    return custom_render('user/new_task.html',
                         {'form': form, 'submit': submit, 'task_id':task.id},
                         request)

The problem is, you guessed, the created_by field doesn't get saved. Any ideas? Thanks

+2  A: 

You are creating GPUser, but you don't save it. You must save it first, so it gets pk and only after that it can be assigned to a ForeignKey. Try this:

task.created_by = GPUser.object.create(user=request.user)

or

gpuser = GPUser(user=request.user)
gpuser.save()
task.created_by = gpuser
gruszczy
OK, I'm an idiot. GPUser is actually the user's profile, and what I need is to retrieve that instead of creating a new one.
ign