开发者

How to add default value on django save form?

开发者 https://www.devze.com 2022-12-23 16:16 出处:网络
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:

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号