我有ManyToMany
字段的模型,它连接了用户......所以,我的模板中需要if-else
函数,可以检查当前已验证的用户是否连接到模型。我试图这样做,但做错了......
我的模型article
:
from django.db import models
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Article(models.Model):
class Meta():
db_table = 'article'
article_users = models.ManyToManyField(User, null=True, blank=True, default=None)
article_title = models.CharField(max_length=200, blank=False, null=False)
article_content = models.IntegerField(choices=CONTENT_CHOICES, null=True, blank=True)
我的views.py
:
from django.shortcuts import render, render_to_response, redirect, Http404
from article.models import Article
from django.core.context_processors import csrf
from django.contrib import auth
from django.contrib.auth.models import User
from django.template import RequestContext
# Create your views here.
def article(request, article_id=1):
args = {}
args.update(csrf(request))
args['article'] = Article.objects.get(id=article_id)
args['username'] = auth.get_user(request).username
users = args['article'].article_users
return render_to_response('article.html', args, context_instance=RequestContext(request))
模板:
{% if article.article_users = user %}
<p>Purchased</p>
{% else %}
<input type="submit" value="Buy">
{% endif %}
修改
{% if user in article.article_users %}
<p>Purchased</p>
{% else %}
<input type="submit" value="Buy">
{% endif %}
答案 0 :(得分:1)
尝试使用
{% if user in article.article_users %}
答案 1 :(得分:0)
# user -- current user
#article.article_users -- article users
{% if user in article.article_users %}
应该进行预定的检查。