/save_data/ 处的 ValueError

Posted

技术标签:

【中文标题】/save_data/ 处的 ValueError【英文标题】:ValueError at / save_data/ 【发布时间】:2021-10-28 04:32:47 【问题描述】:

无法分配“'Electronic'”:“Product.category”必须是“Category”实例。

文件/models.py:

from django.db import models

# Create your models here.


class Category(models.Model):
    name = models.CharField(max_length=150, db_index=True)

    def __str__(self):
        return self.name


class SubCategory(models.Model):
    name = models.CharField(max_length=150, db_index=True)
    category = models.ForeignKey(Category, related_name='souscatégories', on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class Product(models.Model):
    name = models.CharField(max_length=100, db_index=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    subcategory = models.ForeignKey(SubCategory,  on_delete=models.CASCADE)

    def __str__(self):
        return self.

还有业务逻辑代码...... 文件/views.py

# from django.urls import reverse_lazy
# from django.views.generic import ListView, CreateView

from django.shortcuts import render

from .models import Product, Category, SubCategory


# Create your views here.
def home(request):
    if request.method == "POST":
        name = request.POST['name']
        subcategory = request.POST['subcategory']
        category = request.POST['category']

        ins = Product(name=name, subcategory=subcategory, category=category)
        ins.save()


    data = Product.objects.all()
    return render(request, 'mysiteapp/index.html', 'data': data)

模板就在那里......

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Hello, world!</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


</head>

<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="/">Product List </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>

            <li class="nav-item">
                <a class="nav-link disabled" href="#">Disabled</a>
            </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
    </div>
</nav>
<!-- Table -->
<table class="table table-dark">
    <thead>
    <tr>
        <th scope="col">#</th>
        <th scope="col">Product</th>
        <th scope="col">Subcategory</th>
        <th scope="col">Category</th>
    </tr>
    </thead>
    % for p in data%
    <tbody>
    <tr>
        <th scope="row">p.id</th>
        <td>p.name</td>
        <td>p.subcategory</td>
        <td>p.category</td>
    </tr>
    % endfor %
    </tbody>
</table>
<!-- modal -->
<!-- Button trigger modal -->

<h2><a class="btn btn-success" data-toggle="modal" data-target="#exampleModal">
    Add Product
</a></h2>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Add Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <!-- form -->
            <form method="POST">% csrf_token %
                <div class="form-group row">
                    <label for="name" class="col-sm-2 col-form-label">Product</label>
                    <div class="col-sm-8">
                        <input name="name" type="text" id="name" class="form-control mx-sm-2">
                    </div>
                </div>

                <div class="form-group row">
                    <label for="subcategory" class="col-sm-2 col-form-label">SubCategory</label>
                    <div class="col-sm-8">
                        <select name="subcategory" class="custom-select mr-sm-2" id="subcategory">
                            <option>Choose....</option>
                            % for p in data %
                            <option>p.subcategory</option>
                            % endfor %
                        </select>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="category" class="col-sm-2 col-form-label">Category</label>
                    <div class="col-sm-8">
                        <select name="category" class="custom-select mr-sm-2" id="category">
                            <option>Choose....</option>
                            % for p in data %
                            <option>p.category</option>
                            % endfor %
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save changes</button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- Optional javascript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
</body>

</html>

最后的错误是:

ValueError 在 / 无法分配“'Electronic'”:“Product.category”必须是“Category”实例。

请回答我...

【问题讨论】:

【参考方案1】:

您不能直接从 POST 数据中传递类别。 要么它需要是 Category 类的实例

category_id = request.POST['category']
#Get category instance
category = Category.objects.get(pk=category_id)
ins = Product(name=name, subcategory=subcategory, category=category)

或者你可以使用类别pk值。

ins = Product(name=name, subcategory=subcategory, category_id=category_id)

【讨论】:

以上是关于/save_data/ 处的 ValueError的主要内容,如果未能解决你的问题,请参考以下文章

/change-password/ 处的 ValueError 视图 authapp.views.ChangePassword 未返回 HttpResponse 对象。它返回 None 而不是

Elixir GenServer handle_cast 未被调用

linux中I2C驱动函数常用接口

试图在 STUDENT 模型(外键)中保存 POST 数据 CLASS NAME?

Django - 字典更新序列元素#0 的长度为 1; 2是必需的[重复]

ValueError:未知标签类型