Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throws AttributeError: 'str' object has no attribute '_meta' when I register my Model
Im novice and I didnt find solution for problem here. Im writing code for blog. I have a model Post where I want to create field author which is ForeighKey to User. If I make migration without admin.site.register - everything is ok. But then Im trying to register my Model to Django admin it throws AttributeError: 'str' object has no attribute '_meta' Comment: my idea is that every user (after registration) can create post. And I want to show some inforamtion about author using User model models.py from django.db import models from django.contrib.auth import get_user_model class Post(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name='Автор', related_name='posts', null=True) title = models.CharField(verbose_name='Заголовок объявления', max_length=255) text = models.TextField(verbose_name='Текст объявления') CATEGORIES = ( ('T','Танки'), ('HM','Хилы'), ('DD','ДД'), ('TrM','Торговцы'), ('GM','Гилдмастеры'), ('QG','Квестгиверы'), ('FM','Кузнецы'), ('LM','Кожевники'), ('PM','Зельевары'), ('WM','Мастера заклинаний') ) category = models.CharField(verbose_name='Категория', max_length=3, choices=CATEGORIES) pub_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') class Meta: verbose_name = 'Пост' verbose_name_plural = 'Посты' def __str__(self): return self.title admin.py from django.contrib import admin admin.site.register('Post') -
Django, use annotated field or SQL function in Case & When
I'm trying to do a query where I use an average of a column against its latest value and then use it in Case and When. I can successfully annotate the monthly average and latest field but not compare them in the DB: this is the direction of what I'm trying to do latest_known_kpi_obj = KPIs.objects.filter(tag_count__isnull=False, group__id=OuterRef(ID)) tag_count_of_latest = Subquery(latest_known_kpi_obj.values(ASSIGNED_TAG_COUNT)[:1]) places_count_of_latest = Subquery(latest_known_kpi_obj.values(PLACES_COUNT)[:1]) user = self.request.user self.kpis = user.user_selected_kpis.get_all_kpis_qs() kpis_monthly_averages_annotations = {} latest_kpis = {} for kpi in self.kpis: latest_kpis[f'{kpi.internal_name}_latest'] = Subquery(latest_known_kpi_obj.values(kpi.internal_name)[:1]) kpis_monthly_averages_annotations[f'{kpi.internal_name}_trend'] = Case( When(condition=Avg(f'farm_scores__{kpi.internal_name}', filter=Q(farm_scores__date__range=month_range)) < (latest_kpis[f'{kpi.internal_name}_latest']), then=1), When(Avg(f'farm_scores__{kpi.internal_name}', filter=Q(farm_scores__date__range=month_range)) > (latest_kpis[f'{kpi.internal_name}_latest']), then=-1), default=0 ) query_set = (Group.objects.filter(**filters). annotate(**kpis_monthly_averages_annotations,**latest_kpis) this is not possible '<' not supported between instances of 'Avg' and 'Subquery' -
How to search by the date?
I am trying to search records between two date range from database. Here is my code views: def profile(request): if request.method == 'POST': fromdate = request.POST.get('from') todate = request.POST.get('to') cursordate = connection.cursor() cursordate.execute('SELECT * FROM Lesson WHERE StartDateTime between "'+fromdate+'" and "'+todate+'"' ) data = dictfetchall(cursordate) return render(request,'personal.html',{'data':data}) else: cursordate = connection.cursor() cursordate.execute('SELECT * FROM Lesson') data = dictfetchall(cursordate) return render(request,'personal.html',{'data':data}) html: {% for lesson in data1 %} <div class="card mb-3 mt-1 shadow-sm"> <div class="card-body"> <p class="card-text"> <div class="row"> <div class="col-2"> <div>{{ lesson.StartDateTime}} - {{ lesson.EndDateTime}}</div> </div> <div class="col-4"> <div>{{ lesson.Name }}</div> </div> </div> <div class="mt-5"></div> </p> </div> </div> {% endfor %} But I get the following error: Invalid column name "2021-03-02". (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name "2021-03-03". (207)') Is it connected with the fact that type of the 'StartDateTime' is DateTime and not Date? However,I tried to hardcord dates with time in sql query it still failed. (I know that it may be done with the help of ORM Django, but I need to use raw SQL) -
best practice for django models with expanding data
I am looking to chart some data that will grow day by day. For example daily rainfall data. My plan is to scrap the data from the web using a cronjob. however im just thinking what is the best way to store this data in a django model? As the values are always growing. My plan is to store this in a django model an then graph it daily. any ideas -
Comparing Datetime in Django
I am working with Django. My database has a Schedule table with the following fields: startingTime content DateTimeField durationInMinits content IntegerField Actually, it means that any work starts at startingTime and lasts for durationInMinits (numeric value, in minute unit). If a work is started at April 22, 2021, 6 p.m. and it's durationInMinits is 30 minutes, then it will running till April 22, 2021, 6:30 p.m. Now I need to determine, does the work running time belong to the current time? Here I will determine current time by using timezone.now() function. kindly provide any suggestion to determine it. -
Django: Prefill forms with database entries from inside a loop
I want to prefill a form with already existing database entries but can't access the correct ones. A user can create a task and pass information on when creating it. When he wants to update it later, the already saved information should be used to prefill the form. My problem is, that I'm inside a for-loop and it seems that I can't access the elements of the loop. Here is what I'm doing: I'm in a template inside a for-loop. The loop lists all tasks with an update button for every task. This button calls a form via the bootstrap data-target. Here's an example: {% for task in tasks %} <button class="btn-primary btn-block btn-lg" data-toggle="modal" data-target="#updateTask">Update Task</button> {% endfor %} In my upcoming form I can't use the variables from the task element. For example the task.taskname. However, I can use all other variables like the user.first_name which exists outside the loop. <div class="modal-body"> <form method="POST" action="{% url 'update_task' %}"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="name" class="col-form-label">Task:</label> <input type="text" id="taskID" name="task" class="form-control" value="{{ user.first_name }}" required> -> this works <input type="text" id="taskID2" name="task2" class="form-control" value="{{ task.taskname }}" required> -> this doesn't </div> <input type="submit" value="Send" class="btn … -
Displaying Django images: view and model want conflicting static root directories
I have a simple model that holds a static image: DjangoProject/projects/models.py class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() tags = models.CharField(max_length=30) image = models.FilePathField(path='projects/static/img') github_link = models.CharField(max_length=100, default='None') You can see that the image path points to the static folder that contains the images to display. The static folder "img" is located in that path shown there. Here's the template that displays the image with bootstrap cards. It just calls {% static projects.image %} as it's src. DjangoProject/projects/templates/project_index.html {% extends "base.html" %} {% load static %} {% block page_content %} <h1>Projects</h1> <div class="row"> {% for project in projects %} <div class="col-md-6"> <div class="card mb-2"> <img class="card-img-top" src="{% static project.image %}"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary"> See Details </a> </div> </div> </div> {% endfor %} </div> {% endblock %} With the path /projects/static/img I can use the admin page to edit the object, but any image I select won't work. Why? Because the view wants the relative path, for instance, img/somephoto.jpg . If it's the full path, projects/static/img/somephoto.jpg, it won't work. But, if I change the model to not include the full path to the static file … -
Saving multiple forms with one POST method. (Django)
I'm trying to build a quiz, where there are multiple questions. I want to store all the answers at once. Each question is a form called "RespostaForm" . The questions come from another model. I managed to stablish a relation between the "RespostaForm" and the id_question, so that i know for which question is the answer stored. The problem is, i can't save all the answers, it's saving only the answers from the last form rendered. Here is some of the coding: (html file) {% csrf_token %} {% for pergunta in perguntas %} {% if pergunta.tema_id == 1 %} <tr> <td>{{pergunta.id}} ) {{pergunta.question}}</td> </tr> <tr> {{form}} <tr> <hr> {% endif %} {% endfor %} <div class="col-md-8"> <button type="submit" class="btn btn-success btn-block btn-lg"><i class="fas fa-database"></i> Submit </button> </div> </form> </tbody> (views.py file) def quest_perg2(request,quest_id): questionario= Questionario.objects.get(pk=quest_id) perguntas= Pergunta.objects.all() numperg = Pergunta.objects.filter(tema=1).count() if request.method == 'POST': forms = [RespostaForm(request.POST, prefix=i) for i in range(numperg)] if all((form.is_valid() for form in forms)): forms.save() return redirect('perg1',quest_id=questionario.id) else: form = RespostaForm() context={'form':form,'perguntas':perguntas,'questionario':questionario} return render(request, 'quest_perg1.html',context) (forms.py file) class RespostaForm(forms.ModelForm): class Meta: model = Resposta fields = ('id_pergunta', 'resposta') labels = { 'resposta':'Resposta', 'id_pergunta':'Pergunta' } def __init__(self, *args, **kwargs): super(RespostaForm,self).__init__(*args, **kwargs) self.fields['id_pergunta'].empty_label = "Select" self.fields['resposta'].empty_label = False -
Adapting a jQuery function to send files
A function on our website fires for all of our forms. It uses jquery's serializearray method and works great. I need to add a form with a file input, and serializearray doesn't handle files. I'm not new to Python and Django, but I am new to Jquery. And I'm having trouble adapting the function. Since the formData class handles files, I thought I could change "data: serializedform" to "data: new formData(form)". When I did that, Chrome's console displayed "Uncaught TypeError: Illegal invocation". Firefox's console displayed "Uncaught TypeError: 'append' called on an object that does not implement interface FormData." Do I need to convert the FormData object to another type? A snippet follows: uploadfile.html: function postAndLoad(form, url, panelDivID, btnName){ var serializedForm = $(form).serializeArray(); return request = $.ajax({ url: url, dataType : 'html', cache: 'false', type : 'POST', data: serializedForm, //data: new FormData(form) produces an error. success: function (data) { console.log("Completed POST"); error: function(data) { console.log('There was a problem in postAndLoad()'); console.log(data); } }); return false; }; … <form enctype="multipart/form-data" onsubmit="postAndLoad(this, '{% url 'UploadFile' %}', 'panel_upload'); return false;" method='post'> {% csrf_token %} {{ form | crispy}} <div class="row w-100"> <input class="btn" type='submit' name="form1btn" value="button" /> </div> </form> forms.py: class UploadFile(forms.Form): uploadFile = … -
Django graphene, filtering by object
Now my filter looks like this class Document(graphene.ObjectType): number = graphene.relay.ConnectionField( ReportDocumentNumberConnection, doc__number__in=graphene.List(graphene.String, required=False), doc__supplier__delivery__in=graphene.List(graphene.String, required=False), doc__supplier__number__in=graphene.List(graphene.String, required=False), ) And it works fine with Query like this { allDocuments{ number(doc_Number_In: "TVF" doc_Supplier_Delivery_In: "Q23") { ... } } } But I want to put all my filters into one object, something like this { allDocuments{ number(inputFilter: {doc_Number_In: "TVF" doc_Supplier_Delivery_In: "Q23"}) { ... } } } Is that possible? If yes, how to do that? -
Joined Blog, User, UserActive model but api showing only blog and user table data
I am new on django-rest-api. trying to learn myself. Please help me. I am having problem getting Blog, User, and UserActive model data altogether getting only Blog and User model data like this: [ { "blog_id": 1, "user": { "id": 1, "password": "pbkdf2_sha256$260000$sGvXY1BbGTEeCADbzdLe9m$Pad1fd3N7CYVvz1jQv5xMRTxikqyOFnfWr6bmqUfv5o=", "last_login": "2021-04-11T13:46:49.739205Z", "is_superuser": true, "username": "superuser", "first_name": "", "last_name": "", "email": "superuser@email.com", "is_staff": true, "is_active": true, "date_joined": "2021-04-08T13:26:43.174410Z", "groups": [], "user_permissions": [] }, "title": "first blog", "description": "hola", "image": "/images/phone.jpg", "create_at": "2021-04-08T14:24:51.122272Z", "update_at": "2021-04-08T14:37:00.287746Z" } ] but I want to get data from exteded User Model 'LastActive' for that i also added ser.objects.all().select_related('useractive') on views.py serializer.py is : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserActiveSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserActive fields = '__all__' class BlogSerializers(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Blog fields = '__all__' views.py is: @api_view(['GET']) def get_users(request): user = User.objects.all().select_related('useractive') serializer = UserSerializer(user, many=True) return Response(serializer.data) @api_view(['GET']) def get_blogs(request): blogs = Blog.objects.all() serializer = BlogSerializers(blogs, many=True) return Response(serializer.data) models.py is: class UserActive(models.Model): user_active_id = models.AutoField(primary_key=True, editable=False, null=False) user = models.OneToOneField(User, on_delete=models.CASCADE,null=False) last_active = models.DateTimeField(auto_now_add=True, editable=False) class Blog(models.Model): blog_id = models.AutoField(primary_key=True, editable=False) title = models.CharField(max_length=128,null=False,blank=False) description = models.TextField(null=True,blank=True) image=models.ImageField(null=True,blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True, … -
Django ORM: misleading `first()` for `prefetch_related`
Working on a DRF endpoint I expierenced an issue with prefetch_related and first called on the prefetched set. Let's consider two models: X and Y; Y contains a foreign key to X. Then I perform following code: qs = X.objects.all().prefetch_related("y_set") for x in qs: for y in x.y_set.all(): print(e) Everything is OK, django performs 2 queries as expected. Then I perform: for x in qs: for y in x.y_set.all(): print(e) first = x.y_set.first() In this example, Django perform n+2 queries what is not expected (at least for me). I found a workaround with: for x in qs: for y in x.y_set.all(): print(e) first = y_set.all()[0] if y_set.all() else None but it's not satisfying for me - I feel like checking if qs is not empty and then taking the first element is a bit messy, I'd definitely prefer to use first or some other function that hides this logic. Can anyone explain why first doesn't use prefetched cache or can you give me a tip how to handle it a bit clearer? (I don't want to add a wrapper to handle that, I prefer native django orm solution. Also I can't just take the first element from the loop - … -
Dynamically priced products from an external vendor
I'm trying to implement "Dynamically priced products from an external vendor" as it is referred to in the docs but have not found any instructions on how to. -
Django reverse page object numeration
I use {{ forloop.counter0|add:page_obj.start_index }} And get (pagination 3): Page1: 1 Page2: 4 2 5 3 If I use {{ forloop.revcounter0|add:page_obj.start_index }} I get: Page1: 3 Page2: 5 2 4 1 How can I get: Page1: 5 Page2: 2 4 1 3 I was thinking something like {{ paginator.count|add:SOMETHING }} -
Rest Framework not raising error to react native
When i send fetch api request to Django backend. when ever i return this Response: return Response( { 'message': 'Username is already taken' } ) , status = status.HTTP_409_CONFLICT But in this case, React native, this method did not catch any error, why? .catch(error_resp => { console.warn('error_resp : ') console.warn(error_resp) }) -
Django can't connect to MariaDB instance with Docker
I am getting the following error: (2002, "Can't connect to MySQL server on 'db' (115)"), when trying to use the Django admin dashboard (or running migrations or anything that connects to the DB). This is my docker-compose.yml: version: "3.9" services: db: image: mariadb restart: always volumes: - ./data/db:/var/lib/mysql env_file: - .env ports: - 3306:3306 healthcheck: test: "/usr/bin/mysql --user=test --password=test --execute \"SHOW DATABASES;\"" interval: 3s timeout: 1s retries: 5 web: build: . command: gunicorn -b 0.0.0.0:8000 web.wsgi volumes: - .:/usr/src/app ports: - 8000:8000 env_file: - .env depends_on: db: condition: service_healthy .env contains all MYSQL_* env variables for the server: root password, user, database name and password. It also contains env for my settings.py, which looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME', 'test'), 'USER': os.getenv('DB_USER', 'test'), 'PASSWORD': os.getenv('DB_PASSWORD', 'test'), 'HOST': os.getenv('DB_HOST', 'localhost'), 'PORT': 3306, } } For the example here, DB_HOST is set in .env to db, which is the image name in docker-compose.yml. If I jump into a bash shell of my web app, I can ping db, so it can see the mariadb container (they're on the same network). Whenever I try to use mysql in the db container though (mysql -u root -p) it … -
'ModelBackend' object has no attribute 'authenticate_header'
I have a Django API. I have multiple views with authentication_classes, as follow: class DeviceCreate(generics.CreateAPIView): """ Create a new device User Must be staff """ authentication_classes = [ModelBackend, GoogleOAuth2] permission_classes = [IsAdminUser] queryset = Device.objects.all() serializer_class = DeviceSerializer But when I want to create a device I get an error saying: 'ModelBackend' object has no attribute 'authenticate_header' Any ideas ? -
Datepicker value not retaining in Django form
So I have this DateRangePickerForm that gets the work done, except I would like it to be rendered with the initial values, as well as retain the inputted values after submit. Tried to manually render the form but nothing changed. widget=forms.DateField doesn't help either. What is strange to me is that inspecting the input html element, shows it does not have any value="" property, it is not empty, it is absent. views.py end = datetime.date.today() start = end.replace(day=1) form = DateRangePickerForm( self.request.GET, initial={ 'start_date': start, 'end_date': end } ) if form.is_valid(): start = form.cleaned_data['start_date'] end = form.cleaned_data['end_date'] form part of the template: <form action="" method="GET"> <legend><h2>Select data range:</h2></legend> {{ form }} <input type="submit" value="Submit"> </form> and the form.py class DateRangePickerForm(forms.Form): start_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'})) end_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'})) -
Access several tables with only one query
I have the same schema in my django application: class SomeModel(models.Model): value = models.CharField(max_length=30) class AbstractModel(models.Model): someModel = models.ForeignKey(SomeModel) class Meta: abstract = True class A(AbstractModel): anotherValue = models.CharField(max_length=5) class B(AbstractModel): anotherValue = models.CharField(max_length=5) class C(AbstractModel): anotherValue = models.CharField(max_length=5) class D(AbstractModel): anotherValue = models.CharField(max_length=5) class E(AbstractModel): anotherValue = models.CharField(max_length=5) With this layout, I need the most efficient way to query all objects from models A, B, C, D and E with a given id of SomeModel. I know that I cannot execute a query in an abstract model, so right now, what I do is query each model separately like this: A.objects.filter(someModel__id=id) B.objects.filter(someModel__id=id) C.objects.filter(someModel__id=id) D.objects.filter(someModel__id=id) E.objects.filter(someModel__id=id) Obviously this approach is quite slow, because I need to make 5 different queries each time I want to know all those objects. So my question is, is there a way to optimize this kind of query? -
how can i count and show followers in django
models.py class Relation(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rel_from_set', null=True, blank=True) to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rel_to_set', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) -
Fastest way to write binary files on drive
I take the files(images, audios or videos) from a <input type="file"> and save them on a hard drive in a local server, here's the part of code I use: direc = 'C:\\EXAMPLE\\FOLDER\\' for fl in request.FILES.getlist('file'): filetow = open(direc + str(fl), 'wb+') for chunk in fl.chunks(): filetow.write(chunk) filetow.close() Is there a way to make the process of write files on hard drive faster? Thanks in advance. -
Django static image not loading on setting debug=False
How do I load images in debug=False for testing purposes? Below is my code for your reference. <img src="/static/b_icon.png" alt="Brand Icon" width="30" height="30" class="d-inline-block align-text-top"> -
Cannot connect Django pyodbc to ms sql server
this is my first thread here so forgive me if something is wrong. I'm creating a CRM sorta application in Django and trying to connect to a MSSQL database using pyodbc. I manage to connect and Django even created some tables dbo.django_migrations and dbo.django_content_type (which is blank). But when I run I get a lot of errors: Traceback (most recent call last): File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\allauth\account\views.py", line 146, in dispatch return super(LoginView, self).dispatch(request, *args, **kwargs) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\allauth\account\views.py", line 69, in dispatch if request.user.is_authenticated and app_settings.AUTHENTICATED_LOGIN_REDIRECTS: File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\utils\functional.py", line 246, in inner self._setup() File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\utils\functional.py", line 382, in _setup self._wrapped = self._setupfunc() File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\contrib\auth\middleware.py", line 23, in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\contrib\auth\middleware.py", line 11, in get_user request._cached_user = auth.get_user(request) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\contrib\auth\__init__.py", line 177, in get_user user_id = _get_user_session_key(request) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\contrib\auth\__init__.py", line 60, in _get_user_session_key return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 65, in __getitem__ return self._session[key] File "c:\Users\thardt\Documents\Web-Development\employeeweb\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 238, in _get_session self._session_cache = … -
Why does the HTML file render differently through Django and when opened directly?
When I run the below HTML file via Django's render function, I get the following result: Django result However, when I open the HTML file directly by clicking on it, I get the following result: HTML result Why do they render so differently? How should I modify the code such that when I render the HTML file through Django, I can obtain the same result as when I open the HTML file directly?` <!DOCTYPE html> <html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.82.0"> <title>Headers · Bootstrap v5.0</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/headers/"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!-- Favicons --> <link rel="apple-touch-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png"> <link rel="manifest" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/manifest.json"> <link rel="mask-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon.ico"> <meta name="theme-color" content="#7952b3"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/5.0/examples/headers/headers.css" rel="stylesheet"/> </head> <body> <svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <symbol id="bootstrap" viewBox="0 0 118 94"> <title>Bootstrap</title> <path fill-rule="evenodd" clip-rule="evenodd" d="M24.509 0c-6.733 0-11.715 … -
Arranging data from django model in chartsJS
I have a chartsJS chart that takes numbers from a django model and uses the values to populate the chart. Is it possible to perform data organisation that will organise the values from highest to lowest in the data section of chartsjs: datasets: [{ axis: 'y', label: false, data: [ {% for number in numbers_in_sModel %} {{number.L1_Full_Sum}}, {{number.L2_Full_Sum}}, {{number.L3_Full_Sum}}, {{number.L4_Full_Sum}}, {{number.L5_Full_Sum}}, {{number.L6_Full_Sum}}, {{number.L7_Full_Sum}}, {{number.L8_Full_Sum}}, {{number.L9_Full_Sum}}, {{number.L10_Full_Sum}}, {% endfor %} ],