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