【问题标题】:I am confused while rendering my views.py "Django"渲染views.py“Django”时我很困惑
【发布时间】:2021-12-20 07:28:53
【问题描述】:

我的 vews.py:

如果您希望我分享另一条信息,请随时询问! 我只是出价系统有问题!!,我尝试了出价,但是当我将新号码添加到输入字段中并单击地方出价按钮时,页面刚刚重新加载,这意味着该功能不起作用! 当我尝试关闭出价时,我遇到了另一个问题,我遇到了这个 Django 错误

ValueError at /bidding/26
 The view auctions.views.bidding didn't return an HttpResponse object. 
 It returned None instead.

代码:

 def viewList(request, id):
        # check for the watchlist
        listing = Post.objects.get(id=id)
        user = User.objects.get(username=request.user)
        if listing.watchers.filter(id=request.user.id).exists():
                is_watched = True
        else:
                is_watched = False

        if not listing.activate:
              if request.POST.get('button') == "Close":
                  listing.activate = True
                  listing.save()
        else:
            price = request.POST.get('bid', 0)
            bids = listing.bids.all()
        if user.username != listing.creator.username:
            if price <= listing.price:
                return render(request, 'auctions/item.html', {
                    "listing": listing,
                    'form': BidForm(),
                    "message": "Error! Your bid must be largest than the current bid!",
                    'comment_form': CommentForm(),
                    'comments': listing.get_comments.all(),
                    'is_watched': is_watched,
                })
            form = BidForm(request.POST)
            if form.is_valid():
                bid = form.save(commit=False)
                bid.user = user
                bid.save()
                listing.bids.add(bid)
                listing.bid = price
                listing.save()
            else:
                return render(request, 'acutions/item.html', {'form'})
        context = {
          'listing': listing,
          'comment_form': CommentForm(),
          'comments': listing.get_comments.all(),
          'is_watched': is_watched,
          'form': BidForm()}
        return render(request, 'auctions/item.html', context)

models.py

class Bid(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    bid = models.DecimalField(max_digits=10, decimal_places=2)
    time = models.DateTimeField(default=timezone.now)


class Post(models.Model):
    # data fields
    title = models.CharField(max_length=64)
    textarea = models.TextField()

    # bid
    price = models.FloatField(default=0)
    currentBid = models.FloatField(blank=True, null=True)

    imageurl = models.CharField(max_length=255, null=True, blank=True)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, default="No Category Yet!", null=True,  blank=True)

    creator = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name="all_creators_listings")

    watchers = models.ManyToManyField(
        User, blank=True, related_name='favorite')
    date = models.DateTimeField(auto_now_add=True)

    # for activated the Category
    activate = models.BooleanField(default=False)

    bids = models.ManyToManyField(Bid, )

    def __str__(self):
        return f"{self.title} | {self.textarea} |  {self.date.strftime('%B %d %Y')}"

item.html

            <div class="card-body">
            <ul class="list-group">
                <div class="info">
                    <li class="list-group-item mb-2">Description:<br>{{listing.textarea}}</li>
                    <li class="list-group-item mb-2">category: {{listing.category.name}}</li>
                    <li class="list-group-item mb-2"><h5>Start bid: {{listing.price}}$</h5></li>
                </div>

                <div class="newbid">
                <p>{{ message }}</p>
                <form action="{% url 'viewList' listing.id %}" method="POST">
                    {% csrf_token %}
                    <div class="form-group">
                    <label for="bid">{{ listing.bids.count }} bid(s) so far. Your bid is the current bid</label>
                    </div>
                    <div class="form-group">
                    {{ form }}
                    </div>
                    <div class="form-group">
                    <input type="submit" name="button" class="btn btn-primary" value="Place Bid">
                    </div>
                </form>
                    {% if listing.activate %}
                        <li><strong>Winner: </strong>{{ listing.bids.last.user.username }}</li>
                    {% endif %}

                    {% if user.username == listing.creator.username and not listing.activate %}
                    <form action="{% url 'viewList' listing.id %}" method="POST">
                        {% csrf_token %}
                        <button type="submit" name="button" class="btn btn-danger" value="Close">Close</button>
                    </form>
                    {% endif %}

                </div>

            </ul>
        </div>

在这个视图中,我添加了我的项目要求(cmets/watchlist(书签)/最后一件事(我有很多问题)是投标系统),它可以让用户在此类帖子上添加出价并让该帖子的创建者能够关闭它....请帮助我坚持这个区域,我尝试了很多次才能理解! 注意我是后端开发的新手

【问题讨论】:

  • 可以分享模型吗???
  • @MohamedBeltagy 当然是分钟
  • @MohamedBeltagy 见..

标签: python python-3.x django


【解决方案1】:

你的代码中有两个问题,第一个是 Husam 强调的 user = User.objects.get(username=request.user.username) 另一个在else部分的return语句中

render(request, 'acutions/item.html', {'form'}) 而不是上下文对象,您传递的字符串在 python 中被视为set 对象,这就是您收到None type 错误的原因。

这是重构后的代码:-

def viewList(request, id):
        # check for the watchlist
        listing = Post.objects.get(id=id)
        user = User.objects.get(username=request.user.username)
        form = BidForm()
        is_watched = listing.watchers.filter(id=request.user.id).exists():
        context = {}
        if not listing.activate:
              if request.POST.get('button') == "Close":
                  listing.activate = True
                  listing.save()
        else:
            price = request.POST.get('bid', 0)
            bids = listing.bids.all()
        if user.username != listing.creator.username:
            if price <= listing.price:
                context.update({'message':"Error! your bid must be largest than the current bid !"})
            else:    
                form = BidForm(request.POST)
                if form.is_valid():
                    bid = form.save(commit=False)
                    bid.user = user
                    bid.save()
                    listing.bids.add(bid)
                    listing.bid = price
                    listing.save()
                else:
                    return render(request, 'acutions/item.html', {'form': form})

        context.update({'listing': listing,
          'comment_form': CommentForm(),
          'comments': listing.get_comments.all(),
          'is_watched': is_watched,
          'form': form})
        return render(request, 'auctions/item.html', context)

【讨论】:

  • 当我开始点击查看按钮时出现错误:UnboundLocalError at /Post/21/viewlist local variable 'price' referenced before assignment
  • 这个错误也是TypeError at /Post/21/viewlist '&lt;=' not supported between instances of 'str' and 'decimal.Decimal'
  • 第一个错误 price 您尝试比较 if price &lt;= listing.price: 未声明价格的地方,这就是您收到此错误的原因。
  • listing.price 返回十进制值,而 price 以字符串形式出现,这就是您收到第二个错误的原因。
  • 我尝试运行@kichik 代码我没有收到任何错误,但是如果您注意到我在我的代码'message':"Error! your bid must be largest than the current bid !" 中放置了一条错误消息,此消息消失了,您知道为什么吗? 我将分享 HTML 文件
【解决方案2】:

您在出价视图中遇到的错误和您共享的视图是视图列表,如果您共享出价视图并突出显示错误行/s会更好

无论如何,我注意到这一行有一个错误: 用户 = User.objects.get(username=request.user)

假设是: 用户 = User.objects.get(username=request.user.username)

希望对你有所帮助

【讨论】:

  • 你能帮忙吗?我找不到我的问题的解决方案:
  • there is something else, I tried the bidding but when I add the new number into the input field and click the place bid button the page just reloads which means the function doesn't work!!
猜你喜欢
  • 2011-04-11
  • 2020-08-17
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多