0

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

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.

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.

<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

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

efx
  • 63
  • 9
  • You can [add fields](http://stackoverflow.com/questions/30761411/add-extra-field-to-modelform/30763406#30763406) to a Modelform – Pynchia Nov 21 '15 at 06:28

3 Answers3

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>
Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
  • hello @geo-jacob thank you for your response but my label attributes did not change. Also, if decide to use the last part `` the django automatic form generator with the default validation i want to keep goes away – efx Nov 22 '15 at 18:05
0

The answer was there all along, i was missing a piece of code in between the 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

efx
  • 63
  • 9
0

You can use field_args. Let assume I have a form class city_form in which I am calling model 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."
                    }                       
                }
            }
Nids Barthwal
  • 2,205
  • 20
  • 12