首页 > 解决方案 > 禁止保存()以防止由于未保存的相关对象“用户”而导致数据丢失

问题描述

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

这是我的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()

如果可以的话,请帮忙

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


此行引起的问题:

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

UsingUser(id=user)表示您想创建一个未保存的User并在未保存的情况下使用它,Order然后保存订单,但这不起作用,因为您尚未保存User,如错误所述。

您可以按如下顺序简单地使用现有用户:

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

推荐阅读