Django中AccessToken匹配查询不存在问题排查及代码咨询
Let's break down why you're hitting this error even when your access token seems valid, and fix it step by step:
1. Wrong Data Retrieval Method for DRF Requests
Your current code uses request.POST.get("access_token") to fetch the token, but if you're sending a JSON payload in Postman (instead of form-data), Django REST Framework doesn't populate request.POST—it stores JSON data in request.data instead. This means your code is actually trying to query an access token with a None value, which naturally doesn't exist.
Fix: Replace all request.POST calls with request.data in your customer_add_order view, and fix the JSON parsing issue:
# Replace this: access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) # With this: access_token = AccessToken.objects.get(token = request.data.get("access_token"), expires__gt = timezone.now()) # Also update other POST references: if not request.data.get("address"): return JsonResponse({"status": "failed", "error": "Address is required."}) order_details = json.loads(request.data["order_details"]) # Use json.loads() for string payloads, not json.load() # And in Order creation: restaurant_id = request.data["restaurant_id"] address = request.data["address"]
2. Missing Exception Handling for Edge Cases
Right now, if the token is invalid, expired, or missing, your code will throw an uncaught DoesNotExist exception instead of returning a meaningful error. Adding a try-except block will help you debug exactly what's going wrong.
Fix: Wrap the AccessToken query in a try-except:
try: access_token = AccessToken.objects.get( token=request.data.get("access_token"), expires__gt=timezone.now() ) except AccessToken.DoesNotExist: return JsonResponse({"status": "fail", "error": "Invalid or expired access token"})
3. Verify Timezone Consistency
Double-check that the expires field on your AccessToken model is saved using timezone-aware datetime objects. If your token's expiration time is stored in UTC but your server's timezone is different, expires__gt = timezone.now() might incorrectly mark valid tokens as expired.
Fix: Ensure you use timezone-aware times when creating AccessTokens:
# Example token creation code from django.utils import timezone from datetime import timedelta expires_at = timezone.now() + timedelta(hours=24) # 24-hour expiration AccessToken.objects.create(token=generated_token, user=user, expires=expires_at)
4. Confirm Postman Request Setup
Make sure your Postman request is configured correctly:
- If sending JSON: Set the request body to
raw > JSONand include all parameters (access_token, restaurant_id, etc.) in the JSON object. - If using form-data: Ensure the
access_tokenkey is spelled correctly and has the valid token value.
Modified customer_add_order View (Incorporating All Fixes)
import json from django.utils import timezone from django.http import JsonResponse from .models import AccessToken, Customer, Order, Meal, OrderDetails def customer_add_order(request): """ params: access_token restaurant_id address order_details(json format), example: [{"meal_id": 1, "quantity":2}, {"meal_id": 2, "quantity":3}] stripe_token return: {"status": "success"} """ if request.method == "POST": # Get token with error handling try: access_token = AccessToken.objects.get( token=request.data.get("access_token"), expires__gt=timezone.now() ) except AccessToken.DoesNotExist: return JsonResponse({"status": "fail", "error": "Invalid or expired access token"}) # Get profile customer = access_token.user.customer # Check if customer has an undelivered order (use .exists() for efficiency) if Order.objects.filter(customer=customer).exclude(status=Order.DELIVERED).exists(): return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"}) # Check Address if not request.data.get("address"): return JsonResponse({"status": "failed", "error": "Address is required."}) # Get Order Details with error handling try: order_details = json.loads(request.data["order_details"]) except (KeyError, json.JSONDecodeError): return JsonResponse({"status": "fail", "error": "Invalid or missing order_details"}) order_total = 0 for meal in order_details: try: meal_obj = Meal.objects.get(id=meal["meal_id"]) order_total += meal_obj.price * meal["quantity"] except Meal.DoesNotExist: return JsonResponse({"status": "fail", "error": f"Meal with ID {meal['meal_id']} does not exist"}) if order_details: # Step 1 - Create an Order order = Order.objects.create( customer=customer, restaurant_id=request.data["restaurant_id"], total=order_total, status=Order.PENDING, address=request.data["address"] ) # Step 2 - Create Order details for meal in order_details: meal_obj = Meal.objects.get(id=meal["meal_id"]) OrderDetails.objects.create( order=order, meal_id=meal["meal_id"], quantity=meal["quantity"], sub_total=meal_obj.price * meal["quantity"] ) return JsonResponse({"status": "success"})
内容的提问来源于stack exchange,提问作者bruhsmh

