How to add default value on django save form?
- by Ignacio
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