How to implement django-material in your Django project?

PythonServer Side ProgrammingProgramming

Material Design is a design template that is very popular among developers. It is used at the frontend as CDN. In this article, we are going to see how to use material design on our form widgets and render that form from our views.

Django-material is a library that will apply material design to rendered html file or form widget without CDN.

First, install the django-material package.

pip install django-material

Setup project and app and urls.

In settings.py

INSTALLED_APPS+=['material']

My app name is "myapp".

Example

In models.py

from django.db import models

# Create your models here.
class Data(models.Model):
   Name=models.CharField(max_length=100)
   salary = models.CharField(max_length=20)

Here, we created a simple Django model that we will use in forms.

In urls.py

from django.urls import path
from . import views

urlpatterns = [
   path('', views.home,name="home"),
]

Here, we rendered our view in home url.

In view.py

from django.shortcuts import render
from django import forms
from .models import Data

class SalaryForm(forms.ModelForm):
   class Meta:
      model=Data
      fields="__all__"

def home(request):
   if request.method=='POST':
      form=SalaryForm(request.POST)
      if form.is_valid():
         form.save()

   else:
      form=SalaryForm()

return render(request,'home.html',{'form':form})

Here we created a form and rendered it on frontend.

Don't forgot to create a template folder and home.html in it.

In home.html

{% include 'material/includes/material_css.html' %} #These
two include
{% include 'material/includes/material_js.html' %} # will
import material design
<!DOCTYPE html>
<html>
   <head>
      <title>
         TUT
      </title>
      <style>

      </style>
   </head>
   <body>

      <h2>FORM</h2>
      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">
      </form>
   </body>

Here, we created the frontend and loaded the CSS and JS of our Django Material and it will automatically add design on our form.

Output

You can override the material CSS using <style> tag.

raja
Published on 26-Aug-2021 12:01:43
Advertisements