Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?
at this moment I am creating a project to learn how to use django. In this project there are three models:
- Category
- Subcategory
- Product
And what I'm trying to achieve is to dynamically choose the corresponding subcategory after selecting the category, and thus be able to add the product.
I tried to use smart_selects without results, since it is not compatible with python 3.7
I tried to filter the list of subcategories using the selected category field as a filter, without success, I think I am not formulating the code well, so that it takes the value of the category field to filter the list of subcategories dynamically.
This is my code:
///////////
//models.py
"""Z"""
from django.db import models
class Category(models.Model):
"""Z"""
category_name = models.CharField("Name", max_length=50)
class Meta:
ordering = ('pk',)
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
"""Z"""
return self.category_name
class Subcategory(models.Model):
"""Z"""
subcategory_name = models.CharField("Name", max_length=50)
subcategory_parent = models.ForeignKey(
Category, verbose_name="Parent", on_delete=models.CASCADE)
class Meta:
ordering = ('pk',)
verbose_name = "Subcategory"
verbose_name_plural = "Subcategories"
def __str__(self):
return self.subcategory_name
class Product(models.Model):
"""Z"""
category = models.ForeignKey(
Category, verbose_name="Category", on_delete=models.SET_NULL, null=True)
subcategory = models.ForeignKey(
Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True)
product_name = models.CharField("Name", max_length=50, unique=True)
class Meta:
ordering = ('pk',)
verbose_name = "Product"
verbose_name_plural = "Products"
def __str__(self):
"""Z"""
return self.product_name
///////////
//admin.py
"""Z"""
from django.contrib import admin
from .models import Category, Subcategory, Product
class SubcategoryInline(admin.StackedInline):
"""Z"""
model = Subcategory
extra = 1
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
"""Z"""
inlines = (SubcategoryInline,)
@admin.register(Subcategory)
class SubcategoryAdmin(admin.ModelAdmin):
"""Z"""
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
"""Z"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "subcategory":
kwargs["queryset"] = Subcategory.objects.filter(subcategory_parent=request.category)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
#
/////////////////////////////////////
//And this is the error that is shown when I'm trying to use it:
AttributeError at /admin/prototype/product/add/
'WSGIRequest' object has no attribute 'category'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/prototype/product/add/
Django Version: 2.0.9
Exception Type: AttributeError
Exception Value:
'WSGIRequest' object has no attribute 'category'
Exception Location: C:asppilgrimprototypeadmin.py in formfield_for_foreignkey, line 30
Python Executable: C:Program FilesPython37python.exe
Python Version: 3.7.0
Python Path:
['C:asppilgrim',
'C:Program FilesPython37python37.zip',
'C:Program FilesPython37DLLs',
'C:Program FilesPython37lib',
'C:Program FilesPython37',
'C:UserslisandroAppDataRoamingPythonPython37site-packages',
'C:Program FilesPython37libsite-packages']
Server time: Tue, 1 Jan 2019 11:48:18 -0400
django forms foreign-keys cascadingdropdown
add a comment |
at this moment I am creating a project to learn how to use django. In this project there are three models:
- Category
- Subcategory
- Product
And what I'm trying to achieve is to dynamically choose the corresponding subcategory after selecting the category, and thus be able to add the product.
I tried to use smart_selects without results, since it is not compatible with python 3.7
I tried to filter the list of subcategories using the selected category field as a filter, without success, I think I am not formulating the code well, so that it takes the value of the category field to filter the list of subcategories dynamically.
This is my code:
///////////
//models.py
"""Z"""
from django.db import models
class Category(models.Model):
"""Z"""
category_name = models.CharField("Name", max_length=50)
class Meta:
ordering = ('pk',)
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
"""Z"""
return self.category_name
class Subcategory(models.Model):
"""Z"""
subcategory_name = models.CharField("Name", max_length=50)
subcategory_parent = models.ForeignKey(
Category, verbose_name="Parent", on_delete=models.CASCADE)
class Meta:
ordering = ('pk',)
verbose_name = "Subcategory"
verbose_name_plural = "Subcategories"
def __str__(self):
return self.subcategory_name
class Product(models.Model):
"""Z"""
category = models.ForeignKey(
Category, verbose_name="Category", on_delete=models.SET_NULL, null=True)
subcategory = models.ForeignKey(
Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True)
product_name = models.CharField("Name", max_length=50, unique=True)
class Meta:
ordering = ('pk',)
verbose_name = "Product"
verbose_name_plural = "Products"
def __str__(self):
"""Z"""
return self.product_name
///////////
//admin.py
"""Z"""
from django.contrib import admin
from .models import Category, Subcategory, Product
class SubcategoryInline(admin.StackedInline):
"""Z"""
model = Subcategory
extra = 1
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
"""Z"""
inlines = (SubcategoryInline,)
@admin.register(Subcategory)
class SubcategoryAdmin(admin.ModelAdmin):
"""Z"""
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
"""Z"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "subcategory":
kwargs["queryset"] = Subcategory.objects.filter(subcategory_parent=request.category)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
#
/////////////////////////////////////
//And this is the error that is shown when I'm trying to use it:
AttributeError at /admin/prototype/product/add/
'WSGIRequest' object has no attribute 'category'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/prototype/product/add/
Django Version: 2.0.9
Exception Type: AttributeError
Exception Value:
'WSGIRequest' object has no attribute 'category'
Exception Location: C:asppilgrimprototypeadmin.py in formfield_for_foreignkey, line 30
Python Executable: C:Program FilesPython37python.exe
Python Version: 3.7.0
Python Path:
['C:asppilgrim',
'C:Program FilesPython37python37.zip',
'C:Program FilesPython37DLLs',
'C:Program FilesPython37lib',
'C:Program FilesPython37',
'C:UserslisandroAppDataRoamingPythonPython37site-packages',
'C:Program FilesPython37libsite-packages']
Server time: Tue, 1 Jan 2019 11:48:18 -0400
django forms foreign-keys cascadingdropdown
add a comment |
at this moment I am creating a project to learn how to use django. In this project there are three models:
- Category
- Subcategory
- Product
And what I'm trying to achieve is to dynamically choose the corresponding subcategory after selecting the category, and thus be able to add the product.
I tried to use smart_selects without results, since it is not compatible with python 3.7
I tried to filter the list of subcategories using the selected category field as a filter, without success, I think I am not formulating the code well, so that it takes the value of the category field to filter the list of subcategories dynamically.
This is my code:
///////////
//models.py
"""Z"""
from django.db import models
class Category(models.Model):
"""Z"""
category_name = models.CharField("Name", max_length=50)
class Meta:
ordering = ('pk',)
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
"""Z"""
return self.category_name
class Subcategory(models.Model):
"""Z"""
subcategory_name = models.CharField("Name", max_length=50)
subcategory_parent = models.ForeignKey(
Category, verbose_name="Parent", on_delete=models.CASCADE)
class Meta:
ordering = ('pk',)
verbose_name = "Subcategory"
verbose_name_plural = "Subcategories"
def __str__(self):
return self.subcategory_name
class Product(models.Model):
"""Z"""
category = models.ForeignKey(
Category, verbose_name="Category", on_delete=models.SET_NULL, null=True)
subcategory = models.ForeignKey(
Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True)
product_name = models.CharField("Name", max_length=50, unique=True)
class Meta:
ordering = ('pk',)
verbose_name = "Product"
verbose_name_plural = "Products"
def __str__(self):
"""Z"""
return self.product_name
///////////
//admin.py
"""Z"""
from django.contrib import admin
from .models import Category, Subcategory, Product
class SubcategoryInline(admin.StackedInline):
"""Z"""
model = Subcategory
extra = 1
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
"""Z"""
inlines = (SubcategoryInline,)
@admin.register(Subcategory)
class SubcategoryAdmin(admin.ModelAdmin):
"""Z"""
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
"""Z"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "subcategory":
kwargs["queryset"] = Subcategory.objects.filter(subcategory_parent=request.category)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
#
/////////////////////////////////////
//And this is the error that is shown when I'm trying to use it:
AttributeError at /admin/prototype/product/add/
'WSGIRequest' object has no attribute 'category'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/prototype/product/add/
Django Version: 2.0.9
Exception Type: AttributeError
Exception Value:
'WSGIRequest' object has no attribute 'category'
Exception Location: C:asppilgrimprototypeadmin.py in formfield_for_foreignkey, line 30
Python Executable: C:Program FilesPython37python.exe
Python Version: 3.7.0
Python Path:
['C:asppilgrim',
'C:Program FilesPython37python37.zip',
'C:Program FilesPython37DLLs',
'C:Program FilesPython37lib',
'C:Program FilesPython37',
'C:UserslisandroAppDataRoamingPythonPython37site-packages',
'C:Program FilesPython37libsite-packages']
Server time: Tue, 1 Jan 2019 11:48:18 -0400
django forms foreign-keys cascadingdropdown
at this moment I am creating a project to learn how to use django. In this project there are three models:
- Category
- Subcategory
- Product
And what I'm trying to achieve is to dynamically choose the corresponding subcategory after selecting the category, and thus be able to add the product.
I tried to use smart_selects without results, since it is not compatible with python 3.7
I tried to filter the list of subcategories using the selected category field as a filter, without success, I think I am not formulating the code well, so that it takes the value of the category field to filter the list of subcategories dynamically.
This is my code:
///////////
//models.py
"""Z"""
from django.db import models
class Category(models.Model):
"""Z"""
category_name = models.CharField("Name", max_length=50)
class Meta:
ordering = ('pk',)
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
"""Z"""
return self.category_name
class Subcategory(models.Model):
"""Z"""
subcategory_name = models.CharField("Name", max_length=50)
subcategory_parent = models.ForeignKey(
Category, verbose_name="Parent", on_delete=models.CASCADE)
class Meta:
ordering = ('pk',)
verbose_name = "Subcategory"
verbose_name_plural = "Subcategories"
def __str__(self):
return self.subcategory_name
class Product(models.Model):
"""Z"""
category = models.ForeignKey(
Category, verbose_name="Category", on_delete=models.SET_NULL, null=True)
subcategory = models.ForeignKey(
Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True)
product_name = models.CharField("Name", max_length=50, unique=True)
class Meta:
ordering = ('pk',)
verbose_name = "Product"
verbose_name_plural = "Products"
def __str__(self):
"""Z"""
return self.product_name
///////////
//admin.py
"""Z"""
from django.contrib import admin
from .models import Category, Subcategory, Product
class SubcategoryInline(admin.StackedInline):
"""Z"""
model = Subcategory
extra = 1
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
"""Z"""
inlines = (SubcategoryInline,)
@admin.register(Subcategory)
class SubcategoryAdmin(admin.ModelAdmin):
"""Z"""
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
"""Z"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "subcategory":
kwargs["queryset"] = Subcategory.objects.filter(subcategory_parent=request.category)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
#
/////////////////////////////////////
//And this is the error that is shown when I'm trying to use it:
AttributeError at /admin/prototype/product/add/
'WSGIRequest' object has no attribute 'category'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/prototype/product/add/
Django Version: 2.0.9
Exception Type: AttributeError
Exception Value:
'WSGIRequest' object has no attribute 'category'
Exception Location: C:asppilgrimprototypeadmin.py in formfield_for_foreignkey, line 30
Python Executable: C:Program FilesPython37python.exe
Python Version: 3.7.0
Python Path:
['C:asppilgrim',
'C:Program FilesPython37python37.zip',
'C:Program FilesPython37DLLs',
'C:Program FilesPython37lib',
'C:Program FilesPython37',
'C:UserslisandroAppDataRoamingPythonPython37site-packages',
'C:Program FilesPython37libsite-packages']
Server time: Tue, 1 Jan 2019 11:48:18 -0400
django forms foreign-keys cascadingdropdown
django forms foreign-keys cascadingdropdown
asked Jan 1 at 15:59
Lisandro DanielLisandro Daniel
61
61
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996879%2fis-there-a-simple-way-to-create-chained-dynamic-drop-down-list-in-django-admin-s%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996879%2fis-there-a-simple-way-to-create-chained-dynamic-drop-down-list-in-django-admin-s%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
