首页 > 解决方案 > 如何将类添加到 django ModelForms 文件字段

问题描述

我想为我的文件字段添加类作为其他元素(虽然我不能使用attrs={"rows": "1", "class": "form-control"}我不知道如何继续),但在他们将其应用于其他字段的每个地方都找不到任何指南。表格.py

from django import forms
from .models import MedicalRecords

class UpdateMedicalRecordForm(forms.ModelForm):
    class Meta:
        model = MedicalRecords
        fields = ("title", "file", "doctor")

        widgets = {
            "title": forms.Textarea(attrs={"rows": "", "class": "form-control"}),
             "file": ?? (how to add class as above),
        }

标签: djangodjango-forms

解决方案


根据 Django 小部件类(有关可用的小部件/html 输入类型类型,请参阅此链接):

from django import forms
from .models import MedicalRecords

class UpdateMedicalRecordForm(forms.ModelForm):
    # we can directly specify attributes to individual fields like this
    title = forms.CharField(max_length = 100, widget = forms.TextInput(attrs={'class':'title_class_name', 'id':'title_id'}))
    file = forms.ImageField(widget = forms.FileInput(attrs={'class':'file_class_name', 'id':'file_id'}))
    
    class Meta:
        model = MedicalRecords
        fields = ("title", "file", "doctor")
        
        # or we can use widgets like this
        widgets = {
            "title": forms.Textarea(attrs={"rows": "", "class": "title_class_name"}),
             "file": forms.FileInput(attrs={"rows": "", "class": "file_class_name"}),
        }

推荐阅读