2015-05-04 68 views
0

我與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 %} 

回答

1

嘗試使用

{% if user in article.article_users %} 
+0

在'EDIT'下 - 我的更新模板。它仍然不起作用...購買後,用戶迷上了文章和它的平衡也改變了,但我仍然看到輸入按鈕,但不是'

...

'標籤。 –

0
# user -- current user 
#article.article_users -- article users 
{% if user in article.article_users %} 

應該做的意圖檢查。

+0

在編輯下 - 我更新的模板。而且它仍然不起作用...購買後,用戶連接到文章和其平衡也改變了,但我仍然看到輸入按鈕,但不是'

...

'標籤 –

+0

您能打印/顯示文章。 article_users模板上的值? – moonstruck

+0

我該怎麼做?如果你的意思是'{{article.article_users}}',我得到了'沒有提供異常消息'。如果我把'{{article.article_users.user.username}}這樣的東西 - 我沒有錯誤,但沒有信息...或者我做錯了什麼? –