【问题标题】:How to autofocus a Charfield in a Django ModelForm如何在 Django ModelForm 中自动聚焦 Charfield
【发布时间】:2021-04-15 08:01:00
【问题描述】:

在我的 django 应用程序中,我想在页面加载时将焦点设置到第一个 CharField(任务)。

我的 models.py

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)}"

forms.py

from django.forms import ModelForm
from .models import ListModel

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

我尝试在 CharField(在 models.py 中) 中添加以下小部件:

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

但它给出了一个 AttributeError:module 'django.db.models' has no attribute 'TextInput'

我还尝试将以下内容添加到 ListForm 类(在 forms.py 中)

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

虽然我没有收到任何错误,但是当我加载我的页面时,焦点也没有设置到任务 CharField 上。我可以做些什么来为我的 CharField 添加自动对焦?

【问题讨论】:

    标签: python django django-models django-forms modelform


    【解决方案1】:

    您混淆了 model 字段(用于在数据库中存储数据)和 form 字段,这些字段用于获取、验证和清理用户数据已进入。

    您因此与:

    from django.forms import ModelForm
    from django import forms
    from .models import ListModel
    
    class ListForm(ModelForm):
        #  forms ↓
        task = forms.CharField(
            max_length=255,
            #  forms ↓
            widget=forms.TextInput(attrs={'autofocus': True})
        )
    
        class Meta:
            model = ListModel
            fields = ['task', 'status']

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2018-11-05
      • 2014-08-05
      • 2016-01-12
      • 2023-04-09
      • 1970-01-01
      • 2019-03-21
      • 2014-06-18
      • 2011-08-11
      相关资源
      最近更新 更多