You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django代码报错求助:预约页面无法跳转,项目周一需提交

Fixing Reservation Page Redirect & Query Issues

Hey there, let's tackle these problems head-on so you can get your project ready for Monday's deadline! The two code snippets you shared have clear issues that are breaking your page redirect and data retrieval—here's how to fix them:

1. The pk=request Problem

You're passing the entire request object as a primary key, which doesn't make sense. The pk needs to be a specific value (like an integer ID) that references the Book object you're trying to access.

Instead, you need to extract the actual book ID from the request. Depending on how your frontend sends data:

  • If it's a POST request (from a form), use request.POST.get('book')
  • If it's a GET request (from a URL parameter), use request.GET.get('pk')

2. The book = Book.objects.get(pk=request.post['book']) Problem

This line has two critical issues:

  • Case sensitivity: In Django, the POST data attribute is uppercase request.POST, not lowercase request.post—this will throw an attribute error right away.
  • Unsafe data access: Using request.POST['book'] will raise a KeyError if the 'book' parameter is missing from the request. Plus, get() will throw a DoesNotExist exception if no Book matches the provided ID.

Corrected Code Example

Here's a safe, working version that handles edge cases and retrieves the Book object properly:

from django.shortcuts import get_object_or_404, redirect
from .models import Book

def your_reservation_view(request):
    # Handle POST request (assuming your form submits via POST)
    if request.method == 'POST':
        # Safely get the book ID from POST data
        book_id = request.POST.get('book')
        
        # Use get_object_or_404 to handle missing IDs or non-existent books
        book = get_object_or_404(Book, pk=book_id)
        
        # Add your reservation logic here (e.g., create a Reservation object)
        
        # Redirect to your target page (use your URL name or direct URL)
        return redirect('confirmation-page')  # Replace with your actual URL name
    
    # Handle GET request (load the reserve.html page)
    return render(request, 'reserve.html')

Quick Additional Checks

  • Double-check your frontend form: Make sure the input field for the book has name="book" so the ID is sent correctly in the POST data.
  • Always return a response: If your view doesn't return a render() or redirect() call, it will cause a server error—this is a common reason pages don't redirect.
  • Debug with print statements: Add print(request.POST) temporarily to your view to confirm the 'book' parameter is being sent correctly.

内容的提问来源于stack exchange,提问作者stefanie leow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:35:50