Задать вопрос
AlexayIva
@AlexayIva

У пользователя не создаётся товар на главной странице?

Добрый вечер, на моём сайте когда пользователь создаёт свой товар на главной странице ничего не отображается.
Папка create(где находится форма создания товара)
Папка catalog(где находится страница с выводом товара)

create/froms.py:
from django import forms
from .models import Create

class CreateForm(forms.ModelForm):
    class Meta:
        model = Create
        fields = ['name', 'slug', 'image',
                  'description', 'price']

create/models.py:
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.template.defaultfilters import slugify


class Create(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        index_together = (('slug'),)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Create, self).save(*args, **kwargs)

    def __str__(self):^M       
         return self.name

    def get_absolute_url(self):
        return reverse('catalog:product_detail', args=[self.id, self.slug])

create/views.py:
from django.shortcuts import render, get_object_or_404
from .models import Create
from .forms import CreateForm
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse

def product_create(request):
        if request.method == "POST":
                form = CreateForm(request.POST)
                if form.is_valid():
                        return_name = form.cleaned_data["name"]
                        return_slug = form.cleaned_data["slug"]
     <b></b>                   return_image = form.cleaned_data["image"]
                        return_description = form.cleaned_data["description"]
                        return_price = form.cleaned_data["price"]
                        current_user = request.user
                        if return_image == "":  # checks if it is empty
                                return_image = "https://i.imgur.com/qldLMTx.png"
                        create = Create(name=return_name, slug=return_slug, image=return_image, description=return_description,  price=return_price)
                        create.save()
                        return HttpResponseRedirect(reverse("catalog:product_list"))
                else:
                        return render(request, "create/create.html", {
                                        "form": form
                        })

        return render(request, "catalog/product/list.html", {
                "form": CreateForm()
        })


catalog/forms.py:
from django import forms
from .models import Category

class ProductFilterForm(forms.Form):
    q = forms.CharField(label='Search', required=False)
    category_id = forms.ModelMultipleChoiceField(
        label='Category',
        queryset=Category.objects.all(),
        queryset=forms.CheckboxSelectMultiple,
        required=False
    )
    max_price = forms.DecimalField(decimal_places=2, max_digits=12, required=False)
    min_price = forms.DecimalField(decimal_places=2, max_digits=12, required=False)


catalog/models.py:
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.template.defaultfilters import slugify

class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, unique=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('catalog:product_list_by_category', args=[self.slug])

class Product(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='products_created', on_delete=models.CASCADE)
    category = models.ForeignKey(
        Category, related_name='products', on_delete=models.CASCADE)
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    stock = models.PositiveIntegerField(default=1)

    class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Product, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('catalog:product_detail', args=[self.id, self.slug])

catalog/views.py:
from django.shortcuts import render, get_object_or_404
from .models import Product, Category
from cart.forms import CartAddProductForm

def home(request):
    return render(request, 'catalog/home.html', {})

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
    return render(request, 'catalog/product/list.html', {'category': category,  'categories': categories, 'products': products})

def product_detail(request, id, slug):
    product = get_object_or_404(Product, id=id, slug=slug, available=True)
    cart_product_form = CartAddProductForm()
    return render(request, 'catalog/product/detail.html', {'product': product, 'cart_product_form': cart_product_form})

Буду признателен за вашу помощь!
  • Вопрос задан
  • 45 просмотров
Подписаться 1 Простой Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы