How do I set custom HTML attributes in django forms

0 votes

I have a Django form that is part of page. Lets say I have a field:

search_input = forms.CharField(_(u'Search word'), required=False)

I can access it only in template via {{ form.search_input }}. How to set custom HTML attrs (such as name and value)? I would like to find flexible solution, that would allow me to add any needed custom attributes to all types of fields.

But using attrs gives me (if used with CharField):

__init__() got an unexpected keyword argument 'attrs'
Jul 29, 2020 in Python by kartik
• 37,510 points
2,582 views

1 answer to this question.

0 votes

Hello @kartik,

You can change the widget on the CharField to achieve the effect you are looking for.

search_input = forms.CharField(_(u'Search word'), required=False)
search_input.widget = forms.TextInput(attrs={'size': 10, 'title': 'Search',})

Hope it helps!!

Thank You!!

answered Jul 29, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How should I write tests for Forms in Django with Python?

from django.tests import TestCase class MyTests(TestCase): ...READ MORE

answered Nov 20, 2018 in Python by Nymeria
• 3,560 points
1,204 views
0 votes
0 answers

how do i install django in my system for the project?

can you tell me the procedure for ...READ MORE

May 3, 2019 in Python by Waseem
• 4,540 points
477 views
0 votes
1 answer

How do I run a set of code for all the requests in Flask?

Hi, You can use dedicated hooks(decorators) called before ...READ MORE

answered Jun 21, 2019 in Python by Shabnam
• 930 points
586 views
0 votes
0 answers

How do I fix this Set function in python?

I have the following code below I ...READ MORE

May 20, 2020 in Python by Olufemiodubote
• 120 points
714 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,097 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,246 views
0 votes
1 answer

How do I get user IP address in django?

Hii Kartik, check uwsgi + django source code and pass static param ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,880 points
8,732 views
0 votes
1 answer

How do I filter query objects by date range in Django?

Hello @kartik, Use Sample.objects.filter(date__range=["2020-01-01", "2020-01-31"]) Or if you are just ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,880 points
33,050 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP