Django 表单中的 CSS 样式 [英] CSS styling in Django forms

查看:37
本文介绍了Django 表单中的 CSS 样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置以下样式:

forms.py:

from django 导入表单类 ContactForm(forms.Form):主题 = forms.CharField(max_length=100)email = forms.EmailField(required=False)message = forms.CharField(widget=forms.Textarea)

contact_form.html:

<表格>{{ form.as_table }}<input type="submit" value="提交"></表单>

例如,如何为subjectemail设置classID>message 提供外部样式表给?

解决方案

摘自我的回答:如何标记表单带有

的字段在 Django 中

class MyForm(forms.Form):myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))

class MyForm(forms.ModelForm):元类:模型 = 我的模型def __init__(self, *args, **kwargs):super(MyForm, self).__init__(*args, **kwargs)self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})

class MyForm(forms.ModelForm):元类:模型 = 我的模型小部件 = {'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),}

--- 编辑---
以上是对原始问题的代码进行的最简单的更改,以完成所要求的内容.如果您在其他地方重复使用该表格,它还可以防止您重复自己;如果您使用 Django 的 as_table/as_ul/as_p 表单方法,您的类或其他属性就可以工作.如果您需要完全控制完全自定义的渲染,这是 清楚记录

-- 编辑 2 ---
添加了一种为 ModelForm 指定小部件和属性的新方法.

I would like to style the following:

forms.py:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

contact_form.html:

<form action="" method="post">
  <table>
    {{ form.as_table }}
  </table>
  <input type="submit" value="Submit">
</form>

For example, how do I set a class or ID for the subject, email, message to provide an external style sheet to?

解决方案

Taken from my answer to: How to markup form fields with <div class='field_type'> in Django

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented

-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.

这篇关于Django 表单中的 CSS 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆