Skip to content
Advertisement

How to autofocus a Charfield in a Django ModelForm

In my django app I want to set focus to the first CharField (task) when the page loads.

my models.py is

JavaScript

and forms.py is

JavaScript

I have tried adding the following widget in my CharField (in models.py):

JavaScript

but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput'

I have also tried adding the following to the ListForm class (in forms.py):

JavaScript

though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField?

Advertisement

Answer

You are confusing model fields (which are used to store data in the database), and form fields, which are used to obtain, validate and clean data the user has entered.

You thus work with:

JavaScript
Advertisement