Django – Series – Post – 14 – Django forms – Saving data to DB

Django – Series – Post – 14 – Django forms – Saving data to DB
Spread the love

 

 

Django – Series –​​ Post – 14 – ​​ Django forms – Saving​​ data to DB :

In this blog post , we will see how to use Django forms instead of using form input in html for saving the data to​​ DB.​​ 

First create ​​ “forms.py” under templates folder,​​ 

Import Django forms and create a class restaurantFormCreation with the required for form fields, inside this class we will also define a function to validate the form for a dummy name “Hello”

from​​ django​​ import​​ forms

class​​ restaurantFormCreation(forms.Form):
 ​​ ​​ ​​​​ name  ​​ ​​ ​​ ​​ ​​ ​​​​ = forms.CharField()
 ​​ ​​ ​​​​ location  ​​ ​​​​ = forms.CharField(required=False)
 ​​ ​​ ​​​​ category  ​​ ​​​​ = forms.CharField(required=False)

 ​​ ​​ ​​​​ def​​ clean_name(self):
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ name =​​ self.cleaned_data.get('name')
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ if​​ name ==​​ "Hello":
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ raise​​ forms.ValidationError("Not a Valid Name")
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ name

 

Import the form class in “views.py” and update the function as below, Here we will get only the request.POST method and if the form is​​ valid , it will save the details to the DB , if the form has any errors it is captured in the errors variable.​​ 

The context returns the form and the errors.​​ 

from​​ django.db.models​​ import​​ Q
from​​ django.views​​ import​​ View
from​​ django.shortcuts​​ import​​ render,​​ get_object_or_404
from​​ django.views.generic​​ import​​ TemplateView, ListView, DetailView
from​​ django.http​​ import​​ HttpResponse, HttpResponseRedirect
from​​ .models​​ import​​ restaurantLocations
from​​ .forms​​ import​​ restaurantFormCreation

def​​ restaurant_createView(request):
 ​​ ​​ ​​​​ form = restaurantFormCreation(request.POST​​ or None)
 ​​ ​​ ​​​​ errors =​​ None
 ​​ ​​ ​​​​ if​​ form.is_valid():
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ obj​​ = restaurantLocations.objects.create(
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ name​​ = form.cleaned_data.get('name'),
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ location​​ = form.cleaned_data.get('location'),
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ category​​ = form.cleaned_data.get('category')
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ )
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ HttpResponseRedirect('/restaurants/')
 ​​ ​​ ​​​​ if​​ form.errors:
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ errors = form.errors
 ​​ ​​ ​​​​ template_name =​​ 'restaurants/forms.html'
 ​​ ​​ ​​​​ context={"form":form,"errors":errors}
 ​​ ​​ ​​​​ return​​ render(request,template_name,context)

 

Now we will modify the “forms.html“, we will fieldset to display the fields in the form and we will also use the bootstrap alert class to notify us on the validation error.​​ 

{% extends 'base.html' %}
{% block title %}Add Restaurant{% endblock %}

{% block page %}
<h3>Add restaurants</h3><br>
<div class= "col-sm-6">

 ​​ ​​ ​​​​ {% if errors %}
 ​​ ​​ ​​​​ <div class="alert alert-danger alert-dismissible fade in" role="alert">
 ​​ ​​ ​​ ​​ ​​​​ <button type="button" class="close" data-dismiss="alert" aria-label="Close">
 ​​ ​​ ​​ ​​ ​​​​ <span aria-hidden="true">&times;</span>
 ​​ ​​ ​​ ​​ ​​​​ </button>
 ​​ ​​ ​​ ​​ ​​​​ <strong>Oh snap!</strong> See the below error message.
 ​​ ​​ ​​ ​​ ​​​​ {{ errors }}
 ​​ ​​ ​​​​ </div>
 ​​ ​​ ​​​​ {% endif %}

 ​​ ​​ ​​​​ <form METHOD="POST"> {% csrf_token %}
 ​​ ​​ ​​ ​​ ​​​​ <div class="form-group form-inline ">
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {% for field in form %}
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ <fieldset class="control-group">
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ <label class="control-label">{{ field.label }}</label>
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ <div class="controls">
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​  ​​​​ {{ field }}
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ </div>
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ </fieldset>
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {% endfor %}
 ​​ ​​ ​​ ​​ ​​​​ </div>
 ​​ ​​ ​​ ​​ ​​​​ <button type="submit" class="btn btn-primary col-sm-2">Save</button>
 ​​ ​​ ​​​​ </form>

</div>
{% endblock %}

 

We had already defined the function in “urls.py”, so let’s​​ go ahead and open up the url,

 

 

The entry is successfully added to the DB.

Django form validation error, we test it with giving the name of the restaurant as “Hello” and when we try to save it , it will give a validation error.​​ 

Thanks for viewing the post, please post your comments below.

Please Like & Follow us on Facebook & Twitter,

https://www.facebook.com/gadoth/

https://www.twitter.com/GadothDA/

The code is available in the below github link,

https://github.com/rajathithan/Django

 

 

Related posts

Leave a Comment