正如标题所说,我正在尝试缩小Django页面上几个字段的宽度。主要是CharField
,DecimalField
和IntegerField
,如果这有任何区别的话。
以下是其中一个字段
的示例title = models.CharField(max_length=200)
我发现其他人已经使用了小部件,但却无法使其工作,因为我不确定如何使用这些,也许是因为这些例子似乎都在使用django.forms.CharField
。以下是此an example的链接。我试过这样一个例子:
title = models.CharField(max_length=200, widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
但也是:
title = models.CharField(max_length=200, widget=models.Textarea(attrs={'cols': 10, 'rows': 20}))
import django.db.models
和import django.forms
以下是我更新的文件:
models.py
class ChemRun(forms.Form):
title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'style': 'width: 400px;' }))
created_date = forms.DateTimeField(initial=timezone.now)
status = forms.CharField(max_length=20, initial="In queue")
forms.py
class ChemRunForm(forms.Form):
class Meta:
model = ChemRun
exclude = ('created_date', 'status')
views.py
@verified_email_required
def create(request):
if request.POST:
form = ChemRunForm()
f = form.save(commit=False)
f.owner = request.user
f.save()
data = form.cleaned_data
initiate_run.delay(data)
return HttpResponseRedirect('/accounts/profile')
else:
form = ChemRunForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('interface/newrun.html', args, context_instance=RequestContext(request))
答案 0 :(得分:1)
你可以用几种方式设置......
你可以在不必定义小部件的情况下完成它,只需设置html' style'元素上的属性
选项1
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyFormForm, self).__init__(*args, **kwargs)
self.fields['title'].widget.attrs['style'] = "width:200px"
选项2
class MyForm(forms.ModelForm):
class Meta:
model = Foo
'widgets' = {
'title' = forms.CharField(attrs={'size':'80'}),
}
选项3
class MyForm(forms.ModelForm):
title = models.CharField(max_length=200, widget=forms.CharField(attrs={'size':'80'})