سؤال

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?

هل كانت مفيدة؟

المحلول 2

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 }}

نصائح أخرى

I think this is what django.core.urlresolvers.reverse_lazy is meant for.
For information: it was added to django in 1.4, so if you're using an earlier version, you'll need to upgrade.


As mentionned in the comments, you'll still need to go around the string formatting which breaks the "laziness" of the URL reverse:

from django.utils.translation import string_concat

# ...

help_text = string_concat( # Happens to be lazy!
                u'Terms and conditions are available on <a href="', 
                reverse_lazy("terms"),
                u'">this site</a>"',
)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top