I have a template that displays a list of objects from the database.
{% for item in items %}
<li>
{{ item }} - Tags:
{% for tag in item.tags.all %}
<a href="/{{ user }}/{{ tag }}/">{{ tag }}</a>
{% endfor%}
<br>
{{ item.notes }}
<br>
{{ item.date_modified|humanize_time_diff }}
<a href="">delete</a>
</li>
{% endfor%}
How can I allow a user to delete one of these objects, while staying on the same page?
H开发者_开发知识库ere is my view function:
def tag_page(request, username, tag=None):
if username == request.user.username:
if tag and tag in request.user.userprofile.tag_set.all():
tag = Tag.objects.get(title=tag)
items = tag.item_set.all()
return render_to_response("tag_page.html", { 'user': request.user ,
'tag': tag,
'items': items })
else:
items = request.user.userprofile.item_set.all()
return render_to_response("tag_page.html", { 'user': request.user ,
'tag': tag,
'items': items })
else:
raise Http404
It's a simple, but longer story. To make it short, you can check this article: http://www.arnebrodowski.de/blog/484-Django-Ajax-comment-deletion.html which contains a snippet (written with YUI, but its jQuery counterpart would be very similar: http://api.jquery.com/jQuery.ajax/) that performs AJAX query, which in turn deletes a comment.
The comment deletion view is built into django.contrib.comments.views
, and you have to write your own view for deleting tags. It should look roughly like this:
def delete_tag_view(request, tag):
tag_to_delete = get_object_or_404(Tag, title=tag)
tag_to_delete.delete()
return HttpResponse('OK') # This should really return JSON and/or some relevant HTTP status code
Of course, you need to hook this into your URLconf:
url(r'/tag/delete/(?P<tag>\w+)', 'tags.views.delete_tag_view', name='tag-delete')
精彩评论