Home > front end >  Why the data base is not populated even after successful form rendering and submission of form in my
Why the data base is not populated even after successful form rendering and submission of form in my

Time:07-05

I am beginner in django and making a simple Book registration form to populate sql3 database. I think i did everything right, and the the form is rendering properly and when hit submit it even sends POST request but database don't get populated. I researched on this problem my entire weekend, went to bootstrap documentation and also studied about is_valid() function. It shows error like "

  • book_name
  • This field is required.
  • ". I don't know how to deal with it and what should i do?? My models.py

    from django.db import models
    class Book(models.Model):
        #Create your models here
        book_name = models.CharField(max_length=200)
        page =models.CharField(max_length=20)
        authors =models.CharField(max_length=200)
        registration = models.CharField(max_length=200)
        #email = models.EmailField(max_length=100)
        def __str__(self):
            return self.book_name
    ```
    views.py
    
    ```
    from django.shortcuts import render
    from django.http import HttpResponse
    from . models import Book
    from .forms import BookForm
    def say_hello(request):
        if(request.method=="POST"):
            #if Post request is made :do something
            form = BookForm(request.POST or None)
            if form.is_valid():
                print("New Book Object is created")
                #Book.objects.create(**form.cleaned_data)
                form.save()
            else:
    
                print(form.errors)
                print("Invalid Form data")
    
            return render(request,'join.html',{})
            #Add all things posted to the Bookform
    
        else:
            #otherwise just reder a normal web page
            return render(request,'join.html',{})
    def index(request):
        all_books=Book.objects.all
        return render(request,'index.html',{'all':all_books})
    # Create your views here.
    ```
    
    
    forms.py
    ```
    from django import forms
    from . models import Book
    #To post data to the datbase obtained from form
    class BookForm(forms.ModelForm):
        class Meta:
            model = Book
            fields = ['book_name','authors','page','registration']
    
    ```
        
    
    join.html
    ```
    {%  extends 'base.html' %}<!-- We are including bootstrap loaded base.html file-->
    {% block content %}
    
        <h1>    Register Your Favorite Book
            </h1>
        <p>
        <form method="POST" action="{% url 'hello' %}"> <!-- It says that Call view function respective to 'hello url -->
        {% csrf_token  %} <!-- IT's for security from hacker-->
            <p>
      <div >
        <label for="">Book Name</label>
        <input type="text"  id="book_name" placeholder="Enter Book Name",name="book_name">
      </div>
      <div >
        <label for="authors_name">Authors</label>
        <input type="text"  id="author_name" placeholder="Authors' Name" name="authors">
      </div>
             <div >
        <label for="Pages">No. Of Pages</label>
        <input type="text"  id="page_no" placeholder="No. of Pages" name="page">
                  <div >
        <label for="Registration">Registration No</label>
        <input type="text"  id="reg_no" placeholder="Book Registration No" name="registration">
      </div>
      </div>
      <button type="submit" >Submit</button>
    </form>
        </p>
        </body>
    {% endblock %}```
    
    
     
    

    CodePudding user response:

    Your book_name is not well processed, because you have comma inside name attribute:

    placeholder="Enter Book Name",name="book_name"
    

    Another thing is form data in template is not the same that BookForm is expecting.

    To do it right way, you should add your form as a context in GET part:

    else:
        # otherwise just reder a normal web page
        return render(request, 'join.html', {'form': BookForm()})
    

    Then in template just do this:

    {{ form }}
    

    You can check what id and name attributes are automatically created (which are needed later for BookForm in POST part. Which you should also provide then. Basically it might look like this:

    def say_hello(request):
        if request.method == "POST":   # don't use parenthesis for if statement, it's redundant in Python :)
            form = BookForm(request.POST or None)
            if form.is_valid():
                ...
            else:
                ...
        elif request.method == "GET":
            form = BookForm()
            ...
        return render(request, 'join.html', {'form': form})
    
    • Related