Pages

Managing Data in Django (Database)

 Create a model and then use migration.

The model defines the database.

In "app"  folder, open model.py file and modify it accordingly.

from django.db import models

# Create your models here.
class Contact(models.Model):
# use the field of form
# it is used for connection with dbms
name = models.CharField( max_length=122)
email = models.CharField( max_length=122)
phone = models.CharField(max_length=12)
desc = models.TextField()
date = models.DateField()

 Now make migration, using command

python3 manage.py makemigrations

After that, in admin.py register your model like this, 

from django.contrib import admin
from home.models import Contact
# Register your models here.

admin.site.register(Contact)

From app.py, copy class name and then in settings.py file of main project, put it in installed apps. and save all this.

INSTALLED_APPS = [
'home.apps.HomeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Now, make migrations. Now, it will show some changes. Migration is used to store data. Now run the command " python3 manage.py migrate ". It will create a table for you. Use " http://127.0.0.1:8000/admin/ " to check whether the Contact table is created or not. 

Change views.py file to get data from the form,

from datetime import datetime
from home.models import Contact
def contact(request):
# if form is posted then use it otherwise it will render
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
phone = request.POST.get('phone')
desc = request.POST.get('desc')
contact = Contact(name=name,email=email,phone=phone,
            desc=desc,date=datetime.today())
# to save data
contact.save()
return render(request,'contactus.html')
# return HttpResponse('This is contact page')

Submit a form to see whether data is stored in a table or not using "http://127.0.0.1:8000/admin/home/contact/".  

To get the contact details by name of the object, use the function below in the models.py file.

class Contact(models.Model):
# use the field of form
# it is used for connection with dbms
name = models.CharField( max_length=122)
email = models.CharField( max_length=122)
phone = models.CharField(max_length=12)
desc = models.TextField()
date = models.DateField()


# it will show contacts by name in http://127.0.0.1:8000/admin/home/contact/
def __str__(self):
return self.name

To check whether the form is submitted or not, Copy "from django.contrib.messages import constants as messages" and paste it in the settings.py file. 

In the views.py file import messages like " from django.contrib import messages" then file will be

from django.shortcuts import render, HttpResponse
from datetime import datetime
from home.models import Contact
from django.contrib import messages

# render for templates
# Create your views here.
def contact(request):
# if form is posted then use it otherwise it will render
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
phone = request.POST.get('phone')
desc = request.POST.get('desc')
contact = Contact(name=name,email=email,phone=phone,
        desc=desc,date=datetime.today())
# to save data
contact.save()
messages.success(request, 'Your form is submitted')
return render(request,'contactus.html')
# return HttpResponse('This is contact page')

Edit base.html file like this,

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
<title>{% block title %}
{% endblock title %}
</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Ice-Cream</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about">About US</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="/services" id="navbarDropdown"
role="button" data-bs-toggle="dropdown" aria-expanded="false">
Services
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="/services">Ice-Cream</a></li>
<li><a class="dropdown-item" href="#">Softy</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Family Pack</a></li>
</ul>
</li>
<!--
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
-->
<li class="nav-item">
<a class="nav-link" href="/contact">Contact US</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>

<!-- To show success message -->
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}" role="alert">
{{ message }}
<!--
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
-->
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}

{% block body %}{% endblock body %}
<!-- Optional JavaScript; choose one of the two! -->

<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>

<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"
integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"
integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13"
crossorigin="anonymous"></script>
-->
</body>
</html>



No comments:

Post a Comment

If you have any doubt, let me know

Email Subscription

Enter your email address:

Delivered by FeedBurner

INSTAGRAM FEED