Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing ID of form input element in django when it's created

When django creates a form the id for the input are the following:

<input id="id_name"..../>

How do I change the id to let's say "test"?

Has to be somehow in the form.py, right?

class ReviewForm (forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ReviewForm, self).__init__(*args, **kwargs)
        self.fields['location']=forms.CharField(label='', required=False)
        self.fields['review']=forms.CharField(label='', required=False)
like image 797
Tom Avatar asked Aug 19 '15 00:08

Tom


People also ask

How do I override a form in Django?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.


2 Answers

When you instantiate your form, you'll want to call it with the auto_id keyword set to a string with the format character '%s' which will be replaced by the field name.

So you'll want to do this:

ReviewForm(auto_id="test_%s")

And your ids will be generated with test_ as a prefix, followed by the field name.

Direct from the Django 1.8 docs:

Use the auto_id argument to the Form constructor to control the id and label behavior.

...

If auto_id is set to a string containing the format character '%s', then the form output will include tags, and will generate id attributes based on the format string. For example, for a format string 'field_%s', a field named subject will get the id value 'field_subject'.

https://docs.djangoproject.com/en/1.8/ref/forms/api/#configuring-form-elements-html-id-attributes-and-label-tags

like image 125
Andrew Leinung Avatar answered Sep 18 '22 23:09

Andrew Leinung


I found a way to do this, explained here

[class ReviewForm (forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ReviewForm, self).__init__(*args, **kwargs)
        self.fields\['location'\]=forms.CharField(widget=forms.TextInput(attrs={'id':'myField'}),label='', required=False)
        self.fields\['review'\]=forms.CharField(widget=forms.TextInput(attrs={'id':'myField'}),label='', required=False)
like image 24
Tom Avatar answered Sep 17 '22 23:09

Tom