Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize django form label

class permForm(forms.Form):
    def __init__(self, data=None, **kwargs):
        super(permForm, self).__init__(data, **kwargs)

        for item in list(AdminMenu.objects.filter(parent_id=0)):
            self.fields['menu_%d' % item.id] = forms.BooleanField(label=item.title)
            for childitem in list(AdminMenu.objects.filter(parent_id=item.id)):
                arr=[]
                arr.append(str(item.id))
                arr.append(str(childitem.id))
                self.fields['menu_%s' % '_'.join(arr)] = forms.BooleanField(label=childitem.title)

This will return

category: checkbox

add category: checkbox

List Category:checkbox

Food: checkbox

Add Fooditems: checkbox

List Fooditem: checkbox

Tables: checkbox

Add Tables: checkbox

List Tables: checkbox

Users: checkbox

View Users: checkbox
How can i display it as following

category: checkbox

add category: checkbox

List Category:checkbox

Food: checkbox

Add Fooditems: checkbox

List Fooditem: checkbox

Tables: checkbox

Add Tables: checkbox

List Tables: checkbox

Users: checkbox

View Users: checkbox

I WANT TO MAKE PARENT CATEGORY LABEL BOLD TO DISTINGUISH IT FROM CHILD. POSSIBLE? I DONT WANT TO USE HARD CODED FORMS

like image 665
sumit Avatar asked Apr 26 '12 11:04

sumit


People also ask

How to customize Django forms for good design?

But Django doesn’t easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id to individual fields in forms.

How many fields can a form have in Django?

Let’s say, we are having a simple Django form that will have four fields: We are not going to discuss how we create this form but rather than we are going to see how to customize the frontend of Django forms.

How to validate every field in Django?

Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. label is used to change the display name of the field. label accepts as input a string which is new name of field.

What is a form class in Django?

At the heart of this system of components is Django’s Form class. In much the same way that a Django model describes the logical structure of an object, its behavior, and the way its parts are represented to us, a Form class describes a form and determines how it works and appears.


1 Answers

Here's an example of how to add some HTML to form labels:

from django.template.defaultfilters import mark_safe


class MyForm(forms.Form):
    my_field = forms.CharField(
        max_length=100,
        label = mark_safe('<strong>My Bold Field Label</strong>')
    )
like image 162
Brandon Avatar answered Oct 26 '22 22:10

Brandon