2012-11-05 94 views
3

在我的模板中,我顯示了用戶關注的用戶列表。我希望用戶能夠通過按鈕刪除他關注的用戶之一。 我有一個刪除關係的函數remove_relationship。參數在模板中的函數。 Django

這裏是我的models.py功能:

class UserProfile(models.Model): 
    (...) 

     def remove_relationship(self, person): 
     Relationship.objects.filter(
      from_person=self, 
      to_person=person).delete() 
     return 

我想給這個函數傳遞到我的模板:

{% for user in following % } 
    <form method="post"> 
    {% csrf_token %} 
    <input type="submit" value="delete" onclick="remove_relationship"/> 
    </form> 
    {%endfor%} 

的事情是,我不能通過論點我的模板。那麼我該怎麼做才能讓每個按鈕都刪除與正確用戶的關係?

我看到關於此主題的其他問題,它看起來像它不能解決我的問題(http://stackoverflow.com/questions/1333189/django-template-system-calling-a-function-inside -a型)

謝謝你的幫助。

回答

5

看起來好像您將客戶端代碼(JavaScript)與服務器端(Django)混淆在一起。

要獲得提交你可以額外的隱藏字段添加到表單相關的用戶ID:

{% for user in following % } 
<form method="post" action="{% url views.remove_relationship %}"> 
{% csrf_token %} 
<input type="hidden" name="user_id" value="{{ user.id }}"> 
<input type="submit" value="delete" /> 
</form> 
{%endfor%} 

然後創建一個remove_relationship認爲確實在服務器端的缺失,基於用戶ID你」現在在request.POST['user_id']找到

+0

謝謝。當我像你說的那樣做的時候,這個關係就會被我刪除。但它會將用戶重定向到「remove_relationship」視圖。我希望用戶保持在同一頁面上。你有關於如何做到這一點的想法? –

+0

是的,只需從'remove_relationship'視圖返回'HttpResponseRedirect(reverse('your original view here'))''。 –

+0

或者,通過Ajax提交表單。但是,你需要一些Javascript來發布它,並從頁面中刪除現在刪除的內容。 –