2
\$\begingroup\$

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
            form_object.save()
            return HttpResponseRedirect('to somewhere over the rainbow')
    else:
        # 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.

\$\endgroup\$
2
  • \$\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\$ Commented Jan 3, 2021 at 20:06
  • \$\begingroup\$ Ah, understood. I'll edit ArticleForm in this example to do that. \$\endgroup\$ Commented Jan 5, 2021 at 22:35

0

Your Answer

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

Browse other questions tagged or ask your own question.