Reputation: 759
I am trying to add an item in the database but I keep getting the TypeError, what am i doing wrong please. I have the model class for it and I am using the Django ModelForm to implement the Create operation.
Error Log
Traceback (most recent call last):
File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\SMS\core\views.py", line 26, in Addproduct
form = Addproduct()
Exception Type: TypeError at /add-product/
Exception Value: Addproduct() missing 1 required positional argument: 'request'
models.py
class Product(models.Model):
name = models.CharField(max_length=36)
price = models.PositiveIntegerField()
description = models.TextField()
quantity = models.PositiveIntegerField()
image = models.ImageField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
forms.py
from django import forms
from .models import *
class Addproduct(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
views.py
def Addproduct(request):
form = Addproduct()
if request.method == 'POST':
form = Addproduct(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, "Products Added Successfully")
return redirect('product')
context = {"form":form}
return render(request, "core/addstation.html", context)
Upvotes: 1
Views: 488
Reputation: 476557
You have given the view the same name as the form, so if you call Addproduct
, it will call the view, since the view overwrote the reference to the form.
I suggest that you rename your form to:
from django import forms
from .models import *
# ↓ rename to …Form
class AddproductForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
and update the view with:
def add_product(request):
form = AddproductForm()
if request.method == 'POST':
form = AddproductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'Products Added Successfully')
return redirect('product')
context = {'form':form}
return render(request, 'core/addstation.html', context)
Normally function-based views are written in snake_case
, so add_product
instead of .AddProduct
Upvotes: 1