Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django many to many
I am fairly new to django and I am trying to create an app with the following models class User(models.Model): name = models.CharField(max_length=20) class Group(models.Model): identifier = models.CharField(max_length=3,primary_key=True) name = models.CharField(max_length=120) def __str__(self): return self.name class Department(models.Model): users = models.ManyToManyField(User) ric = models.CharField(max_length=12,primary_key=True) name = models.CharField(max_length=60) def __str__(self): return self.name class Encounter(models.Model): department = models.ForeignKey(Department,on_delete=models.DO_NOTHING) message = models.CharField(max_length=120) datetime = models.DateTimeField() The user would finally be the logged in user. I am able to get a set of all Department objects for a user, but how do I get the set for all Encounters with the said set of Departments? Is there some built in way or do I just use a for loop over all the Departments? -
Django model does not recognize MarkdownxFormField field
I am trying to add markdownx support to my model, which will enable preview editing from the admin panel. However, once i change my content field from models.FileField to MarkdownXFromField() django just deletes the content field when migrating and ignores it as if it wasn't part of the model at all. I've followed these docs exactly but it's not working. I have also ran collectstatic. # models.py from os.path import splitext from uuid import uuid4 from django.db import models from markdownx.fields import MarkdownxFormField def hashImageFilename(instance, name): ext = splitext(name)[1] return "images/{}{}".format(uuid4(), ext) class Article(models.Model): title = models.CharField(("title"), max_length=100) content = MarkdownxFormField() description = models.TextField(("description"), default='') uploadDate = models.DateTimeField(("uploadDate"), auto_now=True) lastModified = models.DateTimeField(("uploadDate"), auto_now=True) publicationDate = models.DateField("publicationDate") image = models.ImageField("image", upload_to=hashImageFilename) def __str__(self): return self.title # urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf.urls import url from django.conf import settings from markdownx import urls as markdownx urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/articles/', include('articles.api.urls')), url(r'^markdownx/', include('markdownx.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # admin.py from django.contrib import admin # Register your models here. from markdownx.admin import MarkdownxModelAdmin from .models import Article admin.site.register(Article, MarkdownxModelAdmin) # settings.py INSTALLED_APPS = [ #... 'markdownx' ] -
How to display "Twint response" on html page? As the data is displayed only on command promt
I am beginner in django, twint I am trying to write API call with query parameters for displaying Twint response on html page or postman, but the extracted data is displayed in command prompt. Please guide me through this. I am using Updated version of twint, Python 3.7, Django 3.0, windows 10 Below is my code views.py class UserName(APIView): def get(self,request,format=None): return self.username(request,request.query_params) def username(self, request, result): c = twint.Config() asyncio.set_event_loop(asyncio.new_event_loop()) result = twint.run.Search(c) return Response(result) -
JsonWebsocketConsumer class self.send() in a loop sends all the iterations messages at once
when I use self.send(content) in a loop , all the messages are sent at once , instead of one my one. the first self.send() in the if condition od connecting is executed perfectly but all loop self.send() messages are recieved by client at once after a delay of about 60 second. how to make it one at a time? consumer.py from channels.generic.websockets import JsonWebsocketConsumer class MyConsumer(JsonWebsocketConsumer): # Set to True if you want it, else leave it out strict_ordering = False def connect(self, message, **kwargs): super(MyConsumer,self).connect(message) pass def receive(self, content, **kwargs): if content['status'] == "connecting": content['status'] = "connected" self.send(content) elif content['status'] == "data": for p in range(5): content={ 'status': 'sending', 'polygon': p } self.send(content) time.sleep(15) self.close() def disconnect(self, message, **kwargs): pass clientside.js socket = new WebSocket("ws://" + location.host + "/mahaplans/"); socket.onopen = function () { var msg = { status: "connecting" }; socket.send(JSON.stringify(msg)) } socket.onmessage = function (e) { let status=JSON.parse(e.data) if (status["status"]=="connected") { var imageData={ #someddata } socket.send(JSON.stringify(imageData)) } if (status["status"]=="sending") { console.log(status["polygon"]) } } socket.onclose = function (event) { console.log("bye bye") } if (socket.readyState == WebSocket.OPEN) socket.onopen(); -
Partial Update option is not visible in the browsable api window
I have created the update class for put and patch operation and configured in urls too. But the only put button is visible here. The patch button is not available. views.py from django.shortcuts import render from rest_framework.views import APIView from restapp.models import employee from restapp.serializers import EmployeeSerializer from rest_framework.response import Response from rest_framework.generics import UpdateAPIView class EmployeeUpdateAPIView(UpdateAPIView): queryset=employee.objects.all() serializer_class=EmployeeSerializer lookup_field='id' urls.py from django.contrib import admin from django.urls import path,re_path from restapp import views urlpatterns = [ re_path('api/(?P<pk>\d+)/',views.EmployeeUpdateAPIView.as_view()) ] serializers.py from rest_framework.serializers import ModelSerializer from restapp.models import employee class EmployeeSerializer(ModelSerializer): class Meta: model=employee fields='__all__' models.py from django.db import models class employee(models.Model): eno = models.IntegerField() ename = models.CharField(max_length=60) esal = models.FloatField() eaddr = models.CharField(max_length=100) -
Save_model in admin not working in Django
I have a trouble with Django. Models.py: class PlaylistItem(models.Model): playlist_name = models.TextField() date_created_playlist = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) and my Admin.py : class PlaylistItemAdmin(admin.ModelAdmin): list_display=['playlist_name','author'] def save_model(self, request, obj, form, change): print("hello") obj.author = request.user super().save_model(request, obj, form, change) admin.site.register(PlaylistItem,PlaylistItemAdmin) And in console, it's not printing "hello". But in admin page, it is showing 2 'playlist_name','author', Why is it ? -
How to add additional field in Django REST Framwork Serializer GET return
I want to add additional statistics to a working serializer for the Django REST framework: If I do a GET request for multiple cases, I want to return not only the cases but a statistic about the cases matching the request (without the pagination): Request: GET /api/cases/?page=1&gender=0 What I want is return all matching cases paginated but add statistics over all matching (in this case all female) cases: { "count": 10593, "next": "http://localhost:8000/api/adrcases/?page=2", "previous": null, "stats": { "age_mean": 32.212, "age_sd": 6.12, ... } "results": [ { "code": "case_001", ... How can I modify my serializer to add an additional field like the stats field shown above? class CaseSerializer(serializers.ModelSerializer): class Meta: model = Case fields = "__all__" def update(self, instance, validated_data): ... def create(self, validated_data): ... -
Django Channels - Receive JSON objects
for a WebRTC project, I have to build up a signaling mechanism. I use Django Channels for that job. As you might know in WebRTC, there are Session Description objects that will be passed back and forth as "offer"/"answer" and also there are ICE candidate objects which will also be passed between two (or more) clients. Playing with Django Channels a little bit, I have wrote the following consumer: ''' A basic consumer that accepts WebSocket connections on the path /ws/chat/ROOM_NAME/ that takes any message it receives on the WebSocket and echos it back to the same WebSocket. we want to have multiple instances of SignallingConsumer in the same room communicate with each other. To do that we will have each SignallingConsumer add its channel to a group whose name is based on the room name. That will allow SignallingConsumers to transmit messages to all other SignallingConsumers in the same room. ''' class SignallingConsumer(WebsocketConsumer): def connect(self): print("connect() is called.") ''' Obtains the 'room_name' parameter from the URL route in chat/routing.py that opened the WebSocket connection to the consumer. Every consumer has a scope that contains information about its connection, including in particular any positional or keyword arguments from the URL … -
Returning the posts of the people a user follows
I have a user following system, I want to be able to get all the posts/showcases of the people a user follows. I have been able to implement this to a point. THE PROBLEM is that instead of getting the posts of all of a user following, it instead returns only the posts of one user, and does not return all of the user's posts that a person follows. given the models.py -- the models of the user, the follow, and the showcse(posts of the user) class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] class FollowLog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='followers') followed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='following', null=True) followed_on = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=FOLLOW_STATUS, default=FollowStatus.following.value, max_length=30) updated_on = models.DateTimeField(auto_now=True) unfollowed_on = models.DateTimeField(null=True) blocked_on = models.DateTimeField(null=True) class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) views.py to get all the posts of the users a … -
M2M in Django, intermediate table has extra field. how could I show this extra field in form and save?
I have a problem to deal with an extra field in the intermediate table. here is my models such ClinicHospital, Doctor, and DoctorClinic(custom intermediate table) class ClinicHospital(models.Model): name = models.CharField(max_length = 256) address = models.TextField() contact = models.CharField(max_length = 15) lat = models.FloatField() lon = models.FloatField() class Doctor(models.Model): name = models.CharField(max_length = 256) speciality = models.CharField(max_length = 256) contact = models.CharField(max_length = 12) speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE) clinic_hospital = models.ManyToManyField(ClinicHospital, through='DoctorHospital') class DoctorHospital(models.Model): clinic = models.ForeignKey(ClinicHospital, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) shift = models.CharField(max_length = 10) Firstly, shift is an extra field which I want to show in Doctor form as input field and save in intermediate table. Secondly, in db I entered the fields of shift as Evening/Morning manually but I am unable to fetch the record of clinic based on specific doctor with shift field by this CVB class DoctorDetailView(generic.DetailView): model = Doctor def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['clinic_hospital_list'] = self.object.clinic_hospital.all() return context this return clinics based on doctor but without shift field that is an extra field in intermediate table. here are forms as well class ClinicHospitalForm(forms.ModelForm): class Meta(): model = ClinicHospital fields = ('name','address','contact','lat','lon') class DoctorForm(forms.ModelForm): class Meta(): model = Doctor fields = ('name','speciality','contact','clinic_hospital', ) … -
Update an field in django rest framework
I have a class named Customer: class Customer(models.Model): name = models.CharField(max_length=250) status = models.IntegerField() And the serializer is: class CustomerSerializer(serializers.ModelSerilizer): class Meta: model = Customer fields = '__all__' Now how can I change/update only the status field using POST method. I am using function base view here. -
Populate a ModelForm field with an initial value obtained from a variable in django
I am using ModelForm and i want to populate my dataset_id field with an initial value that will come from the "pid" variable passed in the arguement. I ve tried something and attaching that code but its not working def home(request, pid): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = DelegateForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required p = form.save() # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: # Here I want to pass the value of "pid" to the dataset_id field so that when it renders it is populated with the value in the pid variable form = DelegateForm(initial={'dataset_id': pid}) return render(request, 'add_delegate.html', {'dform': form, 'uid': pid}) also attaching my forms.py class DelegateForm(forms.Form): dataset_id = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='Result', max_length=10) name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='Your Name', max_length=100) phone_number = forms.CharField(label='Phone Number', max_length=12, min_length=10) and template {% block content %} {% load static %} <form action="/success/" method="post"> {% csrf_token %} <div class="form-group"> <label>{{ … -
Django channels error loading javascript wrapper
channels. So far i have successfully ran the server ,as this appeared in my cmd prompt: System check identified no issues (0 silenced). January 21, 2020 - 17:43:42 Django version 3.0.2, using settings 'crm.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. however im facing with this error within my console : Failed to load resource: the server responded with a status of 404 (Not Found)websocketbridge.js:1 Uncaught ReferenceError: channels is not defined at HTMLDocument.<anonymous> ((index):353) Here is my code. in my settings: ALLOWED_HOSTS = ["0.0.0.0","127.0.0.1"] INSTALLED_APPS = [ 'channels', ..... ] WSGI_APPLICATION = 'crm.wsgi.application' ASGI_APPLICATION = 'crm.routing.application' in my routers.py: from channels.routing import ProtocolTypeRouter , URLRouter from django.urls import path from rnd.consumers import EchoConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path("ws/",EchoConsumer) ]) }) In my consumers.py: from channels.consumer import AsyncConsumer class EchoConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send({ "type" : "websocket.accept" }) async def websocket_receive(self,event): await self.send({ "type" : "websocket.send", "text" : event["text"] }) in my html: <script src="{% static '/channels/js/websocketbridge.js' %}"></script> <script type="text/javascript"> document.addEventListener('DOMContentLoaded',function(){ const webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect('/ws/'); webSocketBridge.listen(function(action,stream){ console.log("RESPONSE:",action,stream); }) document.ws = webSocketBridge; }) </script> Does anyone have a solution for this? -
Giving "Add User" user permission without giving "Change User" one
I've read it at https://docs.djangoproject.com/en/3.0/topics/auth/default/#id6 that it's not possible, but I need to have some kind of a solution for certain admins to be able to just create users, without being able to delete or change them. So is it really not possible? -
Django Single Sign On(SSO) to multiple applications
How to implement SSO in django (applications running in multiple servers). ie; if a user is logged into one application he have the functionality to switch to next application without login. so in backend we should authenticate that it is already logged into one of our application. -
How to export var form view.py and use in model
I want to use the data stored in variable var in view.py to model.py so that I set the path of uploaded file My View.py - def model_form_upload(request): if request.method == 'POST': test = str(request.get_full_path) o = urlparse.urlsplit(test) var = o.query form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload2.html', { 'form': form }) My Model.py - class Document(models.Model): document = models.FileField(upload_to=var) My Forms.py - class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) My template - <form action="{% url 'model_form_upload2' %}?test1" method="post"> {% csrf_token %} <button type="submit">test 1</button> </form> -
Celery task retry after soft time limit exceeds when late acknowledgement is enabled
I have a task that runs for around two minutes doing some DB operation. I enabled the late acknowledgment but I found that the task never retried after the soft time limit exceeded. So I added autoretry_for and retry_backoof as mentioned in the documentation of the celery version I'm using. Doing retry for the late acknowledged task is a good practice or not? If I did not set the autoretry_for then the task won't run from where it is terminated. tasks.py @shared_task(soft_time_limit=20, autoretry_for=(SoftTimeLimitExceeded, ), retry_backoff=True) def test_func_celery(current_time): fake = Faker() logger = logging.getLogger() time1 = time.perf_counter() main_time_end = current_time + 25 logger.info('Task started here \n \n') while time.time() < main_time_end: logger.info('Before doing main operations') time.sleep(10) logger.info(f'Inside Main operation ===>>> {time.time()}') while True: name = fake.first_name() logger.info(f'Inside inner operation for {name}') logger.info(f'inner operation before starts for {name}') time.sleep(12) logger.info(f'Inside inner {name}===>>> {time.time()}') logger.info(f'inner operation after finishes for {name}') break logger.info('Completed Main operation') break if time.time() >= main_time_end: logger.info('Out from main operations') time2 = time.perf_counter() logger.info(f'Total time =======>>>>>>> {time2 - time1}') return None views.py def home(request): current_time = time.time() test_func_celery.apply_async(args=(current_time, ), acks_late=True) return HttpResponse("Celery being tested here") celery.log [2020-01-21 15:28:30,708: INFO/ForkPoolWorker-7] Task started here [2020-01-21 15:28:30,708: INFO/ForkPoolWorker-7] Before doing main operations [2020-01-21 … -
How to make ajax call in Django 3.0
Hello I'm trying to make ajax call in django 3.0. From some tutorials I found that I need to use JSONResponse library to send data back to client side. I used it but its giving me error : ValueError at /workbench/retrain The view workbench.views.workbench.views.workbench didn't return an HttpResponse object. It returned None instead. My Django version is 3.0 and python version is Python 3.8.0 Below is Ajax code: function retrain(sr_number){ $.ajax({ url: '{% url "retrain" %}', type: 'POST', contentType: 'application/json', dataType: 'json', success: function (data) { alert("hi") } }); } Below is my python code : from django.shortcuts import render from workbench.models.workbench import WorkBench from django.http import JsonResponse def retrain(request): return JsonResponse({'foo':'bar'}, safe=False) I even tried adding if blocks inside retrain method for GET and POST request separately still I'm facing same issue. Error : ValueError at /workbench/retrain The view workbench.views.workbench.views.workbench didn't return an HttpResponse object. It returned None instead. Let me know if you need any other information. -
How does Waitress handle concurrent tasks?
I'm trying to build a python webserver using Django and Waitress, but I'd like to know how Waitress handles concurrent requests, and when blocking may occur. While the Waitress documentation mentions that multiple worker threads are available, it doesn't provide a lot of information on how they are implemented and how the python GIL affects them (emphasis my own): When a channel determines the client has sent at least one full valid HTTP request, it schedules a "task" with a "thread dispatcher". The thread dispatcher maintains a fixed pool of worker threads available to do client work (by default, 4 threads). If a worker thread is available when a task is scheduled, the worker thread runs the task. The task has access to the channel, and can write back to the channel's output buffer. When all worker threads are in use, scheduled tasks will wait in a queue for a worker thread to become available. There doesn't seem to be much information on Stackoverflow either. From the question "Is Gunicorn's gthread async worker analogous to Waitress?": Waitress has a master async thread that buffers requests, and enqueues each request to one of its sync worker threads when the request I/O … -
sorl-thumbnail - how to keep geometry ratio without up scaling the image?
Is it possible to get non-square ratio thumbnail from square image, without up scaling the image, when geometry parameters are larger than the source image dimensions? Example My goal is to display thumbnail in 1200x630 size or smaller, but keeping the ratio (optimal Facebook post image dimensions and proper ratio to avoid cropping image by Facebook). Source image (model.image) is 400x400, so I expect the thumbnail size to be 400x210. Let's try: {% thumbnail model.image "1200x630" crop="top" as im %} Effect? Thumbnail is 400x400, which means that neither the geometry setting has been respected, nor cropping has been done. If I use upscale parameter: {% thumbnail model.image "1200x630" crop="top" upscale="True" as im %} Then the thumbnail is 1200x630, which means that geometry setting has been respected and image has been cropped, but image is unnecessary upscaled. Is it somehow possible to create thumbnail with correct ratio without up scaling it to geometry setting? -
I am getting error in console “You need to enable JavaScript to run this app.” reactjs and django
I am working on Django and react app.after I hosted it on Heroku it shows "You need to enable JavaScript to run this app." when I tried to edit any order(product details).other API request is working perfectly except the edit component This is the response from api -
getting "Cannot read property 'getElementsByTagName' of null at getAmpHtmlLinkHref" error in rss feed in django
Asiavillenewshttp://example.com/feeds/Asiaville is a next generation multi-lingual, multimedia and multi-platform digital media venture. Our twin objectives are to reimagine journalism and disrupt news stereotypesenWed, 25 Dec 2019 05:46:31 +0000testinghttps://www.asiavillenews.com/your-take/alternative-ending/testing-NonetestingWed, 25 Dec 2019 05:46:31 +0000testing-Nonehttps://image.asiavillenews.com/versatile/Asiaville_Logo_1024x1024.jpegStanding with JNU in times of Whataboutery!https://www.asiavillenews.com/your-take/alternative-ending/standing-with-jnu-in-times-of-whataboutery-82As a public university, no other institution has earned as many adjectives in the history of India since the 1970s as JNU – swinging from extreme fondness to extreme hatred. Established in 1969 by an Act of Parliament, this university was founded to embody the visions of India’s first Prime Minister Jawaharlal Nehru – a university which “stands for humanism. For tolerance, for reason, for the adventure of ideas and for the search of truth. It stands for the onward march of the human race towards ever higher objectives. If the Universities discharge their duties adequately, then it is well with the Nation and the People”. These days if you are/were a student of JNU, one of India’s most prestigious universities, you would be caught up in a vicious cycle of hatred and conflict, as this institution has been turned into a battleground. This time the issue is of fee hike. This, per se, is not very unusual. Universities around the world … -
Django admin inline has 2 foreign keys to the same model
Currently i have the transfer model as followed: class Transfers(models.Model): class Meta: db_table = "transfers" verbose_name = 'Transfer' verbose_name_plural = 'Transfers' user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_transfer', on_delete=models.CASCADE) to_account = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_transfer_to_account', on_delete=models.SET_NULL) A transfer object need to have from one user transfer to another user so i need to use the same User model And in my admin.py: class TransfersInline(admin.StackedInline): model = Transfers can_delete = False extra = 0 max_num=0 form = TransfersAdminForm class UserAdminCustom(admin.ModelAdmin): exclude = ('password', 'last_login', 'is_superuser', 'is_staff', 'groups', 'user_permissions', 'username', 'first_name', 'last_name', 'is_active', 'date_joined') inlines = [ TransfersInline, ] def get_queryset(self, request): qs = super(UserAdminCustom, self).get_queryset(request) return qs.filter(is_staff=False) def get_readonly_fields(self, request, obj=None): return ('id', 'created', 'modified') admin.site.register(User, UserAdminCustom) In my admin i would like to display transfers inline that the User existed in user field of Transfers model but inline can't have multiple foreign key to the same model: <class 'backend.admin.TransfersInline'>: (admin.E202) 'backend.Transfers' has more than one ForeignKey to 'backend.User' My question is how do i only make TransfersInline use foreign key from user field instead of to_account field ? (transfer inline will have all the transfers object that the User is in user field ) -
Unable to save fileattachment into Django Model FileField
I am currently integrating exchange server email to my application. I am able to retrieve attachments from my emails using exchangelib. I am trying to save the attachments into my Django model filefield. However, it is not working with different errors based on different solutions I tried. Any help is appreciated. Thank you. Below are some of my code: models.py class Attachments(models.Model): name = models.CharField(max_length=255) attachment = models.FileField(upload_to="attachments/") views.py for attachment in item.attachments: if isinstance(attachment, FileAttachment): attachmentlist.append(attachment.name) saveattachments = Attachments( name=attachment.name, attachment=(attachment.content) ) saveattachments.save() -
Django, how do I display a tree without know the depth in template
I work on a web site which gonna display a tree of folders/files but I dont know what user gonna send me. That could be, 1 file in 1 folder like several folders in several folders with several files inside. For the moment, I use accordion from semantic ui for graphics, but it's not responsive with depth of tree. How could I make accordion in template responsive to data depth ? I'm not an expert of django. Thank you very much for help.