I am trying to solve this problem for over 3 days but can't solve it yet. I know self use for a method that is under a class, but I am working with method base view so why this error occurs when I try to save the OrderItem model?
models.py
class OrderItem(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
cart = models.ManyToManyField(Cart, blank=True)
name = models.CharField(max_length=200)
district = models.ForeignKey(District, on_delete=models.CASCADE)
city = models.CharField(max_length=200)
postal_code = models.SmallIntegerField()
area = models.TextField()
phone = models.CharField(max_length=12)
status = models.CharField(max_length=20, choices=STATUS_CHOICE, default="accepted",blank=True, null=True)
email = models.EmailField()
def __str__(self):
return self.user.email
views.py
def checkout(request):
context={}
subtotal =0
forms = OrderItemForm()
context['forms'] = forms
if request.user.is_authenticated:
user = request.user
cart = Cart.objects.filter(user=user).order_by('-id')
for product in cart:
subtotal = product.total_cost
context['subtotal'] = subtotal
customer = Customer.objects.get(user=user)
if request.POST:
form = OrderItemForm(request.POST)
if form.is_valid():
instance = OrderItemForm.save(commit=False)
instance.user = user
instance.customer = customer
instance.cart = cart
instance.save()
else:
messages.warning(request, form.errors)
return render(request, 'checkout.html', context)
command-line error:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\bitspirits\rndm\shop\views.py", line 76, in checkout
instance = OrderItemForm.save(commit=False)
TypeError: save() missing 1 required positional argument: 'self'
CodePudding user response:
You need to init class instance before calling method on it. Only static method can be called without creating class instance.
You need to change line:
instance = OrderItemForm.save(commit=False)
to
instance = form.save(commit=False)
since form
is an instance of OrderItemForm
or
instance = OrderItemForm()
depends on what you want exactly