Remove Labels in a Django Crispy Forms

匆匆过客 提交于 2020-05-28 12:45:51

问题


Does anybody know if there is a correct way to remove labels in a crispy form?

I got as far as this:

self.fields['field'].label = ""

But it's not a very nice solution.


回答1:


You could edit the field.html template: https://github.com/maraujop/django-crispy-forms/blob/dev/crispy_forms/templates/bootstrap/field.html#L7

Add a FormHelper attribute to your form that controls the label rendering and use it in that template if. Custom FormHelper attributes are not yet officially documented, because I haven't had time, but I talked about them in a keynote I gave, here are the slides: https://speakerdeck.com/u/maraujop/p/django-crispy-forms




回答2:


Just do:

self.helper.form_show_labels = False

To remove all labels.




回答3:


Works with Boostrap ( see documentation )

In your form :

from crispy_forms.helper import FormHelper
from django import forms

class MyForm(forms.Form):
    [...]
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False 

In your template:

<form method='POST' action=''>{% csrf_token %}
{% crispy form %}
<input type='submit' value='Submit' class='btn btn-default'>
</form>



回答4:


if you are only to remove some labels from input, then explicitly don't give a label name in model definition, i.e:

field = models.IntegerField("",null=True)



回答5:


The solution below lets you remove a label from both a regular or crispy control. Not only does the label text disappear, but the space used by the label is also removed so you don't end up with a blank label taking up space and messing up your layout.

The code below works in django 2.1.1.

# this class would go in forms.py
class SectionForm(forms.ModelForm):
    # add a custom field for calculation if desired
    txt01 = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        ''' remove any labels here if desired
        '''
        super(SectionForm, self).__init__(*args, **kwargs)

        # remove the label of a non-linked/calculated field (txt01 added at top of form)
        self.fields['txt01'].label = ''

        # you can also remove labels of built-in model properties
        self.fields['name'].label = ''

    class Meta:
        model = Section
        fields = "__all__"

I'm not clear what the problem the OP had with the code snippet he showed, except that he wasn't putting the line of code in the right place. This seems like the best and simplest solution.



来源:https://stackoverflow.com/questions/11472495/remove-labels-in-a-django-crispy-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!