英文:
How to make Django ModelForm filed to update the attrs, so the style can be displayed successfully
问题
from django.forms import ModelForm
from django import forms
from .models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags']
widgets = {
'tags': forms.CheckboxSelectMultiple(),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.fields['title'].widget.attrs.update({'class': 'input'})
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
I am trying to display my dynamic form with the correct styling, but this method doesn't seem to work. How can I fix it?
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.fields['title'].widget.attrs.update({'class': 'input'})
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
This doesn't seem to work.
英文:
from django.forms import ModelForm
from django import forms
from .models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags']
widgets = {
'tags': forms.CheckboxSelectMultiple(),
}
def __int__(self, *args, **kwargs):
super().__int__(*args, **kwargs)
# self.fields['title'].widget.attrs.update({'class': 'input'})
for name, field in self.fields.item():
field.widget.attrs.update({'class': 'input'})
I am trying to display my dynamic form with the correct styling. but this method doesn't seem to work. How can I fix it?
def __int__(self, *args, **kwargs):
super().__int__(*args, **kwargs)
# self.fields['title'].widget.attrs.update({'class': 'input'})
for name, field in self.fields.item():
field.widget.attrs.update({'class': 'input'})`
This doesn't seem to work
答案1
得分: 0
在 __init__
魔法方法中,你使用了 "item" 而不是 "items"。将以下行中的 "self.fields.item()" 修改为 "for name, field in self.fields.items()":
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
同时,将 __int__
修复为 __init__
。希望这能解决问题。
英文:
In the init magic method, you're using "item" instead of "items".
Change the line for name, field in
self.fields.item(): to for name, field in self.fields.items():
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Also fix __int__
to __init__
I hope this will solve the issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论