Fetching Data from Database in Django

After creating models, we know, we have to run ‘makemigrations’ command in the console so that our database is prepared with all the columns in it which we defined in our models.py file inside an app. Suppose you created a registration form and you displayed it in your website. Now if someone registers himself/herself and then wishes to see his/her profile or even if admin wishes to see the data of his customer in the website (not in database) then it means we have to plan something so that the data submitted by the customer which is stored in our database could somehow be fetched and presented in the webpage.

Thats what we are going to do here. I will simply fetch the data from database without focusing on its presentation in the webpage.

Building Registration Page in Django using MySQL

First : I will extend my registration form fields other than what is ready made available in Django in-built forms.

So if you were looking for such forms you are at right place.

Here is the coding –

This is my directory structure at the end.

First uploading code of these files –

settings.py file

Not many things to change – Insert these lines at the end…

in Databases variable delete all the content and insert this –

dj3

In Templates variable look for ‘DIRS’ key and write this –

dj4

Inside ‘INSTALLED APPS ‘ variable add your app. In my case its ‘homepage’. Like this –

dj5

URLS.PY





Now coming inside main mysite folder

admin.py

FORMS.PY


# dappx/forms.py
from django import forms
from django.contrib.auth.models import User
# from django.contrib.auth import get_user_model
from homepage.models import UserProfileInfo

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model   = UserProfileInfo
        fields  = ('fullname', 'address', 'city','mobile_no','alt_mob_no','other_ref_names')

class UserForm(forms.ModelForm):
    password    = forms.CharField(widget=forms.PasswordInput())
    class Meta():
        model   = User
        fields  = ('username','password','email')

MODELS.PY

# from django.db import models

# Create your models here.

# dappx/models.py
from django.db import models
from django.contrib.auth.models import User
# from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# from django.contrib.auth import get_user_model

class UserProfileInfo(models.Model):
   fullname             = models.CharField(max_length=30)
  #  password             = models.CharField(blank=False, max_length=25)
   address              = models.TextField(blank=False, max_length=50)
   city                 = models.TextField(blank=False, max_length=20)
  #  email                = models.EmailField(max_length=60, verbose_name='email', unique=True)
   state                = models.TextField(default="Uttar Pradesh")
   mobile_no            = models.IntegerField()
   alt_mob_no           = models.IntegerField()
   profile_pic          = models.ImageField(upload_to='profile_pics',blank=True)
   user                 = models.OneToOneField(User,on_delete=models.CASCADE)
   date_joined          = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
   other_ref_names      = models.TextField(max_length=100)

   

   def __str__(self):
     return self.user.username
  
 

urls.py

dj9

VIEWS.PY



from django.shortcuts import render
from homepage.forms import UserProfileInfoForm, UserForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required

def index(request):
    return render(request,'indexn.html')

@login_required
def special(request):
    return HttpResponse("You are logged in !")

@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                print('found it')
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request,'registeration.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})

def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account was inactive.")
        else:
            print("Someone tried to login and failed.")
            print("They used username: {} and password: {}".format(username,password))
            return HttpResponse("Invalid login details given")
    else:
        return render(request, 'login.html', {})

Inside templates folder

basen.html

Well, in below code I have used CSS along with HTML. This is not the developer’s way to do. They actually do so in separate folder named ‘static’ but due to my interest and convenience I have used the same HTML page. But its not an issue. All is good. Do as you are convenient.


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Base</title>
    <style>
      body{
        margin: 0px;
      }
      .emptyhead{
        height: 30px;
        background-color: #ff6f61;
      }
      .navbar{
        
        overflow: hidden;
        overflow: hidden;
        background-color:  black;
        position: fixed; /* Set the navbar to fixed position */
         /* Position the navbar at the top of the page */
        width: 100%; /* Full width */
      }
      
      /* Links inside the navbar */
      .navbar a {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        margin-left: 6px;
        font-size: 22px;
      }
      
      /* Change background on mouse-over */
      .navbar a:hover {
        background: #ddd;
        color: red;
      }
      
      /* Main content */
      .main {
        margin-top: 80px; /* Add a top margin to avoid content overlay */;
      }
      .head{
        margin-top: 50px;
        background-color:  #ff6f61;
        color: white;
        height: 100px;
        font-size: 50px;
        font-family: monospace;
        font-weight: bold;
        text-align: center;
        padding: 35px;
      }
    </style>
</head>
  <body >
{# Django Home Link / Admin Link / Register Link#}
    <div class="emptyhead">

    </div>
    <div class="navbar">
          <a href="{% url 'index' %}">About Us</a>
          <a href="{% url 'admin:index' %}">Admin</a>
          <a href="{% url 'homepage:register' %}">Register</a>     
          {# Some logic on what to display for last item#}
          {% if user.is_authenticated %}
            <li><a href="{% url 'logout' %}">Logout</a></li>
          {% else %}
            <li><a href="{% url 'homepage:user_login' %}">Login</a></li>
          {% endif %}
    </div>
    <div class="head">
      PROVISION STORE MANAGEMENT SYSTEM
    </div>
    <div class="main">
    {% block body_block %}
    {% endblock %}
    </div>
  </body>
</html>

INDEXN.HTML

dj11

login.html

dj12

REGISTERATION.HTML

OVER!

Yes, over only thing you have to do is to download WAMP and through phpmyadmin create a database ‘provisionstore’. If you want to name something different then change the name in dj3 pic posted above too.

Happy Coding !

Please, Please, do ask your confusion. If any. Thanks ๐Ÿ™‚