在models.py文件中获取当前登录的Django用户? [英] Get the currently logged in Django user in a models.py file?

查看:391
本文介绍了在models.py文件中获取当前登录的Django用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一款存储有关文章的基本信息的模型还存储当前登录用户的名称,这是可能的吗?或者是需要在views.py文件中完成。

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.

这是我的代码:

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

以下是处理views.py中的文章模型的功能:

Here's the function that handles the Article model located in views.py:

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)

如何让它成为一个新的文章创建时,用户名应该以作者的方式存储在pub_date自动存储当前日期的方式上?

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?

推荐答案

您需要在视图中关注此问题:

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

这篇关于在models.py文件中获取当前登录的Django用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆