如何自定义修改django表单并保持默认验证不变

时间:2022-06-01 12:59:51

i've been searching for some examples on how to use Django's modelforms default validation but also be able to change attributes.

我一直在寻找一些关于如何使用Django的模型默认验证的例子,但也能够改变属性。

Note: this is going to be a very high level explanation to avoid an extra long question

注意:这将是一个非常高级别的解释,以避免一个特别长的问题

so far the easieast way to generate a form is to just do a

到目前为止,生成表单的简单方法就是做一个

<form id="some_form" method="post" action="/do/something/"
        enctype="multipart/form-data" autocomplete="off">
    {{ some_form }}
    <button name="submit" type="submit" class="btn btn-custom-primary">Submit</a>
</form>

that part above will automatically use what you have on forms.py and views.py to render a fully functional form that will generate the validation for you, therefore when you hit submit if there's missing data it will let you know what you are missing and it won't let you go through.

上面的部分将自动使用你在forms.py和views.py上的内容来渲染一个能够为你生​​成验证的完整功能表单,因此当你点击提交时如果缺少数据它会让你知道你缺少什么,它不会让你通过。

But what happens when you want to add/update attributes to the form? by attributes CSS attributes like class, id, etc. if i decide to go the 'manual' way where i can control what attibutes to have instead of letting django automatically render the form for me like below i loose the default validation settings that django has.

但是当您想要向表单添加/更新属性时会发生什么?通过属性CSS属性,如类,身份等,如果我决定采用“手动”的方式,我可以控制什么属性而不​​是让django自动为我呈现表格,如下所示,我放弃了django的默认验证设置。

<form>
{% for field in some_form %}
    <label class="some_class" for="{{ field.name }}">{{ field.label }}</label>
    {{ field }}
{% endfor %}
<button type="submit">Submit</button>
</form>

Now, i have found a way to add some attributes on forms.py see below

现在,我找到了一种在forms.py上添加一些属性的方法,见下文

class DoSomething(forms.ModelForm):
def __init__(self, user,  *args, **kwargs):
    super(DoSomething, self).__init__(*args, **kwargs)
    for field in self.Meta.fields:
        self.fields[field].widget.attrs.update({
            'class': 'form-control',
        })

if i initialize the class like that, i can add attributes to input but i haven't been able to add attributes to labels, i think once i manage to do that i'll be able to render it correctly. It may be something simple at this point but i think i'm already tired.

如果我像这样初始化类,我可以添加属性到输入,但我无法向标签添加属性,我想一旦我设法做到这一点,我将能够正确地渲染它。这点可能很简单,但我想我已经累了。

how can i style the form without loosing the default validation? is what i've done so far ok or is there a different approach to do this?

如何在不丢失默认验证的情况下设置表单样式?是我到目前为止所做的还是有不同的方法来做到这一点?

please advise,

efx

3 个解决方案

#1


0  

Try this;

class DoSomething(forms.ModelForm):
    def __init__(self, user,  *args, **kwargs):
        super(DoSomething, self).__init__(*args, **kwargs)
        for field in self.Meta.fields:
            self.fields[field].widget.attrs.update({
                'class': 'form-control',
            })
            self.fields[field].label_classes = ('class_name1', 'class_name2', )

<label class="{% for class in field.label_classes %}{{ class }} {% endfor %}" for="{{ field.name }}">{{ field.label }}</label>

#2


0  

The answer was there all along, i was missing a piece of code in between the for block {{ field.errors }}

答案一直存在,我在for block {{field.errors}}之间错过了一段代码

<form>
    {% for field in some_form %}
       {{ field.errors }}
        <label class="some_class" for="{{ field.name }}">{{ field.label }}</label>
        {{ field }}
    {% endfor %}
    <button type="submit">Submit</button>
</form>

once i put that part in there, validation error messages appeared when i left them empty or put a non valid value

一旦我把那部分放在那里,当我把它们留空或者放一个无效值时,会出现验证错误消息

#3


0  

You can use field_args. Let assume I have a form class city_form in which I am calling model city_master.

您可以使用field_args。假设我有一个表单类city_form,我在其中调用模型city_master。

class city_form(ModelForm):
    class Meta:
        model = city_master
        fields = ('city', 'state', 'status')
        field_args = {
                "city" : {
                    "error_messages" : {
                        "required" : "Please let us know what to call you!"
                    }
                },
                "state" : {
                    "+error_messages" : {
                        "required" : "Please also enter some notes.",
                        "invalid"  : "This is not a valid state."
                    }                       
                }
            }

#1


0  

Try this;

class DoSomething(forms.ModelForm):
    def __init__(self, user,  *args, **kwargs):
        super(DoSomething, self).__init__(*args, **kwargs)
        for field in self.Meta.fields:
            self.fields[field].widget.attrs.update({
                'class': 'form-control',
            })
            self.fields[field].label_classes = ('class_name1', 'class_name2', )

<label class="{% for class in field.label_classes %}{{ class }} {% endfor %}" for="{{ field.name }}">{{ field.label }}</label>

#2


0  

The answer was there all along, i was missing a piece of code in between the for block {{ field.errors }}

答案一直存在,我在for block {{field.errors}}之间错过了一段代码

<form>
    {% for field in some_form %}
       {{ field.errors }}
        <label class="some_class" for="{{ field.name }}">{{ field.label }}</label>
        {{ field }}
    {% endfor %}
    <button type="submit">Submit</button>
</form>

once i put that part in there, validation error messages appeared when i left them empty or put a non valid value

一旦我把那部分放在那里,当我把它们留空或者放一个无效值时,会出现验证错误消息

#3


0  

You can use field_args. Let assume I have a form class city_form in which I am calling model city_master.

您可以使用field_args。假设我有一个表单类city_form,我在其中调用模型city_master。

class city_form(ModelForm):
    class Meta:
        model = city_master
        fields = ('city', 'state', 'status')
        field_args = {
                "city" : {
                    "error_messages" : {
                        "required" : "Please let us know what to call you!"
                    }
                },
                "state" : {
                    "+error_messages" : {
                        "required" : "Please also enter some notes.",
                        "invalid"  : "This is not a valid state."
                    }                       
                }
            }