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

前端 未结 2 678
栀梦
栀梦 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 take care of this in the view:

    # views.py
    def create(request):
        if request.POST:
            form = ArticleForm(request.POST, request.FILES)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.author = request.user
                instance.save()
    
                return HttpResponseRedirect('/articles/all')
    
        else:
            form = ArticleForm()
    
        args = {}
        args.update(csrf(request))
    
        args['form'] = form 
    
        return render_to_response('create_article.html', args)
    
    # models.py
    class Article(models.Model):
        author = models.ForeignKey('auth.User')
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
提交回复
热议问题