Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a link in label of a form field

Tags:

django

I want to have a checkbox for terms and conditions, label of which should contain a link to a page with, well, terms and conditions.

The following field will have the label with the tags escaped.

BooleanField(label="I agree to <a href='terms-conditions.html'>terms&conditions</a>")
like image 945
luntain Avatar asked Dec 22 '08 11:12

luntain


People also ask

How do you add a link to a label in HTML?

To make a hyperlink in an HTML page, use the <a> and </a> tags, which are the tags used to define the links. The <a> tag indicates where the hyperlink starts and the </a> tag indicates where it ends. Whatever text gets added inside these tags, will work as a hyperlink. Add the URL for the link in the <a href=” ”>.

What is a field label in a form?

A field label is descriptive text you create that appears with or covers the field on the form, and helps the user understand the field. Label text might name a field -- for example: To, From, Author, Subject, or Date. Or it might describe a user action -- for example, "Enter a product name."


2 Answers

Import django's mark_safe from utils.safestring as explained at http://www.kelvinism.com/howtos/using-html-django-form-label/

From the link:

from django.utils.safestring import mark_safe
from django import forms

class AccountForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(), 
                           max_length=15, 
                           label=mark_safe('Your Name (<a href="/questions/whyname/" target="_blank">why</a>?)'))
like image 118
ken Avatar answered Sep 21 '22 15:09

ken


Here is the correct link to the Django documentation on the subject of iteration over the form.

What you want is:

<form method="post">
{% for field in form %}
    <p>
        {{ field.errors }}
        {{ field.label_tag }}: {{ field }}
        {% if field.name == "toc" %}
          <a href="{% url terms %}">Terms and Conditions</a>
        {% endif %}
    </p>
{% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>
like image 22
aigarius Avatar answered Sep 21 '22 15:09

aigarius