0

I am trying to manually render the form fields.

I would like to add a bootstrap and custom css class to rendered html.

How can I do this ?

forms.py

class OrderCreateForm(forms.ModelForm):

    class Meta:
        model = Order

        fields = ['name','postal_code']
        widgets = {
            'postal_code': forms.RadioSelect(),
        }

file.html

 <form action="." method="post" class="order-form">    
 <div class="fieldWrapper">
    {{ form.postal_code }}
 </div>
 <p><input type="submit" value="Send"></p>
    {% csrf_token %}
 </form>
{% endblock %}

rendered html

 <div class="fieldWrapper">
    <ul id="id_postal_code">
    <li><label for="id_postal_code_0"><input type="radio" name="postal_code" value="Yes" required id="id_postal_code_0" />Yes</label></li>
    <li><label for="id_postal_code_1"><input type="radio" name="postal_code" value="No" required id="id_postal_code_1" />No</label></li>
    </ul>
 </div>

How to solve a problem ?

I would appreciate your help.

1 Answer 1

2

You can add css classes to form fields in the following way:

    'postal_code': forms.RadioSelect(attrs={"class": "form-control"}),

Another option is to not render the form this way at all, and just write your own html.

Sign up to request clarification or add additional context in comments.

4 Comments

A good idea. What about other fields? For example: name? Do I have to add attr to the Model ? I do not understand. Because I have my own html. What do you mean ?
By writing the html, i mean doing the <input class="..."/> stuff yourself for complete contol. Also possibly look into django-crispy-forms for more control over style.
That's exactly what I mean. <Input class = "..." /> and full control. But I dont know how to get data from Model.
did you see this in the documentation: Creating custom fields

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.