В админке django надо при выборе категории в одном поле показывать в поле Подкатегории только относящиеся к выбранной категории подкатегории.
Вот так:
Попробовал применить это решение, но у меня оно не работает.
models.py:
from django.db import models
from django.urls import reverse
class Category(models.Model):
cat_name = models.CharField(max_length=25, verbose_name='Название', db_index=True)
cat_slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="SLUG")
@staticmethod
def get_all_categories():
return Category.objects.all()
def __str__(self):
return self.cat_name
def get_absolute_url(self):
return reverse('category', kwargs={'cat_slug': self.cat_slug})
class Meta:
verbose_name_plural = 'Категории'
verbose_name = 'Категория'
ordering = ['cat_name']
class SubCategory(models.Model):
subcategories = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, blank=True, db_index=True,
verbose_name='Категория')
scat_name = models.CharField(max_length=25, unique=True, db_index=True, verbose_name='Название')
scat_slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="SLUG")
@staticmethod
def get_all_subcategories():
return SubCategory.objects.all()
def __str__(self):
return self.scat_name
def get_absolute_url(self):
return reverse('subcategory', kwargs={'scat_slug': self.scat_slug})
class Meta:
verbose_name_plural = 'ПодКатегории'
verbose_name = 'ПодКатегория'
ordering = ['scat_name']
class Product(models.Model):
# category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE)
# subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE)
price = models.IntegerField(default=0, verbose_name="Цена")
category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, verbose_name="Категория")
subcategory = models.ForeignKey('SubCategory', on_delete=models.SET_NULL, null=True, verbose_name="ПодКатегория")
title = models.CharField(max_length=255, db_index=True, verbose_name="Название")
slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
content = models.TextField(blank=True, verbose_name="Текст")
photo = models.ImageField(upload_to="images/%Y/%m/%d/", verbose_name="Фото")
time_create = models.DateTimeField(auto_now_add=True, verbose_name="Создано")
time_update = models.DateTimeField(auto_now=True, verbose_name="Обновлено")
is_published = models.BooleanField(default=True, verbose_name="Опубликовано")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product', kwargs={'prod_slug': self.slug})
class Meta:
verbose_name = 'Товар'
verbose_name_plural = 'Товары'
ordering = ['id']
views.py:
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render
from django.views.generic import ListView
import json
from .models import *
menu = ["Главная", "Обратная связь", "Войти"]
def index(request):
products = Product.objects.all()
categories = Category.objects.all()
subcategories = SubCategory.objects.all()
context = {'products': products,
'subcategories': subcategories,
'categories': categories,
'menu': menu,
'title': 'Главная страница',
'cat_selected': 0,
'sub_cat_selected': 0,
}
return render(request, 'main/index.html', context)
def get_subcategory(request):
scat_id = request.GET.get('id', '')
result = list(SubCategory.objects.filter(id=int(scat_id)).values('id', 'scat_name'))
return HttpResponse(json.dumps(result), content_type="application/json")
def pageNotFound(request, exception):
return HttpResponseNotFound('<h1>Страница не найдена</h1>')
admin.py:
from django.contrib import admin
from django.utils.safestring import mark_safe
from .models import *
class CategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
list_display_links = ('id', 'name')
search_fields = ('name',)
prepopulated_fields = {"cat_slug": ("name",)}
class ProductAdmin(admin.ModelAdmin): # поля в админке
list_display = ('id', 'category', 'subcategory', 'title', 'time_create', 'get_html_photo', 'is_published')
list_display_links = ('id', 'title')
search_fields = ('title', 'content')
list_editable = ('is_published',)
list_filter = ('is_published', 'time_create')
prepopulated_fields = {"slug": ("title",)}
fields = (
'category', 'subcategory', 'title', 'slug', 'content', 'photo', 'get_html_photo', 'price', 'is_published',
'time_create',
'time_update')
readonly_fields = ('time_create', 'time_update', 'get_html_photo')
save_on_top = True
def get_html_photo(self, object):
if object.photo:
return mark_safe(f"<img src='{object.photo.url}' width=50>")
get_html_photo.short_description = "Фото"
class SubCategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'subcategories', 'scat_name')
list_display_links = ('id', 'scat_name')
search_fields = ('scat_name',)
prepopulated_fields = {"scat_slug": ("scat_name",)}
class CategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'cat_name')
list_display_links = ('id', 'cat_name')
search_fields = ('cat_name',)
prepopulated_fields = {"cat_slug": ("cat_name",)}
admin.site.register(Product, ProductAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(SubCategory, SubCategoryAdmin)
admin.site.site_title = 'Админка сайта' # Название вкладки в браузере
admin.site.site_header = 'Админка' # Заголовок в админке
urls.py:
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include, re_path
from main.views import get_subcategory
from medisearch import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
re_path(r'^getSubcategory/$', get_subcategory),
]
if settings.DEBUG:
import mimetypes
mimetypes.add_type("application/javascript", ".js", True)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
change_form.html:
{% extends "admin/change_form.html" %}
{% load static %}
{% block extrahead %}
{{ block.super }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
// inspect html to check id of category select dropdown.
$(document).on("change", "select#id_category", function () {
$.getJSON("/getSubcategory/", { id: $(this).val() }, function (j) {
var options = '<option value="">---------</option>';
for (var i = 0; i < j.length; i++) {
options +=
'<option value="' + j[i].id + '">' + j[i].name + "</option>";
}
// inspect html to check id of subcategory select dropdown.
$("select#id_subcategory").html(options);
});
});
});
</script>
{% endblock %}
Подскажите, пожалуйста, что не так сделано? Или есть другие рабочие варианты решений?