Django – Series – Post – 15 – Django forms – CreateView & ModelForm

Django – Series – Post – 15 – Django forms – CreateView & ModelForm
Spread the love

 

 

Django – Series – Post – 15 – ​​ Django forms – CreateView & ModelForm :

 In this blog post , we will see how to use Django CreateView and ModelForm to save the data to the DB. Under​​ forms.py​​ create a new class called​​ restaurantLocationFormCreation​​ which will receive ModelForm , define the model’s class as restaurantLocations and define the fields.​​ 

from django import forms
from .models import restaurantLocations
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


class restaurantLocationFormCreation(forms.ModelForm):
 ​​ ​​ ​​​​ class Meta:
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ model = restaurantLocations
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ fields = [
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 'name',
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 'location',
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 'category',

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

Include the clean_name function for validation purpose.

Now under “views.py” import the newly created restaurantLocationFormCreation class and create a new CreateView class and define the form_class, template_name and success_url.

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,CreateView
from​​ django.http​​ import​​ HttpResponse, HttpResponseRedirect
from​​ .models​​ import​​ restaurantLocations
from​​ .forms​​ import​​ restaurantFormCreation, restaurantLocationFormCreation

def​​ restaurant_createView(request):
 ​​ ​​ ​​​​ form = restaurantLocationFormCreation(request.POST​​ 
or None)
 ​​ ​​ ​​​​ errors =​​ 
None
 ​​ ​​ ​​​​ 
if​​ form.errors:
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ errors = form.errors

 ​​ ​​ ​​​​ template_name =​​ 
'restaurants/forms.html'
 ​​ ​​ ​​​​ 
context={"form":form,"errors":errors}
 ​​ ​​ ​​​​ 
return​​ render(request,template_name,context)

def​​ restaurant_listView(request):
 ​​ ​​ ​​​​ template_name=
'restaurants/restaurants_list.html'
 ​​ ​​ ​​​​ 
queryset = restaurantLocations.objects.all()
 ​​ ​​ ​​​​ context={

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 
"object_list"​​ : queryset
 ​​ ​​ ​​​​ }

 ​​ ​​ ​​​​ 
return​​ render(request,template_name,context)


class​​ searchandlistRestaurants(ListView):
 ​​ ​​ ​​​​ 
def​​ get_queryset(self):
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ slug =​​ 
self.kwargs.get("slug")
 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 
if​​ slug:
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ queryset = restaurantLocations.objects.filter(

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ Q(
category__iexact​​ = slug)|
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ Q(
category__icontains​​ = slug)
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ )

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ else:
 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ queryset = restaurantLocations.objects.none()

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 
return​​ queryset

class​​ restaurantDetailview(DetailView):
 ​​ ​​ ​​​​ queryset = restaurantLocations.objects.all()

 ​​ ​​ ​​​​ template_name =​​ 
'restaurants/restaurants_detail.html'



class​​ restaurantCreateView(CreateView):
 ​​ ​​ ​​​​ form_class = restaurantLocationFormCreation

 ​​ ​​ ​​​​ template_name =​​ 
'restaurants/forms.html'
 ​​ ​​ ​​​​ 
success_url =​​ '/restaurants/'

 

Update the errors condition to forms.errors in​​ forms.html

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

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

 ​​ ​​ ​​​​ {% if form.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.
 ​​ ​​ ​​ ​​ ​​​​ {{ form.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 %}

 

Update urls.py as below , import the newly created CreateView class and update the url pattern.

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from restaurants.views import (
 ​​ ​​ ​​​​ restaurant_listView,
 ​​ ​​ ​​​​ searchandlistRestaurants,
 ​​ ​​ ​​​​ restaurantDetailview,
 ​​ ​​ ​​​​ restaurantCreateView,
)

urlpatterns = [
 ​​ ​​ ​​​​ url(r'^admin/', admin.site.urls),
 ​​ ​​ ​​​​ url(r'^$', TemplateView.as_view(template_name="home.html")),
 ​​ ​​ ​​​​ url(r'^restaurants/$', restaurant_listView),
 ​​ ​​ ​​​​ url(r'^restaurants/create/$', restaurantCreateView.as_view()),
 ​​ ​​ ​​​​ #url(r'^restaurants/(?P<slug>\w+)/$', searchandlistRestaurants.as_view()),
 ​​ ​​ ​​​​ url(r'^restaurants/(?P<slug>[\w-]+)/$', restaurantDetailview.as_view()),
 ​​ ​​ ​​​​ url(r'^works/$', TemplateView.as_view(template_name="works.html")),
 ​​ ​​ ​​​​ url(r'^cities/$', TemplateView.as_view(template_name="cities.html")),
 ​​ ​​ ​​​​ url(r'^plans/$', TemplateView.as_view(template_name="plans.html")),
]

 

Let’s test the restaurant creation functionality in the website,

 

The newly added entry got added in the restaurants list,

It is working as expected,

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