开发者

Set form 'author' field to logged in user before render

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 fo开发者_高级运维r 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.


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.


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)


"Dynamic initial values"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜