Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

how to add class to django ModelForms file field

I want to add class for my file field as other elements(while I can't use attrs={"rows": "1", "class": "form-control"} I've no idea how to go on), couldn't find any guides about that every where they applied that on other fields. forms.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),
        }
question from:https://stackoverflow.com/questions/65920518/how-to-add-class-to-django-modelforms-file-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per Django widget classes (see this link for available types of widget/html input types):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...