(Django - Python) views.py 的隐藏输入请求

(Django - Python) Hidden Input Request to views.py

我必须创建一个带有拍卖的网站,并且我有一个显示所有活动拍卖的主页...

我想将用户重定向到点击相关按钮的拍卖详情,但我对隐藏输入请求有一些问题,因为它没有向我的函数报告隐藏值(def bid (request, auction)),但我在 csrfmiddlewaretoken (id=1) 之后的 url 栏上看到它,你能帮我吗? (我也尝试过 POST 请求...)

这些是我的代码:

 def home(request):

 auctions = Auction.objects.filter(status=True)

 form = detailForm(request.GET or None)

 if request.method == "GET":

     id = request.GET.get("id")

     if form.is_valid():

         [bid(request,auction) for auction in auctions if auction.id==id]

     else:

         form = detailForm()

 return render(request, "index.html", {"auctions":auctions, "form":form})
def bid(request, auction):

user = request.user

form = bidForm(request.POST)

if request.method == "POST":

    bid = request.POST.get("endPrice")

    if form.is_valid():

        if bid > auction.startPrice:

            auctionUpdate=form.save(commit=False)
            auctionUpdate.endPrice=bid
            auctionUpdate.winner=user
            auctionUpdate.save()

        else:

            messages.warning(request, "Devi puntare una cifra superiore a quella vincente!")
    else:

        form = bidForm()

return render(request, "bid.html", {"form":form})
class detailForm(forms.ModelForm):

class Meta:
    model = Auction
    fields = ("id",)

谢谢大家!

不确定我是否理解你的问题,所以基本上我们有一个拍卖列表,当用户点击拍卖的相关按钮时,用户将被重定向到另一个页面。

在此模型中,您需要考虑 2 个视图和 2 个模板来处理它们。 ListView 用于列出您的所有操作,DetailView 用于处理每次拍卖的详细信息页面。因此,您的 ListView 将有一个 home.html,您的拍卖详情将有一个 bid.html

我认为表单提交应该在您的详细视图中实现(在您的代码中 bid 函数),并且详细视图应该使用 bid.html 模板呈现页面。

在您的 home.html 中,您可能只想留下每个拍卖的 link,例如:

{% for auction in auctions %}

<a type='button' href="{{ auction.get_absolute_url }}">{{ auction.name }}</a>

{% endfor %}

您需要在您的 Auction 模型中添加此 get_absolute_url 方法,例如:

# models.py
    def get_absolute_url(self):
        return reverse("auction-detail", kwargs={"pk": self.pk})

也在您的路由中:

# urls.py
urlpatterns = [
    path('/', home, name='home'),
    path('/auctions/<int:pk>/', bid, name='auction-detail'),
]

您还需要将 auction 传递给 bid 函数中的上下文变量,以便在模板中引用它。

def bid (request, auction_id):
    auction = Auction.objects.get_object_or_404(id=auction_id)
    # ...
    context = {'form': form, 'auction': auction}
    return render(request, "bid.html", context)

最后在您的详细视图模板 (bid.html) 中,使用表单提交:

<form method="POST">
{% csrf_token %}
   {{ form.as_p }}
   <input type="hidden" name="id" value={{auction.id}}>
   <input type="submit">
</form>

另一个建议是在这种情况下尝试使用 Class Based View 例如 ListViewDetailView,这将处理您的问题容易多了。查看 this article 了解更多详情。