我有CRUD视图,其中一个看起来像这样:
#model
class Model(models.Model):
field1 = models.CharField()
field2 = models.CharField()
#view
class Model1CreateView(CreateView):
model = Model1
fields = ['field1', 'field2']
#template
and model1_form.html
<form action="{% url 'model1_new' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
我需要为field1指定一个css类,我该怎么做?
答案 0 :(得分:2)
您需要创建Form
并修改该字段小部件的attrs
。有两种常见的方法可以做到这一点。在任何一种情况下,您都需要创建自定义Form
并告诉您的View
使用该表单:
<强> forms.py 强>
from django import forms
from myapp.models import FooModel
class FooForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(FooForm, self).__init__(*args, **kwargs)
self.fields['field1'].widget.attrs = { 'class': 'fooclass' }
class Meta:
model = FooModel
fields = ['field1', 'field2']
或
from django import forms
from myapp.models import FooModel
class FooForm(forms.ModelForm):
field1 = forms.CharField(widget=forms.Textarea(attrs={'class':'fooclass';}))
class Meta:
model = FooModel
fields = ['field1', 'field2']
然后在 views.py :
中from myapp.forms import FooForm
class Model1CreateView(CreateView):
model = Model1
fields = ['field1', 'field2']
form_class = FooForm
答案 1 :(得分:1)
如果要执行此操作,则必须明确定义表单。
class Model1Form(forms.ModelForm):
field1 = forms.CharField(widget=forms.TextInput(attrs={'class': 'myclass'}))
class Meta:
model = Model1
fields = ['field1', 'field2']
class Model1CreateView(CreateView):
form_class = Model1Form
model = Model1