Currently, I can set the the current_user in the views.py for a form, which requires the user object to validate the post (and its origin).

Is there a better way to more eloquently set the user in a form than what I've posted below? Note, this is in views.py and I have no altered forms or models to tackle this aspect.

def index(request):
    article = Article.objects.all()
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        # This segment below is the focal point of my question:
        if form.is_valid() and request.user.is_authenticated:
            form_object = form.save(commit=False)
            form_object.author = request.user
            return HttpResponseRedirect('to somewhere over the rainbow')
        # stuff

The code works. It just seems gimmicky to use a non-committed form, store it in a variable, alter the form object, then ultimately save it.

  • \$\begingroup\$ Well, the right way to deal with this would be the have a Form which you can then prepopulate with the data you need \$\endgroup\$ Jan 3, 2021 at 20:06
  • \$\begingroup\$ Ah, understood. I'll edit ArticleForm in this example to do that. \$\endgroup\$ Jan 5, 2021 at 22:35


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.