djangomodelsurlconf

Reverse url in django model help_text


I want to add a link to terms and conditions in help_text property of django model_field, basically I would like to write code like:

 class UserRegisterData(models.Model):

    accepted_terms = models.BooleanField(
           ...
           help_text = u""Terms and conditions are avilable on <a href="{reg}">this iste</a> stronie""".format(reg = reverse("terms"))
     )

whis obviously fails, because urlconfs are unprepared while models are being instantiated.

I even tried to wrap help_test in SimpleLazyObject but it still didn't work.

I'd rather didn't touch the template code. Is there any way to achieve this without hardcoding url in either string or settings?


Solution

  • As of Django 2.1 django.utils.translation.string_concat() has been removed and marked as deprecated in earlier versions.

    In order to evaluate lazy objects in a str.format() like syntax you now have to use format_lazy() instead.

    Example:

    my_field = forms.BooleanField(
            # ...
            help_text=format_lazy(
                '''
                Please click <a href='{}'>here</a>.
                ''',
                reverse_lazy('my-viewname')
            )
    )
    

    Note that you may have to explicitly mark the help_text content as safe for HTML output purposes. A possible solution to do so could be within the template and the help of the safe filter:

    {{ my_field|safe }}