简体   繁体   中英

Django form not saving objects in database

My form is not saving any objects in the database. No clue why, tried couple more ways to do it but nothing works.

in models.py

from django.db import models

class ProductListing(models.Model):
    product_name = models.CharField(max_length=40, blank=False)
    product_image = models.ImageField(blank=True)
    product_description = models.TextField(blank=False)
    product_price = models.DecimalField(max_digits=7, decimal_places=0, blank=True, null=True)
    product_quantity = models.DecimalField(max_digits=10, decimal_places=0)

in views.py

from django.shortcuts import render
from .forms import addproduct_form

def addproduct_page(request, *arg, **kwarg):
    if request.method == 'POST':
        form = addproduct_form(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = addproduct_form

    return render(request, 'StaffPages/add_product.html', {'productform' : form})

inside the template

{% block content %}
{% load static %}
<link rel = "stylesheet" type = "text/css" href = "{% static 'StaffPages/add_product.css' %}"/>
<div class="maincontainer">
    <form class="addproductform">
        <div>{{productform.product_name}}</div>
        <div>{{productform.product_image}}</div>
        <div>{{productform.product_description}}</div>
        <div>{{productform.product_price}}</div>
        <div>{{productform.product_quantity}}</div>
        <input type="submit" value="Submit">
    </form>
</div>
{% endblock %}

You need to explicitly specify the POST method in your form, otherwise, it would be GET :

<form class="addproductform" method="POST"> {% csrf_token %}
    <div>{{productform.product_name}}</div>
    <div>{{productform.product_image}}</div>
    <div>{{productform.product_description}}</div>
    <div>{{productform.product_price}}</div>
    <div>{{productform.product_quantity}}</div>
    <input type="submit" value="Submit">
</form>

also, don't forget to put the {% csrf_token %} .

The missing ones are;

  • Action url
  • csrf token

For example;

{% block content %}
{% load static %}
<link rel = "stylesheet" type = "text/css" href = "{% static 'StaffPages/add_product.css' %}"/>
<div class="maincontainer">
    <form action="{% url "app_name:url_name" %}  class="addproductform">{% csrf_token %}
        <div>{{productform.product_name}}</div>
        <div>{{productform.product_image}}</div>
        <div>{{productform.product_description}}</div>
        <div>{{productform.product_price}}</div>
        <div>{{productform.product_quantity}}</div>
        <input type="submit" value="Submit">
    </form>
</div>
{% endblock %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM