Django javascript скрыть функциональность не работает
В основном я хочу, чтобы был только флажок "У этого товара есть вариации", тогда, если пользователь отметит этот флажок, то появятся флажки "Размер" и "Цвет". Если пользователь нажмет на размер, появится поле значения вариации размера. То же самое с цветом. Сейчас, хотя я и пытаюсь с помощью своего скрипта добиться этой функциональности, у меня не получается.
Что я делаю не так? Заранее спасибо!
Мой models.py:
class Product(models.Model):
name = models.CharField(max_length=100)
product_slug = models.SlugField(unique=True, blank=True)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='products/')
image2 = models.ImageField(upload_to='products/', null=True, blank=True)
business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='products')
in_stock = models.BooleanField(default=True)
is_popular = models.BooleanField(default=False)
is_best_seller = models.BooleanField(default=False)
min_delivery_time = models.PositiveIntegerField(null=True, help_text="Minimum estimated delivery time in business days")
max_delivery_time = models.PositiveIntegerField(null=True, help_text="Maximum estimated delivery time in business days")
has_variations = models.BooleanField(default=False)
def __str__(self):
return f'{self.business.business_name}, {self.name}'
def get_json_data(self):
data = {
'id': self.id,
'name': self.name,
'price': float(self.price),
'description': self.description,
'images': [self.image.url, self.image2.url] if self.image and self.image2 else [],
'min_delivery_time': self.min_delivery_time,
'max_delivery_time': self.max_delivery_time,
}
return json.dumps(data)
def save(self, *args, **kwargs):
if not self.product_slug:
self.product_slug = slugify(self.name)
super().save(*args, **kwargs)
@property
def overall_review(self):
avg_rating = self.reviews.aggregate(Avg('rating'))['rating__avg']
return round(avg_rating, 1) if avg_rating else 0
def star_rating_percentage(self, star):
total_reviews = self.reviews.count()
if total_reviews == 0:
return 0
star_count = self.reviews.filter(rating=star).count()
return round((star_count / total_reviews) * 100)
VAR_CATEGORIES = (
('size', 'Size'),
('color', 'Color'),
)
class Variation(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations')
name = models.CharField(max_length=50, choices=VAR_CATEGORIES, null=True, blank=True)
def __str__(self):
return f"{self.product.name} - {self.get_name_display()}"
class ProductVariation(models.Model):
variation = models.ForeignKey(Variation, on_delete=models.CASCADE, related_name='values', null=True)
value = models.CharField(max_length=50, null=True)
image = models.ImageField(upload_to='product_variations/', null=True, blank=True)
class Meta:
unique_together = (('variation', 'value'),)
def __str__(self):
return f"{self.variation.product.name} - {self.variation.get_name_display()} - {self.value}"
Мой views.py:
class ProductCreateView(LoginRequiredMixin, View):
def get(self, request, business_slug):
business = get_object_or_404(Business, business_slug=business_slug, seller=request.user)
return render(request, 'business/product_create.html', {'business': business, 'VAR_CATEGORIES': VAR_CATEGORIES})
def post(self, request, business_slug):
business = get_object_or_404(Business, business_slug=business_slug, seller=request.user)
if business.seller == request.user:
name = request.POST.get('name')
description = request.POST.get('description')
price = request.POST.get('price')
min_delivery_time = request.POST.get('min_delivery_time')
max_delivery_time = request.POST.get('max_delivery_time')
image = request.FILES.get('image')
image2 = request.FILES.get('image2')
in_stock = request.POST.get('in_stock') == 'on'
has_variations = request.POST.get('has_variations') == 'on'
product = Product.objects.create(
name=name,
description=description,
price=price,
image=image,
image2=image2,
min_delivery_time=min_delivery_time,
max_delivery_time=max_delivery_time,
business=business,
in_stock=in_stock,
has_variations=has_variations
)
if has_variations:
variation_names = request.POST.getlist('variation_names')
for variation_name in variation_names:
variation = Variation.objects.create(
product=product,
name=variation_name
)
variation_values = request.POST.getlist(f'variation_values_{variation_name}')
variation_images = request.FILES.getlist(f'variation_images_{variation_name}')
for i, value in enumerate(variation_values):
variation_image = variation_images[i] if i < len(variation_images) else None
ProductVariation.objects.create(
variation=variation,
value=value,
image=variation_image
)
return redirect('product_detail', business_slug=business.business_slug, product_slug=product.product_slug)
else:
return render(request, 'business/product_create.html', {'business': business, 'error': 'You are not authorized to add products to this business.', 'VAR_CATEGORIES': VAR_CATEGORIES})
Мой product_create.html:
Хорошо, где ваша функция для
Then if the user checks that box, then the Size and Colour checkboxes will show up.
что вы хотите, чтобы это произошло?