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

前端 未结 2 720
栀梦
栀梦 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')
    

提交回复
热议问题