2013-04-27 50 views
0

我正在開發一個項目,該項目允許用戶創建博客並允許其他用戶對每個其他博客發表評論。當用戶創建博客時,他們具有一定的博客能力所有者可以執行諸如刪除他們自己的評論,我刪除評論的方式是通過超鏈接傳遞值ID。 每個人都可以看到對方的博客,但我只想顯示刪除超鏈接到博客的所有者,所以只有創建博客的用戶。我怎樣才能做到這一點?通過模板Django僅顯示超鏈接到對象的創建者

我的模型

class Blog(models.Model): 
    user = models.ForeignKey(User) 
    name = models.CharField(max_length=100) 
    created = models.DateTimeField(auto_now_add=True) 
    description = models.TextField() 

def Bloglook(request ,animal_id): 
     Blog = Blog.objects.get(pk=animal_id) 
    return render(request,'blog.html',{blog':blog}) 

我blog.html

{% if blog %} 
    {{blog.name%}} 
{% endif %} 

如何我只能顯示此鏈接到誰創造了博客的人?

<a href="{% url world:BlogDelete blog.id %}"> Delete blog</a> 

回答

1

使用RequestContext傳遞給它傳遞request.user變量模板的模板,您可以使用它來檢查博客的所有者。

更改您的視圖中使用RequestContext作爲

def Bloglook(request ,animal_id): 
    Blog = Blog.objects.get(pk=animal_id) 
    return render_to_response('blog.html',{blog':blog}, 
      context_instance = RequestContext(request)) 

然後在模板做

{% if blog.owner == request.user %} 
    <a href="{% url world:BlogDelete blog.id %}"> Delete blog</a> 
{%endif%} 
+0

羅漢,那麼其他沒有被授權的人呢? – donkeyboy72 2013-04-27 06:08:23

+0

這對隱藏的用戶也是隱藏的。只有當用戶是所有者時,他纔會看到刪除鏈接 – 2013-04-27 06:09:35

+0

@Jacob,未經身份驗證的用戶將是匿名用戶,這將與博客所有者用戶不匹配。 – Rohan 2013-04-27 06:10:36

1
{% if request.user==blog.user %}<a href="{% url world:BlogDelete blog.id %}"> Delete blog</a>{% endif %} 

編輯:

這也將是從unautenticated用戶隱藏。只有當用戶是所有者,然後他會看到刪除鏈接

此外,您還可以繼續使用render,沒有必要改變,以render_to_response.

+0

謝謝AKSHAR raaj,我一定要勾選羅漢答案,因爲他之前,你,但我會回答你1分鐘給你一個+1:D – donkeyboy72 2013-04-27 06:13:20

+0

確保將'django.core.context_processors.request'添加到你的'TEMPLATE_CONTEXT_PROCESSORS'中,以便你可以訪問你的模板中的'request'。 – 2013-04-27 06:14:45

+0

謝謝你的幫助 – donkeyboy72 2013-04-27 06:39:32