我目前拥有的是:
<ul>
{% for object in object_list %}
<li>
<ul>
<li>{{ object.property1}}</li>
<li>{{ object.property2}}</li>
</ul>
</li>
{% endfor %}
</ul>
我想要做的是当且仅当用户按下删除按钮时调用一个方法(这将是 {{ object.remove }})。我需要在删除方法中使用对象的属性之一,因此它必须是该特定对象的remove() 调用。
我知道如何在 View 内调用函数,因为对此有很多问题,但我不确定这有什么帮助?与 AJAX 调用相同。
最佳答案
您需要从数据库获取对象,通常是通过从 URL 获取的 id 并进行调用。
例如,您有 Post
url.py
中的这一行:
urlpatterns = patterns('',
url(r'^(?P<post_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<post_id>\d+)/remove/$', views.remove, name='remove'),
# ...
)
那么你就有views.py
:
from .models import Post
def detail(request, post_id):
try:
post = Post.objects.get(pk=question_id)
except Post.DoesNotExist:
raise Http404("Error 404")
return render(request, 'detail.html', {'post': post})
def remove(request, post_id):
try:
post = Post.objects.get(pk=question_id)
post.remove()
except Post.DoesNotExist:
raise Http404("Error 404")
return render(request, 'confirm.html', {'message': 'Post was removed'})
并在您的模板中添加链接到 remove
查看:
<ul>
{% for post in post_list %}
<li>
<ul>
<li><a href="/{{ post.id }}/remove/">{{ post.id}}</a></li>
<!-- or add AJAX call to this URL -->
</ul>
</li>
{% endfor %}
</ul>
这就是 Django 中通常处理它的方式。
只要 post_id 只是一个函数参数,您就可以将其用作您自己存储的列表或字典的索引 id。但请确保您的正则表达式位于 urls.py
中规则适用于您的需求。在我的例子中r'^(?P<post_id>\d+)/remove/$'
查找整数(因为 \d+
规则)。更多信息请参见Django Documentation
关于python - 单击时从 Django 模板调用对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28180425/