У меня следующая проблема: у меня много полей (в модели Toppings), и я не могу заполнить его. Сначала я попытался использовать list и set (), а затем попытался использовать только один объект и add () в views.py, но ни один из них не вернет ничего, кроме none. Я смотрел на документацию и другие вопросы на форуме, но я просто не могу понять это. Любая помощь с благодарностью!
views.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.core import serializers
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from orders.models import Meal, Topping, Order
def order(request):
# Request should be ajax and method should be POST.
if request.is_ajax and request.method == "POST":
# Get IDs of meal, topping(s) and user
idmeal = request.POST["idmeal"]
idmeal = Meal.objects.get(pk = idmeal)
# Topping[] is a list of numbers representing IDs for Topping database
topping = request.POST.getlist('topping[]')
for i in range(0, len(topping)):
topping[i] = int(topping[i])
user = request.user
userID = User.objects.get(username=user.username)
topping = Topping.objects.filter(pk__in=topping)
print(topping)
# Create object in Order table
order = Order.objects.create(customerID = userID, mealID = idmeal, price = 12, status = "pending")
# Add values to ManyToManyField
order.toppingsID.set(topping)
print(order.toppingsID)
return JsonResponse({"success": ""}, status=200)
else:
# some error occured
return JsonResponse({"error": ""}, status=400)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Meal(models.Model):
meal = models.CharField(max_length=64)
classname = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return f"{self.meal} ({self.classname}) ({self.price}) (id: {self.id})"
# Create your models here.
class Topping(models.Model):
topping = models.CharField(max_length=64)
classname = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
def __str__(self):
return f"{self.topping} ({self.classname}) ({self.price}) (id: {self.id})"
class Order(models.Model):
customerID = models.ForeignKey(User, on_delete=models.CASCADE)
mealID = models.ForeignKey(Meal, on_delete=models.CASCADE)
toppingsID = models.ManyToManyField(Topping, blank=True)
price = models.DecimalField(max_digits=5, decimal_places=2)
status = models.CharField(max_length=64)
def __str__(self):
return f"{self.customerID} has ordered {self.mealID} with {self.toppingsID} which costs {self.price} (status : {self.status})"