Set form 'author' field to logged in user

2020-08-05 09:59发布

问题:

I want to set the default value of my forms 'author' field (models.ForeignKey(User)) to the currently logged in user. I want to do this before the entry is saved so when creating an entry the user does not have to select themselves in order for the form to validate.

I tried setting the value in my form init function, but there is not reference to the request object so it seems impossible?

I am not using the django admin panel for this application.

回答1:

Dynamic initial values worked for me, for a default Django form view:

if request.method == 'POST': 
    form = ContactForm(request.POST) 
    if form.is_valid(): # All validation rules pass
        # Process the data in form.cleaned_data
        return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
    form = ContactForm(initial={'author': request.user }) 

return render_to_response('contact.html', {
    'form': form,

This sets the initial value in the author drop-down for an unbound form, the user could still change it whilst editing.



回答2:

You can set the author attribute when you're processing the form in the view (note that in my example, the 'MyForm' class is a Model Form, and I exclude the 'author' field from the form):

def submit_form(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            submission = form.save(commit=False)
            submission.author = request.user
            submission.save()
            return http.HttpResponseRedirect('submitted/')
    else:
        form = MyForm()

  context = Context({'title': 'Submit Form', 'form': form, 'user': request.user})
  return render_to_response('form.html', context)


回答3:

"Dynamic initial values"



标签: django