article

Wednesday, April 8, 2020

Django Model Forms - How to use bootstrap in django forms


Django Model Forms - How to use bootstrap in django forms

Django Model Form - It is a class which is used to create an HTML form by using the Model


Database Table

CREATE TABLE myapp_contact (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR (255),
email VARCHAR (254) NOT NULL,
subject VARCHAR (255),
message TEXT,
createdAt DATETIME NOT NULL

);

Models.py
 
from django.db import models

# Create your models here.
class Contact(models.Model):
    name = models.CharField("First name", max_length=255, blank = True, null = True)
    email = models.EmailField()
    subject = models.CharField("Subject", max_length=255, blank = True, null = True)
    message = models.TextField(blank=True, null=True)
    createdAt = models.DateTimeField("Created At", auto_now_add=True)

    def __str__(self):
        return self.name
Views.py
 
from django.shortcuts import render, redirect

# Create your views here.
from django import forms
from django.utils import timezone
from myapp.forms import MyCommentForm
def index(request):
 
    if request.method == "POST":
        form = MyCommentForm(request.POST)
        if form.is_valid():
            model_instance = form.save(commit=False)
            model_instance.timestamp = timezone.now()
            model_instance.save()
            return redirect('/index')
    else:
        form = MyCommentForm()
        return render(request, "my_template.html", {'form': form})
Forms.py
 
from django.forms import ModelForm
from myapp.models import Contact
from django import forms
  
class MyCommentForm(forms.ModelForm):
    class Meta(object):
        model = Contact
        fields = ['name', 'email', 'subject', 'message']
        widgets = {
            'name': forms.TextInput(
    attrs={
     'class': 'form-control'
     }
    ),
   'email': forms.TextInput(
    attrs={
     'class': 'form-control'
     }
    ),
   'subject': forms.TextInput(
    attrs={
     'class': 'form-control'
     }
    ),
            'message': forms.Textarea(
    attrs={
     'class': 'form-control'
     }
    ),
   }
my_template.html
<DOCTYPE html>
<html>
<head>
<title>Django Forms</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="jumbotron jumbotron-sm">
    <div class="container">
        <div class="row">
            <div class="col-sm-12 col-lg-12">
                <h1 class="h1">Contact us <small>Feel free to contact us</small></h1>
    <p style="font-weight:bold;color:red;">Django Model Forms - How to use bootstrap in django forms</p>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div class="well well-sm">
                <form action="" method="POST" role="form">
                {% csrf_token %}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">
                                Name</label>
                            {{ form.name }}
                        </div>
                        <div class="form-group">
                            <label for="email">
                                Email Address</label>
                            <div class="input-group">
                                <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span>
                                </span>
                                {{ form.email }}</div>
                        </div>
                        <div class="form-group">
                            <label for="subject">
                                Subject</label>
                            <select id="subject" name="subject" class="form-control" required="required">
                                <option value="na" selected="">Choose One:</option>
                                <option value="service">General Customer Service</option>
                                <option value="suggestions">Suggestions</option>
                                <option value="product">Product Support</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">
                                Message</label>
                            {{ form.message }}
                        </div>
                    </div>
                    <div class="col-md-12">
                        <button type="submit" class="btn btn-primary pull-right" id="btnContactUs">
                            Send Message</button>
                    </div>
                </div>
                </form>
            </div>
        </div>
        <div class="col-md-4">
            <legend><span class="glyphicon glyphicon-globe"></span> Our office</legend>
            <address>
                <strong>Cairocoders, Inc.</strong><br>
                158 Folsom Ave, Suite 600<br>
                Olongapo City, CA 94107<br>
                <abbr title="Phone">
                    P:</abbr>
                (123) 456-7890
            </address>
            <address>
                <strong>Cairocoders</strong><br>
                <a href="mailto:#">cairocoders@example.com</a>
            </address>
        </div>
    </div>
</div>
</body>
</html>

Related Post