'How does "template.Library()" and "get_related_name" work in django?
I'm working on a basic social media django project with the help of an udemy course. The following are the models i created:
group : models.py
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(allow_unicode=True,unique=True)
description = models.TextField(blank=True,default='')
description_html = models.TextField(editable=False,default='',blank=True)
members = models.ManyToManyField(User,through="GroupMember")
class GroupMember(models.Model):
group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE)
user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE)
post : models.py
class Post(models.Model):
user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
group = models.ForeignKey(Group,related_name='posts',null=True,blank=True)
And the part that does not make any sense to me is the following:
post_list.html
{% for member_group in get_user_groups %}
<a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name
}}</a></li>
{% endfor %}
{% for other_group in get_other_groups %}
<a href="{% url 'groups:single' slug=other_group.slug %}">{{ other_group.name }}</a></li>
{% endfor %}
What does "get_user_groups","get_other_groups" and "register = template.Library()" mean here and how are they related? Also what are they trying to achieve here? I'm clueless guys, help me out.
Solution 1:[1]
That's an example of custom template tags. There is probably a custom_tags.py file where you created the custom template tags within a folder called template_tags that shows the work being done to create the content of those tags.
get_user_groups isn't pulling from views.py or directly referencing your models.py. Instead, it's referencing queries stored in custom_tags.py
Find a detailed breakdown here: https://medium.com/@hiteshgarg14/creating-custom-template-tags-in-django-application-7bd1dcfeb144
This can be useful if you want to display content from a query on a variety of different views without having to redundantly insert that query into multiple functions within views.py. In this case, it looks like it will be used to insert group membership information within a variety of views by using custom tags.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ed Kohler |