【问题标题】:save() prohibited to prevent data loss due to unsaved related object 'user'禁止保存()以防止由于未保存的相关对象“用户”而导致数据丢失
【发布时间】:2021-07-19 13:40:22
【问题描述】:

当用户单击添加到购物车的结帐按钮时,我正在尝试将数据保存在表格中,但它向我显示上述错误我无法理解,并且当我注销购物车时发生了另一件事我保存的也被删除了是不是和我不知道有什么关系

这是结帐按钮的views.py

class Checkout(View):
    def post (self, request,):
        user = request.session.get('user')
        ids = (list(request.session.get('cart').keys()))
        sections = Section.get_sections_by_id(ids)

        for section in sections:
            order = Order(user = User(id=user),
                          section = section,
                          price = section.price,
                          )
            
            order.save()

cart.html 的我的 views.py

class Cart(View):
    def get (self, request):
        ids = (list(request.session.get('cart').keys()))
        sections = Section.get_sections_by_id(ids)
        print(sections)
        return render(request, 'cart.html', {'sections': sections})

我的 urls.py

urlpatterns = [
    path('cart/', Cart.as_view(),name='cart'),
    path('Check-Out/', Checkout.as_view(),name='checkout'),
]

我的购物车.html

{% extends 'base.html' %}

{% load static %}

{% load cart %}

{% load custom %}

{% block head %}
<link rel="stylesheet" href="{% static 'css/cart.css' %}">
{% endblock %}

{% block content %}
<div class="container jumbotron">
<section>
<h1>My cart</h1>
<table class="table">
    <thead>
      <tr>
        <th scope="col">S.no</th>
        <th scope="col">Subject</th>
        <th scope="col">Section</th>
        <th scope="col">Teacher</th>
        <th scope="col">Duration</th>
        <th scope="col">Price</th>
      </tr>
    </thead>
    {% for section in sections%}
    <tbody style="margin-bottom: 20px;">
      <tr>
        <th scope="row">{{forloop.counter}}</th>
        <td>{{section.subject.name}}</td>
        <td>{{section.title}}</td>
        <td>{{section.teacher}}</td>
        <td>{{section.content_duration}}</td>
        <td>{{section.price|currency}}</td>
      </tr>
    </tbody>
      {% endfor %}
        <tfoot>
            <tr>
                <th> Total</th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th>{{sections|total_price:request.session.cart|currency}}</th>
            </tr>
            <hr>
        </tfoot>
  </table>
  <button type="button"  data-toggle="modal" data-target="#exampleModal" style="float: right; margin-left:5px"  class="btn btn-outline-primary">Check Out</button>
  <button type="button" style="float: right; margin-left:5px" class="btn btn-info">Back To Site</button>
</tfoot>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Please Verify</h5>
        <input type="button"class="btn-close btn-link" style="text-decoration:none; border:none; font-size:20px;" data-dismiss="modal" aria-label="Close" value="X">
      </div>
      <div class="modal-body">
       <form action="{% url 'transactions:checkout' %}" method="Post">
         {% csrf_token %}

         <input type="submit" class="btn float-right btn-primary" value='Go Ahead'>
       </form>
      </div>
    </div>
  </div>
</div>

{% endblock %}

还有我的models.py

class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    section = models.ForeignKey(Section, on_delete=models.CASCADE )
    price = models.FloatField(blank=False)
    update_at = models.DateTimeField(auto_now=True, editable=False)


    def placeorder(self):
        self.save()

如果可以的话请帮忙

【问题讨论】:

    标签: django django-models django-views django-forms django-templates


    【解决方案1】:

    此行引起的问题:

    order = Order(user = User(id=user)
    

    使用User(id=user) 表示您要创建一个未保存的User 并在未保存的Order 中使用它,然后保存订单,但这不起作用,因为您还没有保存User,因为错误中提到的。

    您可以像这样简单地使用现有用户:

    order = Order(user=user, section=section, price=section.price)
    order.save()
    

    【讨论】:

    • 现在它显示此错误 NOT NULL 约束失败:Transaction_order.user_id
    • 尝试将user = request.session.get('user')改为user = request.user
    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多