0

I want to convert something like that id,name to something like that "id","name" in django template.

I looked at django template built in tags but none of them works.

Does anyone have an idea to achieve it?

2
  • If you try to write a CSV file, you should not do that through templates. Commented Jun 24, 2021 at 9:18
  • No, I just try to auto generate serializer file for django rest framework with some options Commented Jun 24, 2021 at 9:21

3 Answers 3

2

you can do this by writing a custom Template Tag:

besides your templates folder add a directory named templatetags.

create convert_tags.py in your templatetags directory:

# convert_tags.py
from django import template

register = template.Library()

@register.filter()
def add_quotes(value: str):
    """ Add double quotes to a string value """
    return f'"{value}"'

In your templates load convert_tags:

<!-- template.html -->
{% load convert_tags %}

{{ your_str|add_quotes }}
Sign up to request clarification or add additional context in comments.

2 Comments

I think you misunderstand me the id,name is just a string all I need is to add double quotes to them to be like that "id","name"
The problem that id,name is in one variable not seprated so it's like that I have a variable called fields which equal to id,name
2

You can simply

"{{ id }}", "{{ name }}"

Or you can define a custom template tag to do this dynamically

from django import template
register = template.Library()

@register.simple_tag
def quote(str):
    return f'"{str}"'

And in your template

{{ id | quote }}, {{ name | quote }}

1 Comment

The problem that id,name is in one variable not seprated so it's like that I have a variable called fields which equal to id,name
2

Thanks for everyone, I solved it by creating a custom template tag

Here's the code :

from django import template

register = template.Library()

def add_quote(var):
    return '"{0}"'.format(var)

@register.filter()
def add_quotes(value):
    """ Add double quotes to a string value """
    excluded_fields = value.split(',')
    return ",".join(add_quote(i) for i in excluded_fields)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.