1

I've written a form class in django, and while trying to output it, found that it is not beautiful to look at.

class AddAppointmentForm(forms.Form):
    docchoices = []
    for doc in doctor.objects.all():
        docst = [doc.docid, doc.name]
        docchoices.append(docst)
    # CHOICES = [('select1', 'select 1'),
    #            ('select2', 'select 2')]
    name = forms.CharField(label='Name', max_length=100)
    gender = forms.ChoiceField(
        required=True,
        widget=forms.RadioSelect,
        choices=[('male', 'Male'), ('female', 'Female')]
    )
    age = forms.IntegerField(max_value=100,min_value=1, required=True)
    phone = forms.CharField(label='Phone', max_length=14, required=True)
    email = forms.CharField(label='Email', max_length=25, required=False)
    address = forms.CharField(label='Address', max_length=60, required=False)
    city = forms.CharField(label='City', max_length=20, required=False)
    doctors = forms.ChoiceField(
        required=True,
        widget=forms.Select,
        choices=docchoices,
    )

{# Load the tag library #} {% extends "appointments/base.html" %} {% block title %}Create appointment{% endblock %} {% block content %}
<div class="container">
    <form class="needs-validation" novalidate="" action="/appointments/appointmentcreated" method="post">
        {% csrf_token %}
        <div class="row">
            <div class="col-md-12 mb-6">
                <label for="Name">Name</label> {{ form.name }}
            </div>
        </div>
        <div class="row py-2 ">
            <div class="input-group col-md-6 mb-3">
                <span class="input-group-addon">Age</span> {{ form.age }}
            </div>
            <div class="input-group col-md-6 mb-3">
                <span class="input-group-addon">Gender</span> {{ form.gender }}
            </div>
        </div>
        <div class="row py-2 ">
            <div class="mb-3">
                <label for="email">Phone
                <span class="text-muted">(Required)</span>
            </label> {{ form.phone }}
            </div>
        </div>
        <div class="row py-2 ">
            <div class="mb-3">
                <label for="email">Email
                <span class="text-muted">(Optional)</span>
</label> {{ form.email }}
            </div>
        </div>

        <div class="mb-3">
            <label for="address">Address</label> {{ form.address }}
        </div>

        <div class="row">
            <div class="col-md-12 mb-6">
                <label for="city">City</label> {{ form.city }}
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 mb-6">
                <label for="sel_doctor">Select Doctor</label> {{ form.doctors }}
            </div>
        </div>

        <div class="row">
            <div class="col-md-2 mb-1">
                <button class="btn btn-primary btn-block" type="submit">Create appointment</button>
            </div>
        </div>
    </form>
</div>
{% endblock %}

Without bootstrap

I attempted to style it as per the suggestions here. But the option attrs arent being accepted for Charfield.

name = forms.CharField(label='Name', max_length=100, attrs={
                       'class': 'form-control'})


File "/home/joel/myappointments/appointments/forms.py", line 7, in <module>
    class AddAppointmentForm(forms.Form):
File "/home/joel/myappointments/appointments/forms.py", line 15, in AddAppointmentForm
    'class': 'form-control'})
File "/home/joel/.local/lib/python3.6/site-packages/django/forms/fields.py", line 214, in __init__
    super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'attrs'

What is the proper way to use a css framework like bootstrap with django forms?

Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86
  • The `docchoices` should not get updated if a new `Doctor` is created? – Willem Van Onsem Jul 31 '18 at 10:37
  • @WillemVanOnsem Didnt get you. Wouldnt that be updated at each form reload? – Joel G Mathew Jul 31 '18 at 10:38
  • no the for loop is executed at the construction of the *class*, not objects of the class. That is one of the reasons why `for` loops in a class are so uncommon. The only real usecase I've seen for such `for` loops, is if you would like to construct for example a large number of (nearly) identical functions. – Willem Van Onsem Jul 31 '18 at 10:40
  • Possible duplicate of [Define css class in django Forms](https://stackoverflow.com/questions/401025/define-css-class-in-django-forms) – Satendra Jul 31 '18 at 10:50
  • There is a Django app [crispy-forms](http://django-crispy-forms.readthedocs.io/en/latest/). It renders the form with Bootstrap (or Foundation). – cezar Jul 31 '18 at 13:54

1 Answers1

3

What you need is widget-tweaks.

It allows you to apply custom styles and CSS classes to django variables (which also includes form objects)

pip install django-widget-tweaks

Then add 'widget-tweaks' to your installed apps.

INSTALLED_APPS = [
...
'widget_tweaks',
...
]

Then import widget-tweaks in your template

{% load static %}
{% load widget_tweaks %}
...

Now suppose you want to apply class "abc" to a form element "email"

{{ form.email|add_class:"abc" }}

This will apply class "abc" to that form element.
This is a much easier and cleaner way to apply styles to forms rather than messing with the backend code

For more info or documentation on "django-widget-tweaks" look here :

https://github.com/jazzband/django-widget-tweaks

coderDude
  • 854
  • 8
  • 15