I am trying to create a product form by 'Create View' as a class-based view, but it tells there is an issue in the terminal as the following snippet.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Products(models.Model):
def __str__(self):
return self.product_name
user_name=models.ForeignKey(User, on_delete=models.CASCADE, default=1)
product_name=models.CharField(max_length=200)
product_descript=models.CharField(max_length=200)
product_price=models.IntegerField()
product_image=models.CharField(max_length=500, default='#')
def get_absolute_url(self):
return reverse('food:detail', kwargs={'pk':self.pk})
url.py
from django.urls import path
from . import views
urlpatterns=[
path('addj',views.CreateProduct.as_view(),name='add_product'),
]
views.py
from django.views.generic.edit import CreateView
from .models import Products
class CreateProduct(CreateView):
model= Products
fields=['product_name','product_descript','product_price','product_image']
template_name='food/product-form.html'
def form_valid(self,form):
format.instance.user_name=self.request.user
return super().form_valid(form)
product-form.html
<form method="POST" >
{% csrf_token %}
{{form}}
<button type="submit">
</form>
Can someone help me with this regard?
Thanks
CodePudding user response:
Error is from views.py
so you have to ways to solve error
You have wrong import of
CreateView
. correct isfrom django.views.generic import CreateView
.You can split form and view as given below. preferred way is 2nd method.
Code for forms.py
#forms.py
from django import forms
from .models import Products
class CreateProductForm(forms.ModelForm):
class Meta:
model = Products
fields=['product_name','product_descript','product_price','product_image']
Code for views.py
# views.py
from django.views import generic
from django.urls import reverse_lazy
from .forms import CreateProductForm
class CreateProduct(generic.CreateView):
form_class = CreateProductForm
template_name='food/product-form.html'
success_url = reverse_lazy('home')