我與ManyToMany
字段模型,即迷上了用戶...所以,我需要if-else
功能在我的模板,即可以檢查是目前認證用戶連接到模型,或不。我想這樣做,但做了錯事......檢查當前用戶ID
我的模型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 %}
在'EDIT'下 - 我的更新模板。它仍然不起作用...購買後,用戶迷上了文章和它的平衡也改變了,但我仍然看到輸入按鈕,但不是'
...
'標籤。 –