模板中带有参数的函数。 Django的 [英] Function with arguments in a template. Django

查看:152
本文介绍了模板中带有参数的函数。 Django的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,显示一个用户关注的用户列表。我希望该用户能够删除他关注的一个用户,这要感谢一个按钮。
我有一个删除关系的函数remove_relationship。



这是我的模型中的函数。py:

 类UserProfile(models.Model):
(...)

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

我想将此函数传递到模板中:

  {%for user in以下%} 
< form method = post>
{%csrf_token%}
<输入type = submit value =删除 onclick = remove_relationship />
< / form>
{%endfor%}

问题是我无法在自己的论点中传递参数模板。那么,如何使每个按钮删除与正确用户的关系呢?



我在该主题上看到了另一个问题,但看起来并不能解决我的问题(http://stackoverflow.com/questions/1333189/django-template-system-calling-a-function-inside-a-model)



谢谢

解决方案

似乎您将客户端代码(JavaScript)与服务器端(Django)混淆了。



要获取相关的用户ID,您可以在表单中添加其他隐藏字段:

  {%为以下%中的用户}} 
< form method = post action = {%url views.remove_relationship%}>
{%csrf_token%}
<输入类型= hidden name = user_id value = {{user.id}}>
< input type = submit value =删除 />
< / form>
{%endfor%}

然后创建 remove_relationship 视图根据您现在在 request.POST ['user_id']

In my template, I display a list of users a user follows. I would like the user to be able to delete one of the users he follows thanks to a button. I have a function remove_relationship that deletes a relationship.

Here is the function in my models.py:

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

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

I would like to pass this function into my template:

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

The thing is that I can't pass argument in my template. So how can I do so that each button deletes the relationship with the right user?

I saw an other question on this topic, abut it looks like it doesn't solve my problem (http://stackoverflow.com/questions/1333189/django-template-system-calling-a-function-inside-a-model)

Thank you for your help.

解决方案

It looks as though you are confusing client-side code (JavaScript) with server-side (Django).

To get the relevant user ID submitted you could add an additional hidden field to the form:

{% 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%}

Then create a remove_relationship view that does the deletion on the server side, based on the user id you'll now find in request.POST['user_id']

这篇关于模板中带有参数的函数。 Django的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆