0

My name is R Kartheek. I'm new to Django. I know how to display database table by using HTML in Django. But, I don't know by using forms.py. Present learning that.

Anyone, please help me with how to print the database table by using forms.py in Django. Just like Modalname.objects.all() how to use this by using Forms.py in Django?

models.py:

from django.db import models

# Create your models here.
class Emp_Data(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    mobile = models.BigIntegerField()
    email = models.EmailField(max_length=50)
    company = models.CharField(max_length=50)
    location = models.CharField(max_length=50)
    salary = models.IntegerField()

views.py

from django.shortcuts import render
from .models import Emp_Data
from .forms import Emp_Data_Form
from django.http import HttpResponse
from django.contrib import messages
# Create your views here.

def Emp_View(request):
    if request.method == 'POST':
        form = Emp_Data_Form(request.POST)
        if form.is_valid():
            first_name = request.POST.get('first_name')
            last_name = request.POST.get('last_name')
            mobile = request.POST.get('mobile')
            email = request.POST.get('email')
            company = request.POST.get('company')
            location = request.POST.get('location')
            salary = request.POST.get('salary')

            data = Emp_Data(first_name = first_name, last_name = last_name, mobile = mobile, email = email, company = company, salary = salary )
            data.save()
            messages.success(request, f'Data submitted successfully...')
            form = Emp_Data_Form()
            context = {'form':form}
            return render(request, 'empformapp/empdata.html', context)
        else:
            return HttpResponse('Invalid form')
    else:
        form = Emp_Data_Form()
        context = {'form':form}
        return render(request, 'empformapp/empdata.html', context)

forms.py

from django import forms

class Emp_Data_Form(forms.Form):
    first_name = forms.CharField( label = 'Enter your first name:', widget = forms.TextInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'First name'
                        }
            )
        )
    last_name = forms.CharField( label = 'Enter your last name:', widget = forms.TextInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Last name'
                        }
            )
        )
    mobile = forms.IntegerField( label = 'Enter your mobile number:', widget = forms.NumberInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Mobile number'
                        }
            )
        )
    email = forms.EmailField( label = 'Enter your email id:', widget = forms.EmailInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Email id'
                        }
            )
        )
    company = forms.CharField( label = 'Enter your Company name:', widget = forms.TextInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Company name'
                        }
            )
        )
    location = forms.CharField( label = 'Enter your location:', widget = forms.TextInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Your location'
                        }
            )
        )
    salary = forms.IntegerField( label = 'Enter your salary:', widget = forms.NumberInput(
                attrs = {
                            'class':'form-control',
                            'placeholder':'Your salary'
                        }
            )
        )

empdata.html

{% extends "empformapp/base.html" %}
{% block content %}
<br>
<!-- Alert message code -->
{% if messages %}
    {% for each_item in messages %}
        <div class="alert alert-success{{each_item.tags}}" role="alert">
            {{each_item}}
        </div>
    {% endfor %}
{% endif %}

    <div class="container text-white">
    <div class="row">
        <div class="col-md-4" style="background-color: indigo;">
            <form method="POST">
                {% csrf_token %}
                    {{ form.as_p }}
                    <input type="submit" value="Send" class="btn btn-success" style="margin-top: 5px; margin-bottom: 5px;">
                    <input type="reset" value="Clear" class="btn btn-danger" style="margin-top: 5px; margin-bottom: 5px;">
            </form>
        </div>
        <div class="col-md-8">
            {% if form %}
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>First name</th>
                            <th>Last name</th>
                            <th>Mobile</th>
                            <th>Email id</th>
                            <th>Company name</th>
                            <th>Location</th>
                            <th>Salary</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for each_item in  form %}
                            <tr>
                                <td>{{each_item.first_name}}</td>
                                <td>{{each_item.last_name}}</td>
                                <td>{{each_item.mobile}}</td>
                                <td>{{each_item.email}}</td>
                                <td>{{each_item.company}}</td>
                                <td>{{each_item.location}}</td>
                                <td>{{each_item.salary}}</td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            {% else %}
                <h4>Oh no... Data is not available.</h4>
            {% endif %}
        </div>
    </div>
</div>

{% endblock %}
1
  • In your view, your have doubled the work either: It is sufficient to instanciate the form class with the data from request.POST as you did and then just call form.save(). No need to handle each value in your form.is_valid() unless you have to manipulate data before saving. Commented Feb 11, 2021 at 5:57

1 Answer 1

1

You're doing redundant work as you define it all twice. Read the chapter "Creating forms from models" from the doc.

All you need is this:

from django import forms
from .models import *

class Emp_DataForm(forms.ModelForm):
    class Meta:
        model = Emp_Data
        fields = '__all__'

And you'll be able to render the entire form (except the buttons and the form-tag) with a single template entry (as you did in your example):

{{ form.as_p }}

By the way: You should not use underscores in class-names as they are distinguished from variables (written with underscores). Use EmpData EmpDataForm (CamelCase) instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your answer. But, I rectify the issue in my own way. I add this 9th line in views.py --- all_data = Emp_Data.objects.all() and added this all_data variable in 25th line context = {'form':form, 'all_data':all_data}. In empdata.html i removed if and add for loop like this {% for each_item in all_data %} that's it. Problem solved. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.