Reputation: 574
I'm using Django 2.2 with Python 3.7, my question have two parts:
CharField
with multiple choices, and only that charfield
is being show with a null
value, so if I change it to some option another charfield
will appear below with more options to choose, of course, all the charfields
are defined in models.py
, just hidden from the admin site until the condition is met, I think the best approach will be use JavaScript, I added the /media/
folder to my project but I didn't understand well how to integrate the JavaScript on the admin site, any help over that?.show()
and .hide()
methods, can anyone point me into the right direction to establish simple if conditions to show or to hide the fields based on another one?My admin class that holds the model I want to hide and show fields is the following one:
class RecipesAdmin(admin.ModelAdmin):
fieldsets = [
("Title/Description", {"fields": ["recipe_title", "recipe_ingredients"]}),
("Ingredients sequence", {"fields": ["sequence"]}),
("Recipe Sequence", {"fields": ["motor1", "motor2", "motor3", "motor4", "pump", "temp", "recipe_interval"]}),
("Photo and Create Date", {"fields": ["recipe_photo", "recipe_created"]})
]
formfield_overrides = {
models.TextField: {'widget': TinyMCE()}
}
If you see the "Recipe sequence" it has multiple values, I want motor2, 3, 4, and the rest to be appearing according the previous one, so no clue how to access this part of the code from JavaScript
Upvotes: 2
Views: 1265
Reputation: 574
I solved this by my own in the following way, I added to my admin class RecipesAdmin the class Media pointing to a java script file, and defining classes in the fieldsets array:
class RecipesAdmin(admin.ModelAdmin):
fieldsets = [
("Title/Description", {"fields": ["recipe_title", "recipe_ingredients"]}),
("Ingredients sequence", {"fields": ["sequence"]}),
(None, {"fields": ["sequence2",], "classes": ("HiddenSequence",)}),
("Photo and Create Date", {"fields": ["recipe_photo", "recipe_created"]})
]
class Media:
js = ('main/JS/ShowOrHideSequence.js',)
As you can see, the field "sequence2" have the class "HiddenSequence", this will let me control everything with JavaScript, the javascript code is the following:
$(function($) {
$(function() {
var sequence = $('#id_sequence'), verified = $('.HiddenSequence');
function toggleVerified(value, HiddenSeq) {
if (value !== '') {
HiddenSeq.show();
} else {
HiddenSeq.hide();
}
}
// show/hide on load based on pervious value of selectField
toggleVerified(sequence.val(), verified);
// show/hide on change
sequence.change(function() {
toggleVerified($(this).val(), verified);
});
});
});
Note, I found this JavaScript over the internet, is not made by myself, and as you can figure out, what it does is verify if the value "sequence" is different than '', if true, is shows the sequence2, if false, it hides it.
The javascript file needs to be on the static folder.
Upvotes: 1