简体   繁体   English

在models.py文件中获取当前登录的Django用户?

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

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 needs to be done in the views.py file. 还是需要在views.py文件中完成的事情。

Here's my code: 这是我的代码:

from django.db import models
from time import time

from django.contrib.auth.models import User


def get_upload_file_name(instance, filename):
    return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)


# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(User.get_username()) #AUTOMATICALLY STORE USERNAME
    body = models.TextField()
    pub_date = models.DateTimeField(auto_now=True)
    likes = models.IntegerField(default=0)
    thumbnail = models.FileField(upload_to=get_upload_file_name)

    def __unicode__(self):
        return self.title

Here's the function that handles the Article model located in views.py: 这是处理位于views.py中的Article模型的函数:

def create(request):
    if request.POST:
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/articles/all')

    else:
        form = ArticleForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form 

    return render_to_response('create_article.html', args)

How can I make it so that when a new article is created, the username should be stored as the "author" the same way the "pub_date" automatically stores the current date? 我该如何做,以便在创建新文章时,用户名应该以“作者”的方式存储,就像“ pub_date”自动存储当前日期一样?

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')

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: commit=False传递给form.save()方法,这样它就不会将数据提交到数据库,从请求中设置作者,然后手动保存:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM