Get the currently logged in Django user in a models.py file?

前端 未结 2 683
栀梦
栀梦 2020-12-19 16:20

I\'m trying to make a model that\'s stores basic information about an Article also store the name of the currently logged in user, is this possible? or is it something that

2条回答
  •  执笔经年
    2020-12-19 16:50

    You'll need to do it in the view, as the model has no idea where it is being created from. Pass commit=False to the form.save() method so it doesn't commit the data to the database, set the author from the request, and then save manually:

    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        return HttpResponseRedirect('/articles/all')
    

提交回复
热议问题