为什么即使在我的Django应用程序中成功表单渲染和提交表单之后,数据库也不会填充?

发布于 2025-02-13 04:25:41 字数 3237 浏览 0 评论 0原文

我是Django的初学者,并制作了一个简单的书记注册表来填充SQL3数据库。我认为我做了正确的一切,并且表格呈现正确,当命中率提交时,甚至会发送帖子请求,但数据库不会被填充。我整个周末都研究了这个问题,转到了Bootstrap文档,还研究了IS_VALID()功能。它显示了“

  • book_name
  • ”此字段之类的错误。
  • ". 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 class="form-group">
        <label for="">Book Name</label>
        <input type="text" class="form-control" id="book_name" placeholder="Enter Book Name",name="book_name">
      </div>
      <div class="form-group">
        <label for="authors_name">Authors</label>
        <input type="text" class="form-control" id="author_name" placeholder="Authors' Name" name="authors">
      </div>
             <div class="form-group">
        <label for="Pages">No. Of Pages</label>
        <input type="text" class="form-control" id="page_no" placeholder="No. of Pages" name="page">
                  <div class="form-group">
        <label for="Registration">Registration No</label>
        <input type="text" class="form-control" id="reg_no" placeholder="Book Registration No" name="registration">
      </div>
      </div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
        </p>
        </body>
    {% endblock %}```
    
    
     
    

    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 class="form-group">
        <label for="">Book Name</label>
        <input type="text" class="form-control" id="book_name" placeholder="Enter Book Name",name="book_name">
      </div>
      <div class="form-group">
        <label for="authors_name">Authors</label>
        <input type="text" class="form-control" id="author_name" placeholder="Authors' Name" name="authors">
      </div>
             <div class="form-group">
        <label for="Pages">No. Of Pages</label>
        <input type="text" class="form-control" id="page_no" placeholder="No. of Pages" name="page">
                  <div class="form-group">
        <label for="Registration">Registration No</label>
        <input type="text" class="form-control" id="reg_no" placeholder="Book Registration No" name="registration">
      </div>
      </div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
        </p>
        </body>
    {% endblock %}```
    
    
     
    

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

    评论(1

    可是我不能没有你 2025-02-20 04:25:41

    您的book_name处理不当,因为您内部有逗号name属性:

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

    另一件事是模板中的形式数据与bookform是期待。

    要正确执行此操作,您应该在get部分中添加表单作为上下文:

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

    然后在模板中进行此操作:

    {{ form }}
    

    您可以检查什么id> idname < /code>属性是自动创建的(bookform in post part。

    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})
    

    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})
    
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文