Django:将额外的属性添加到UpdateView生成的表单字段中 [英] Django: Add extra attributes to form fields generated by UpdateView
问题描述
使用一个自定义用户(该用户是Django AbstractUser的子类),试图归档的是允许用户更新其数据的所有方法都可以正常工作,但是表单看起来很难看.下面是我的代码,class属性没有添加到表单中. forms.py (简体)
Am using a custom user that is a subclass of Django AbstractUser, what am trying to archive is to allow user update their data everything works but the form look ugly. Below is my code the class attribute is not added to the form. forms.py(simplified)
class AccountEditForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ('first_name', 'last_name', 'phone_number', 'date_of_birth', 'country')
widget = {
'first_name':forms.TextInput(
attrs={
'class': 'input-bordered',
}
)
}
views.py
class UserAccountDetails(LoginRequiredMixin, UpdateView):
template_name = 'dashboard/account_edit.html'
context_object_name = 'form'
form_class = AccountEditForm
model = CustomUser
def get_object(self, queryset=None):
"""
Return the object the view is displaying.
"""
if queryset is None:
queryset = self.get_queryset()
#Get logged in user from request data
queryset = queryset.filter(pk=self.request.user.id)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
return obj
推荐答案
widgets
选项用于覆盖显式声明的字段的默认设置.要将类添加到该字段,您可以有很多选择.
The widgets
option is for overriding the defaults on explicitly declared fields. To add class to the field you have many options.
选项1:明确声明表单字段,并通过Meta中的 widgets
添加类.
Option #1: Explicitly declare form field and add class through widgets
in Meta.
class AccountEditForm(forms.ModelForm):
first_name = forms.TextField(widget=forms.TextInput())
class Meta:
model = CustomUser
fields = ('first_name', 'last_name', 'phone_number', 'date_of_birth', 'country')
widgets = {
'first_name': forms.TextInput(
attrs={
'class': 'input-bordered',
}
)
}
选项2:选项1的较短版本.
Option #2: Shorter version of option #1.
class AccountEditForm(forms.ModelForm):
first_name = forms.TextField(widget=forms.TextInput(attrs={'class': 'input-bordered'}))
class Meta:
model = CustomUser
...
选项3:在表单的 __ init __
方法中添加类.
Option #3: Add class in form's __init__
method.
class AccountEditForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AccountEditForm, self).__init__(*args, **kwargs)
self.fields['first_name'].widget.attrs['class'] = 'input-bordered'
选项4:使用django-widget-tweaks插件.
Option #4: Use django-widget-tweaks plugin.
这篇关于Django:将额外的属性添加到UpdateView生成的表单字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!