简体   繁体   中英

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?

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 
from .models import ListModel

class ListForm(ModelForm):
    #  forms ↓
    task = forms.CharField(
        max_length=255,
        #  forms ↓
        widget=TextInput(attrs={'autofocus': True})
    )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM