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

时间:2014-02-13 00:40:42

标签: python django

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

这是我的代码:

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中的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)

如何创建新文章时,用户名应该以“pub_date”自动存储当前日期的方式存储为“作者”?

2 个答案:

答案 0 :(得分:5)

您需要在视图中处理此问题:

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

答案 1 :(得分:1)

您需要在视图中执行此操作,因为模型不知道从何处创建它。将commit=False传递给form.save()方法,以便它不会将数据提交到数据库,从请求中设置作者,然后手动保存:

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