问题:在Django Forms中定义CSS类

假设我有一个表格

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

有没有一种方法可以在每个字段上定义CSS类,以便可以在渲染页面中基于类使用jQuery?

我希望不必手动构建表单。

Assume I have a form

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?

I was hoping not to have to manually build the form.


回答 0

另一种不需要更改python代码的解决方案,因此对于设计人员和一次性演示更改更好:django-widget-tweaks。希望有人会发现它有用。

Yet another solution that doesn’t require changes in python code and so is better for designers and one-off presentational changes: django-widget-tweaks. Hope somebody will find it useful.


回答 1

回答了我自己的问题。

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

我没有意识到它已传递到小部件构造函数中。

Answered my own question. Sigh

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

I didn’t realize it was passed into the widget constructor.


回答 2

这是在类中声明字段后将类定义添加到小部件的另一种解决方案。

def __init__(self, *args, **kwargs):
    super(SampleClass, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs['class'] = 'my_class'

Here is another solution for adding class definitions to the widgets after declaring the fields in the class.

def __init__(self, *args, **kwargs):
    super(SampleClass, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs['class'] = 'my_class'

回答 3

使用django-widget-tweaks,它易于使用并且效果很好。

否则,可以使用自定义模板过滤器来完成此操作。

考虑到您以这种方式呈现表单:

<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        <label for="id_subject">Email subject:</label>
        {{ form.subject }}
    </div>
</form>

form.subject是具有as_widget方法的BoundField的实例。

您可以在“ my_app / templatetags / myfilters.py”中创建自定义过滤器“ addcss”

from django import template

register = template.Library()

@register.filter(name='addcss')
def addcss(value, arg):
    css_classes = value.field.widget.attrs.get('class', '').split(' ')
    if css_classes and arg not in css_classes:
        css_classes = '%s %s' % (css_classes, arg)
    return value.as_widget(attrs={'class': css_classes})

然后应用您的过滤器:

{% load myfilters %}
<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        <label for="id_subject">Email subject:</label>
        {{ form.subject|addcss:'MyClass' }}
    </div>
</form>

然后,将使用“ MyClass” css类呈现form.subjects。

希望能有所帮助。

编辑1

  • 根据dimyG的答案更新过滤器

  • 添加django-widget-tweak链接

编辑2

  • 根据Bhyd的评论更新过滤器

Use django-widget-tweaks, it is easy to use and works pretty well.

Otherwise this can be done using a custom template filter.

Considering you render your form this way :

<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        <label for="id_subject">Email subject:</label>
        {{ form.subject }}
    </div>
</form>

form.subject is an instance of BoundField which has the as_widget method.

you can create a custom filter “addcss” in “my_app/templatetags/myfilters.py”

from django import template

register = template.Library()

@register.filter(name='addcss')
def addcss(value, arg):
    css_classes = value.field.widget.attrs.get('class', '').split(' ')
    if css_classes and arg not in css_classes:
        css_classes = '%s %s' % (css_classes, arg)
    return value.as_widget(attrs={'class': css_classes})

And then apply your filter:

{% load myfilters %}
<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        <label for="id_subject">Email subject:</label>
        {{ form.subject|addcss:'MyClass' }}
    </div>
</form>

form.subjects will then be rendered with the “MyClass” css class.

Hope this help.

EDIT 1

  • Update filter according to dimyG‘s answer

  • Add django-widget-tweak link

EDIT 2

  • Update filter according to Bhyd‘s comment

回答 4

扩展指向docs.djangoproject.com的方法:

class MyForm(forms.Form): 
    comment = forms.CharField(
            widget=forms.TextInput(attrs={'size':'40'}))

我认为必须了解每个字段的本机窗口小部件类型很麻烦,并且认为仅将类名放在表单字段上就覆盖默认值很有趣。这似乎为我工作:

class MyForm(forms.Form): 
    #This instantiates the field w/ the default widget
    comment = forms.CharField()

    #We only override the part we care about
    comment.widget.attrs['size'] = '40'

对我来说,这似乎有点清洁。

Expanding on the method pointed to at docs.djangoproject.com:

class MyForm(forms.Form): 
    comment = forms.CharField(
            widget=forms.TextInput(attrs={'size':'40'}))

I thought it was troublesome to have to know the native widget type for every field, and thought it funny to override the default just to put a class name on a form field. This seems to work for me:

class MyForm(forms.Form): 
    #This instantiates the field w/ the default widget
    comment = forms.CharField()

    #We only override the part we care about
    comment.widget.attrs['size'] = '40'

This seems a little cleaner to me.


回答 5

如果您希望表单中的所有字段都继承某个类,则只需定义一个父类,该类从继承forms.ModelForm,然后从该类继承

class BaseForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'someClass'


class WhateverForm(BaseForm):
    class Meta:
        model = SomeModel

这帮助我将'form-control'类自动添加到应用程序所有形式的所有字段中,而无需添加代码复制。

If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from forms.ModelForm, and then inherit from it

class BaseForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'someClass'


class WhateverForm(BaseForm):
    class Meta:
        model = SomeModel

This helped me to add the 'form-control' class to all of the fields on all of the forms of my application automatically, without adding replication of code.


回答 6

这是更改视图的简单方法。在将其传递到模板之前,在视图中添加以下内容。

form = MyForm(instance = instance.obj)
form.fields['email'].widget.attrs = {'class':'here_class_name'}

Here is Simple way to alter in view. add below in view just before passing it into template.

form = MyForm(instance = instance.obj)
form.fields['email'].widget.attrs = {'class':'here_class_name'}

回答 7

只需将类添加到表单中,如下所示。

class UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={
        'class':'form-control',
        'placeholder':'Username'
        }
    ))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
        'class':'form-control',
        'placeholder':'Password'
        }
    ))

Simply add the classes to your form as follows.

class UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={
        'class':'form-control',
        'placeholder':'Username'
        }
    ))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
        'class':'form-control',
        'placeholder':'Password'
        }
    ))

回答 8

这是上述内容的一种变体,它将为所有字段提供相同的类(例如,jQuery的圆角效果很好)。

  # Simple way to assign css class to every field
  def __init__(self, *args, **kwargs):
    super(TranslatedPageForm, self).__init__(*args, **kwargs)
    for myField in self.fields:
      self.fields[myField].widget.attrs['class'] = 'ui-state-default ui-corner-all'

Here is a variation on the above which will give all fields the same class (e.g. jquery nice rounded corners).

  # Simple way to assign css class to every field
  def __init__(self, *args, **kwargs):
    super(TranslatedPageForm, self).__init__(*args, **kwargs)
    for myField in self.fields:
      self.fields[myField].widget.attrs['class'] = 'ui-state-default ui-corner-all'

回答 9

你可以试试看

class SampleClass(forms.Form):
  name = forms.CharField(max_length=30)
  name.widget.attrs.update({'class': 'your-class'})
...

您可以在以下网站中查看更多信息:Django Widgets

You can try this..

class SampleClass(forms.Form):
  name = forms.CharField(max_length=30)
  name.widget.attrs.update({'class': 'your-class'})
...

You can see more information in: Django Widgets


回答 10

如果您想向模板中的表单字段(而不是view.py或form.py中)添加类,例如,要在不覆盖其第三方视图的情况下修改第三方应用程序,则可以按照以下说明过滤模板在查尔斯泰克 回答很方便。但是在此答案中,模板过滤器会覆盖该字段可能具有的所有现有类。

我尝试将其添加为编辑内容,但建议将其写为新答案。

因此,这是一个尊重字段现有类的模板标记:

from django import template

register = template.Library()


@register.filter(name='addclass')
def addclass(field, given_class):
    existing_classes = field.field.widget.attrs.get('class', None)
    if existing_classes:
        if existing_classes.find(given_class) == -1:
            # if the given class doesn't exist in the existing classes
            classes = existing_classes + ' ' + given_class
        else:
            classes = existing_classes
    else:
        classes = given_class
    return field.as_widget(attrs={"class": classes})

In case that you want to add a class to a form’s field in a template (not in view.py or form.py) for example in cases that you want to modify 3rd party apps without overriding their views, then a template filter as described in Charlesthk answer is very convenient. But in this answer the template filter overrides any existing classes that the field might has.

I tried to add this as an edit but it was suggested to be written as a new answer.

So, here is a template tag that respects the existing classes of the field:

from django import template

register = template.Library()


@register.filter(name='addclass')
def addclass(field, given_class):
    existing_classes = field.field.widget.attrs.get('class', None)
    if existing_classes:
        if existing_classes.find(given_class) == -1:
            # if the given class doesn't exist in the existing classes
            classes = existing_classes + ' ' + given_class
        else:
            classes = existing_classes
    else:
        classes = given_class
    return field.as_widget(attrs={"class": classes})

回答 11

事实证明,您可以在表单构造函数(init函数)中或在启动表单类之后执行此操作。如果您不编写自己的表单并且该表单来自其他地方,则有时需要这样做-

def some_view(request):
    add_css_to_fields = ['list','of','fields']
    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = SomeForm()

    for key in form.fields.keys():
        if key in add_css_to_fields:
            field = form.fields[key]
            css_addition = 'css_addition '
            css = field.widget.attrs.get('class', '')
            field.widget.attrs['class'] = css_addition + css_classes

    return render(request, 'template_name.html', {'form': form})

As it turns out you can do this in form constructor (init function) or after form class was initiated. This is sometimes required if you are not writing your own form and that form is coming from somewhere else –

def some_view(request):
    add_css_to_fields = ['list','of','fields']
    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = SomeForm()

    for key in form.fields.keys():
        if key in add_css_to_fields:
            field = form.fields[key]
            css_addition = 'css_addition '
            css = field.widget.attrs.get('class', '')
            field.widget.attrs['class'] = css_addition + css_classes

    return render(request, 'template_name.html', {'form': form})

回答 12

您还可以使用Django Crispy Forms,这是定义表单的好工具,以防您需要使用Bootstrap或Foundation这样的CSS框架。在那里为表单字段指定类很容易。

您的表单类会这样:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

    helper = FormHelper()
    helper.form_class = 'your-form-class'
    helper.layout = Layout(
        Field('name', css_class='name-class'),
        Field('age', css_class='age-class'),
        Field('django_hacker', css-class='hacker-class'),
        FormActions(
            Submit('save_changes', 'Save changes'),
        )
    )

You could also use Django Crispy Forms, it’s a great tool to define forms in case you’d like to use some CSS framework like Bootstrap or Foundation. And it’s easy to specify classes for your form fields there.

Your form class would like this then:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

    helper = FormHelper()
    helper.form_class = 'your-form-class'
    helper.layout = Layout(
        Field('name', css_class='name-class'),
        Field('age', css_class='age-class'),
        Field('django_hacker', css-class='hacker-class'),
        FormActions(
            Submit('save_changes', 'Save changes'),
        )
    )

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。