Creon12
Creon12

Reputation: 35

Placing a link with onClick property in django helptext field

I have a model form

class RegularUserFormStep1(ModelForm):

class Meta:
    model = RegularUser
    fields = ('school', 'grad_date',)
    help_texts = {'school':mark_safe("<a id='school_add' href = '#' onClick='ModalToggle('{% url 'schools_add' %}','{% url 'schools_add' %}','#form','Add school'); return false;' >Add</a>")}

But when I try to click the link, I get the Uncaught SyntaxError: Unexpected token }

So, I want to ask what is the right way to embed links containing django template variables in field helptext.

Upvotes: 0

Views: 1250

Answers (1)

Alasdair
Alasdair

Reputation: 309049

The string is not treated as a Django template, so you can not use the url template tag.

Instead of

{% url 'schools_add' %}

You can use the reverse to get the url

schools_add_url = reverse('schools_add')

then substitute it into your string.

help_texts = {
    'school': mark_safe(
        "<a id='school_add' href = '#' onClick='ModalToggle('%s','%s','#form','Add school'); return false;' >Add</a>" % (schools_add_url, schools_add_url)
    )
}

You should always be careful when using mark_safe for help text. In this case, you are not including any content from the user, so it's ok.

Upvotes: 1

Related Questions