如何在django保存表单上添加默认值?

时间:2010-03-16 14:43:19

标签: django django-forms

我有一个对象Task和一个保存它的表单。我想自动将created_by字段指定给当前登录的用户。所以,我的观点是:

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)

问题是,您猜测,created_by字段不会被保存。有任何想法吗?感谢

1 个答案:

答案 0 :(得分:2)

您正在创建GPUser,但您没有保存它。您必须先将其保存,以便获取pk,然后才能将其分配给ForeignKey。试试这个:

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

gpuser = GPUser(user=request.user)
gpuser.save()
task.created_by = gpuser