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

from django.db import models

class ListModel(models.Model):
    task = models.CharField(max_length=255)
    status = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.task} : {str(self.status)}"

and forms.py is

from django.forms import ModelForm
from .models import ListModel

class ListForm(ModelForm):
    class Meta:
        model = ListModel
        fields = ["task", "status"]

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

task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True})

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):

def __init__(self):
    self.fields['task'].widget.attrs.update(autofocus = 'autofocus')

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:

from django.forms import ModelForm
from django import <b>forms</b>
from .models import ListModel

class ListForm(ModelForm):
    #  forms &downarrow;
    task = forms.CharField(
        max_length=255,
        #  forms &downarrow;
        widget=<b>forms.</b>TextInput(attrs={'autofocus': True})
    )

    class Meta:
        model = ListModel
        fields = ['task', 'status']
Advertisement