Reputation: 10251
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.
Upvotes: 0
Views: 2349
Reputation: 3297
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.
Upvotes: 5
Reputation: 1767
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)
Upvotes: 2