如何显示使用{%if user.is_authenticated == post.author%}创建的帖子用户?

时间:2016-03-14 02:12:43

标签: python django

这就是我要做的事情:用户可以创建社区(或发布),我希望在我的模板中的某些位置显示用户创建的社区。 所以在models.py我有

.xcodeproject

和我的views.py

class Category(models.Model): 
    name = models.CharField(max_length=128, unique=True)
    description = models.TextField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

这是我的简化类别视图

@login_required
def add_category(request):
    if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
        return render(request,'main/category_already_exists.html')
    if request.method == 'POST':
        category = Category(author=request.user)
        form = CategoryForm(request.POST, request.FILES, instance=category)
        if form.is_valid():
            form.save(commit=True)
            return redirect('category', category_name_url=category.name)

    else:
        form = CategoryForm()
    context = {
        "form":form
    }
    return render(request, 'main/add_category.html',context)

所以我在我的模板中尝试了这个,认为它肯定会起作用

def category(request, category_name_url):
    category_name = decode_url(category_name_url)


                category = Category.objects.get(name=category_name)

    context = {

                "category":category,



        }
    return render(request, "main/category.html", context)

但是当它打印你好时它会打印出来,这是我的错吗?

1 个答案:

答案 0 :(得分:1)

{% if user.is_authenticated == category.author %}

不是有效的支票。 user.is_authenticated返回布尔值(True / False),category.authoruser对象。您正在检查错误是否正确。

请改为尝试:

{% if user.is_authenticated and user == category.author %}

因为category.authorUser个实例