How to add default value on save form?

Posted by Ignacio on Stack Overflow See other posts from Stack Overflow or by Ignacio
Published on 2010-03-16T14:43:19Z Indexed on 2010/03/16 14:46 UTC
Read the original article Hit count: 275

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about django

Related posts about django-forms