create custom views for django-tagging
-
14-03-2021 - |
문제
I'm currently working on django tagging. I want to retrieve all the entries from my given model which are associated with a particular tag. But i don't want to use the generic views. So how should i design my views to get this done and how can i render this in my template?
해결책
Considering Element is your class from your model.
In your view
from django.db import models
from tagging.fields import TagField
from tagging.models import Tag
def myView(request,slug,tag){
user = request.user
element = Element.objects.get(slug=slug)
#getting all tags added on the given element
tags = Tag.objects.get_for_object(element)
#getting all elements containing the given tag
taggedElement = Element.objects.filter(tags__contains=tag)
template = "elements/elements.html";
context = {
'taggedElement':taggedElement ,
'tags':tags,
'user':user,
}
return render_to_response( template, context, context_instance=RequestContext(request))
}
Then in your template (elements.html)
{% for tag in tags%}
<div class="tag">{{tag}}</div>
{% endfor %}
제휴하지 않습니다 StackOverflow