【问题标题】:Django: how to make POST request with form data?Django:如何使用表单数据发出 POST 请求?
【发布时间】:2021-07-10 05:19:55
【问题描述】:

我正在学习 Django,但在将一条数据发布到数据库时遇到了问题。这是我的代码:

urls.py

urlpatterns = [
    path("", views.index, name="index"),
    ...
    path("listing/<int:listing_id>", views.display_listing, name="listing")
]

Models.py

class Bid(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usr_bids')
    price = models.DecimalField(max_digits=5, decimal_places=2)

class Listing(models.Model):
    title = models.CharField(max_length=50) 
    bids = models.ManyToManyField(Bid, blank=True, related_name='bids')    
    price = models.DecimalField(max_digits=7, decimal_places=2)
    closed = models.BooleanField(default=False)

Forms.py

class BidForm(ModelForm):
    class Meta:
        model = Bid
        fields = ['price']

views.py

def display_listing(request, listing_id):
    listing = Listing.objects.get(pk=listing_id)
       
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('login'))

    if request.method == "POST":
        user = User.objects.get(username=request.user)
        if request.POST.get("button") == "Watchlist":
            if not user.watchlist.filter(listing=listing):
                watchlist = Watchlist()
                watchlist.user = user
                watchlist.listing = listing
                watchlist.save()
            else:
                user.watchlist.filter(listing=listing).delete()
            return HttpResponseRedirect(reverse('listing', args=(listing.id, )))
        if not listing.closed:
            if request.POST.get("button") == "Close":
                listing.closed = True
                listing.save()
            else:
                price = float(request.POST["price"])
                bids = listing.bids.all()
                if user.username != listing.creator.username:
                    if price <= listing.price:
                        return render(request, 'auctions/listing.html',{
                            'listing': listing,
                            'form': BidForm(),
                            'message': 'Increase your bid.'
                        })
                    form = BidForm(request.POST)
                    if form.is_valid():
                        bid = form.save(commit=False)
                        bid.user = user
                        bid.save()
                        listing.bids.add(bid)
                        listing.price = price
                        listing.save()
                    else:
                        return render(request, 'auctions/listing.html', {
                            'form': form
                        })

        return HttpResponseRedirect(reverse('listing', args=(listing.id, )))
    else:
        return render(request, 'auctions/listing.html', {
            'listing': listing,
            'form': BidForm(),
            'comments': listing.comments.all()
        })

auction/listings.html

<div>
<form action="{% url 'listing' listing.id %}" method="POST">
    {% csrf_token %}
    <div class="form-group">
        <label for="bid">{{ listing.bids.count }} bid(s) so far.  You have the best bid!.</label>
    </div>
    <div class="form-group">
        {{ form }}
    </div>
    <div class="form-group">
        <input type="submit" name="button" class="btn btn-primary" value="Send Bid">
    </div>
</form>
</div>

我在价格字段中填充了一个值(例如 300)。然后,我单击“发送投标”按钮。不幸的是,什么都没有发生。

有人知道为什么我无法将价格保存到数据库吗?提前感谢您的观看!

【问题讨论】:

  • 尝试在listing.save()之后添加form.save()

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


【解决方案1】:

乍一看,你应该有类似的东西:

<form method="post">
    {% csrf_token %}
     {{ form }}

    <input type="submit" name="button" class="btn btn-primary" value="Send Bid">
</form>

在您的模板中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2020-08-31
    • 2011-07-15
    • 1970-01-01
    • 2011-10-03
    • 2018-01-21
    • 2020-06-05
    相关资源
    最近更新 更多