Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add form control to a Django Form?

I'm try to add form control to a form app I made for Django. I have created the app already and want to add the form into a bootstrap template, however I don't know how to add bootstrap's sleeker text-box for my email field.

I would like to end up with something like the sign-in field found in the corner of this bootstrap template (albeit without the password field): http://getbootstrap.com/examples/jumbotron/

My code in my signup.html file looks like this:

{% extends 'base.html' %}

{% block content %}
    <div class="col-sm-12">
            <form method='POST' action=''> {% csrf_token %}
                {{ form.as_p }}                       
                <input type='submit' class='btn btn-success btn-lg'>
            </form>
    </div>
{% endblock %}

The code for the bootstrap site above looks like this (I got rid of the password part for clarity): I don't know how to integrate the django app into this code so that the site will post signups to my database.

<form class="navbar-form navbar-right" role="form">
  <div class="form-group">
    <input type="text" placeholder="Email" class="form-control">
  </div>
  <button type="submit" class="btn btn-success">Sign in</button>
</form>

How do I integrate the two? Thanks in advance.

like image 227
user3175538 Avatar asked Jan 09 '14 00:01

user3175538


2 Answers

For reference, if you're for example using a ModelForm you can just override the init method of your form like this:

def __init__(self, *args, **kwargs):
        super(MemberForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
like image 68
Milo Wielondek Avatar answered Oct 05 '22 18:10

Milo Wielondek


def __init__(self, *args, **kwargs):
    super(YourModelForm, self).__init__(*args, **kwargs)
    for field_name, field in self.fields.items():
        if field.widget.attrs.get('class'):
            field.widget.attrs['class'] += ' form-control'
        else:
            field.widget.attrs['class']='form-control'

will not override the given class attrs

like image 28
Gabriel Xia Avatar answered Oct 05 '22 20:10

Gabriel Xia