Skip to content

Commit

Permalink
Merge pull request #21 from matagus/update-template-tag-to-use-modern…
Browse files Browse the repository at this point in the history
…-django-stuff

 Refactored template tag to be a simple_tag
  • Loading branch information
matagus authored Feb 6, 2024
2 parents 88c1bb3 + 04edc74 commit 1912dd8
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 26 deletions.
5 changes: 0 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,3 @@ repos:
hooks:
- id: pyupgrade
args: [--py312]

- repo: https://github.com/asottile/reorder_python_imports
rev: v3.12.0
hooks:
- id: reorder-python-imports
31 changes: 11 additions & 20 deletions generic_links/templatetags/generic_links_tags.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,29 @@
"""
Several useful template tags!
"""

from __future__ import annotations

from django import template
from django.db.models import Model
from django.db.models import QuerySet

from generic_links import utils


register = template.Library()


class RelatedLinksNode(template.Node):
def __init__(self, context_var, obj, is_external):
self.context_var = context_var
self.obj_var = template.Variable(obj)
self.is_external = is_external
@register.simple_tag
def get_links_for(obj: Model, is_external: bool | None = None) -> QuerySet:
"""
Usage:
def render(self, context):
obj = self.obj_var.resolve(context)
context[self.context_var] = utils.get_links_for(obj).select_related("user").filter(is_external=self.is_external)
return ""
{% get_links_for <obj> as <some_var> %}
or
@register.tag
def get_links_for(parser, token):
"""
Usage: {% get_links_for <obj> as <some_var> %}
{% get_links_for <obj> <boolean> as <some_var> %}
"""

bits = token.split_contents()

if len(bits) != 4:
message = "'%s' tag requires three arguments" % bits[0]
raise template.TemplateSyntaxError(message)

return RelatedLinksNode(bits[3], bits[1], True)
return utils.get_links_for(obj, is_external=is_external)
2 changes: 1 addition & 1 deletion generic_links/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ def get_links_for(obj, is_external=None):
if is_external is not None:
params["is_external"] = is_external

return GenericLink.objects.filter(**params)
return GenericLink.objects.filter(**params).select_related("user")
1 change: 1 addition & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Generated by Cookiecutter Django Package
"""

from __future__ import annotations

import os
Expand Down

0 comments on commit 1912dd8

Please sign in to comment.