Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django I cannot retrieve the selected value from database its a dropdown in status field also cant retrieve the selected file in upload cv
this is my edit.html code I want to retrieve the selected value from database in status field its a dropdown also I have Upload cv which is a file field I want to retrieve the selected file too how can I do that I am not getting any solution <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="noticeperiod">Notice Period (in … -
override django-allauth custom create user
I'm using allauth for social authentication with custom user model where i don't have username field and the email field is also not required.(as I'm using phone as username). process goes fine till allauth want to create the user here i face django.db.utils.IntegrityError: UNIQUE constraint failed: user_user.phone so trying to override the default allauth create user method. I have no idea here all i know is from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): # sticks here any idea ? :( -
Difficulty Customizing the body bgcolor in app template; tried moving app name over django admin app of INSTALLED APPS, overriding bootstrap
Necessary updates in settings.py INSTALLED_APPS = [ 'store.apps.StoreConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] main.html file <!DOCTYPE html> <html lang="en"> {% load static %} <head> <title>Ecom</title> <meta charset="UTF-8"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>main</h2> (% block content %} {% endblock %} </body> CSS file main.css body { background: #FF0000; } also tried using !important (despite knowing it isn't a good practice) The template I was trying to render, store.html {% extends 'store/main.html' %} {% load static %} {% block content %} <h1>color</h1> {% endblock %} page preview enter image description here The file directories, src -static -css -main.css -store -templates -store -main.html -store.html The problem is I cannot preview the customized background color of the body. Is the problem due to bootstrap, or my customized css attributes? Or is it the {% extend ...} is not working, or am I missing to add something in the settings.py. Just started learning Django, would be of great help if anyone make me clear the bug. -
Using Django JSONField in model
I am creating REST API's. django==3.2.2 djangorestframework==3.12.4 psycopg2==2.8.6 I am new to Django, python. I looking for a way to use the JSON field in the Django model. My model looks like below - class Question(BaseModel): .... other code... attributes = models.JSONField() Now I want the attributes to be a JSON, like below { "index": 0, "guid": "95161b18-75a8-46bf-bb1f-6d1e16e3d60b", "isActive": false, "latitude": -25.191983, "longitude": -123.930584, "tags": [ "esse", "sunt", "quis" ], "friends": [ { "id": 0, "name": "Contreras Weeks" }, { "id": 1, "name": "Dawn Lott" } ] } Should I create a new model, but creating a new model will make it add to migrations which I do not want. How to create a model for the above? -
Backend developer test
I received a backend developer test and I kind of don't know how to approach it. Can anyone give me some input. Please don't solve it just guide me a little bit. Can be done in any programming language Please implement a basic web server and meet the following requirements: • Each IP can only accept 60 requests per minute. • Display the current request amount on the homepage, and display "Error" if it exceeds the limit, for example, the 30th request in one minute 30 is displayed, and Error is displayed for the 61st request. • You can use any database, or you can design your own in-memory data structure, and explain the reason in the file. • Please attach the test. Thanks -
django rest : @api_view and @classmethod error
🚨 I desperately need @classmethod i am use this code: from rest_framework.response import Response class MyClass(): @classmethod @api_view(['GET', 'POST', 'PUT', 'DELETE']) def CRUD(cls, request, id=0): #..... return Response({}) urlpatterns = [ re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', UserView.CRUD) ] get error: The 'request' argument must be an instance of 'django.http.HttpRequest', not 'builtins.type'. please help ; Thankful🙏🏻🙏🏻 -
How to Specify Django Database Schema?
I have 2 django projects that i want to use the same Postgres database, separated on different schemas. The way I've seen recommended to do this is by setting search_path in options & creating the schema in postgres (CREATE SCHEMA exampleschema). But, it doesn't seem to work. If I specify the search_path as "public" (the default), it can connect to that schema no problem. But when I try exampleschema & run migrate, I get the error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in the database settings look like this - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=exampleschema' }, 'NAME': 'example', 'USER': 'postgres', 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': 'db', 'PORT': '5432', }, } is there a permissions setting that I need to set for the schema in Postgres or something? -
DRF API schema TypeError: view() missing 1 required positional argument: 'request'
I was going through the docs on DRF schema and installed the packages pyyaml and uritemplate. I added the urls to my urls.py file. Later I pip installed coreapi following this tutorial url = [ ... path('docs/', include_docs_urls(title='BlogAPI')), path('openapi', get_schema_view( title="Your Project", description="API for all things …", version="1.0.0" ), name='openapi-schema'), I shows me the following error on login to the url Environment: Request Method: GET Request URL: http://127.0.0.1:8000/docs/ Django Version: 3.1.6 Python Version: 3.9.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'GisApplication.apps.GisapplicationConfig', 'users.apps.UsersConfig', 'crispy_forms', 'rest_framework', 'storages', 'django.contrib.gis'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\schemas\views.py", line 48, in handle_exception return super().handle_exception(exc) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\schemas\views.py", line 37, in get schema = self.schema_generator.get_schema(request, self.public) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\schemas\coreapi.py", line 156, in get_schema … -
when passed a dictionary into jinja2 template single apostrophe(') is converted into "'"
JavaScript is throwing an error 'Uncaught Syntax Error: Unexpected token '&'' when debugged in Views.py I got he data with proper Apostrophes. def newEntry(request): assert isinstance(request, HttpRequest) i = 1 for x in lines: for line in x: cursor.execute("select distinct regionn FROM [XYZ].[dbo].[Errors] where [Linne] like '%" +line+ "%'") region[i] = cursor.fetchall() i = i+1 return render( request, 'app/newEntry.html', { 'title': 'New Entry', 'year':datetime.now().year, 'lines': lines, 'regions': region, } ) and here is my JS code var Regions= {{regions}} function changecat(value) { if (value.length == 0) document.getElementById("category").innerHTML = "<option>default option here</option>"; else { var catOptions = ""; for (categoryId in Regions[value]) { catOptions += "<option>" + categoryId+ "</option>"; } document.getElementById("category").innerHTML = catOptions; } } Thanks in advance, if this is not a best practice to carry data, suggest me some best process which fills my requirement -
Showing all the users who have set their country same as request.user
I am building a BlogApp and I am trying to show all the users which set their Countries similar to request.user. For Example : If user_1 is request.user and selected state choice Victoria and country Australia and then user_2 registered and set the same state Victoria and country Australia. So i want to show all the users that have set their Country and state same to request.user BUT When i access these types of users then It is just showing all users of same country BUT it is not showing of same state. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) country = models.CharField(max_length=30,null=True,blank=True) state = models.CharField(max_length=30,null=True,blank=True) views.py def show_user(request.user): show = Profile.objects.filter(country=request.user.profile) show_state = Profile.objects.filter(state=request.user.profile) context = {'show':show,'show_state':show_state} return render(request, 'show_user.html', context) When i try to access {{ show }} in template then it shows two user have set their country same to request.user BUT When i try to access {{ show_state }} in template it shows nothing. I have no idea, what am i doing wrong in accessing. Any help would be Appreciated. Thank You in Advance. Note :- I am using external library to show country and state choices in html. -
Celery task is not getting updated db records from Django-Channels
In my celery task I want to send an event to a Django-Channels group. The event should save the all the results to the database. The task has a success signal that gets the results and sends it to the group. This does not seem to work though... Why? #consumers.py @database_sync_to_async def save_to_db(game) Result.objects.create(game=game) class GameConsumer(AsyncWebsocketConsumer): ... async def save_result(self, event): await save_to_db(self.game) #tasks.py @shared_task(name="run_game") def run_game(): ... async_to_sync(channel_layer.group_send)( 'game', { 'type': 'save.result' } ) return(game) @task_success.connect def task_success_handler(sender=run_game, result=None, **kwargs): game_results = Game.objects.get(id=result.id).results.all() async_to_sync(channel_layer.group_send)( 'game', { 'type': 'end.game', 'data': game_results } -
NoReverseMatch at /student/test/ Reverse for 'single_quiz' with arguments '('',)' not found. 1 pattern(s) tried: ['quiz/(?P<quiz_id>[0-9]+)/$']
revere match error occurred when passing id. but works fine when added manually.it shows NoReverseMatch error. I am unable to figure out where this is coming from. Should I add the traceback too ? template <div style="padding: 100px 270px;"> {% for a in applied%} {{a.job.quiz.id}} <a href="{% url 'single_quiz' a.job.quiz.id %}">{{a.job.quiz}}</a> {%endfor%} </div> views.py def single_quiz(request, quiz_id): print(quiz_id) quiz = get_object_or_404(Quiz, pk=quiz_id) print(quiz) num_questions = len(quiz.question_set.all()) try: unique = Result.objects.get(user=request.user,quiz=quiz) except Result.DoesNotExist: unique = False # deletes quiz and returns to home if no questions created if num_questions == 0: quiz.delete() all_quiz_list = Quiz.objects.all() context = { 'all_quiz_list': all_quiz_list, } return render(request, 'quiz/index.html', context) quiz.num_questions = num_questions quiz.save() # resets accuracy info to 0 request.session["num_correct"] = 0 request.session["num_wrong"] = 0 context = { 'quiz': quiz, 'num_questions': num_questions, 'unique': unique, } return render(request, 'quiz/single_quiz.html', context) urls.py path('<int:quiz_id>/', views.single_quiz, name='single_quiz'), -
How to fetch Form data in django using cloud firestore?
[] ID is been selected but I'm not getting the values in the form, please check my code files. See in the picture in URL of the browser, update/id is selected, the problem is values are not fetched in the form. HTML: <form id="task-form" name="myForm"> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-building" placeholder="Building name" name="building" value="{{buildings.building}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-postal" placeholder="Postal Code" name="postalCode" value="{{buildings.postalCode}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-town" placeholder="town" name="town" value="{{buildings.town}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-street" placeholder="Street" name="street" value="{{buildings.street}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-house" placeholder="House No." name="houseNo" value="{{buildings.houseNo}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-info" placeholder="Additional Information" name="additionalInfo" value="{{buildings.additionalInfo}}"> </div> </div> </div> <div class="text-center mt-3"> <button type="submit" id="btn-task-form" class="btn btn-primary ">UPDATE</button> </div> </form> views.py def update_Building(request, id): docId = id; context = { 'buildings': db.collection('Buildings').document(docId).get() } return render(request,"EmployeeAdmin/updateBuilding.html", context) urls.py path('update/<str:id>/',views.update_Building,name='update_Building'), -
What is acceptable speed of Django JSON search on Postgres DB [closed]
Using a JSON field that I need to search through every field I use this: queries = [Q(**{'field_data__' + f['name'] + '__icontains': search}) for f in model.fields] qs = None for query in queries: qs = query if qs is None else qs | query for 1 million items with 4 fields a search on a random string takes about 1-2 seconds. Insert of 0.5 million items takes about 10-20 seconds using bulk insert. Is that acceptable or is this way to slow. The Postgres database and Django run on the same machine i5 7500T which I think is an avarage modern CPU... I am just wondering if the order of magnitude is about right, I am not looking for the absolute highest speeds... -
Using the URLconf defined in Webwork.urls, Django tried these URL patterns, in this order: The empty path didn’t match any of these
I am getting this error can anyone help me Request Method: GET Using the URLconf defined in Webwork.urls, Django tried these URL patterns, in this order: admin/ ^ ^department/$ ^ ^department/([0-9]+)$ ^ ^employee/$ ^ ^employee/([0-9]+)$ The empty path didn’t match any of these. here is my code: from django.contrib import admin from django.urls import path from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), url(r'^',include('EmpApp.urls')) ] and from django.conf.urls import url from EmpApp import views urlpatterns=[ url(r'^department/$',views.departmentApi), url(r'^department/([0-9]+)$',views.departmentApi), url(r'^employee/$',views.employeeApi), url(r'^employee/([0-9]+)$',views.employeeApi), ] -
Django-Using distinct on a specific field with annotate
I have following models: class Post(models.Model): title = models.CharField(max_length=30) class PostView(models.Model): post = models.ForeignKey(Post, related_name='views', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), related_name='my_views') created = models.DateTimeField(auto_now_add=True) I want to get posts ordered by number of unique views. I get the posts ordered by views by following code: filters = { 'created__date__gte': datetime.datetime(year=2020, month=1, day=1), 'created__date__lte': datetime.datetime(year=2021, month=1, day=1), } qs = Post.objects.all().annotate( total_views=Count('views', filter=Q(**filters)) ).order_by('-total_views') above code will calculate all views as total_views. I want to get unique views by user. Is it possible to do that with ORM? -
Django getting percentage filtering the object
So I have this two models: class Freguesia(models.Model): nome = models.CharField("Freguesia",max_length=255) class Intervencao(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE, verbose_name="Freguesia") ......... And I want to display in html the top 6 freguesias with more intervecao and the percentage they have in total I already can display the freguesias and the number of intervencoes they have , but I don't know how to display the percentage. My View: def DashboardView(request): freguesias = Freguesia.objects.annotate(num_intervencao=Count('intervencao')).order_by('-num_intervencao')[:6] context = { 'freguesias':freguesias } -
Using crispy forms in HTML's select form field
I am Building a BlogApp and I am trying to style HTML select field in django. edit.html class Edit(forms.ModelForm): class Meta: model = Models fields = ('field1','field2','field3') edit.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <div class="card-body text-center"> <select name="field1" class="div1" id="field1Id"> <option value="">Select 1</option> </select> <select name="field2" class="div2" id="field2Id"> <option value="">Select 2</option> </select> <select name="field3" class="div3" id="field3Id"> <option value="">Select 3</option> </select> </div> </table> <button type="submit">Save Changes</button> </form> What have i tried :- I know that i can do it with {{ form.field1|as_crispy_field }} BUT i am using some externel library in all of these three fields, AND i cannot access there ids with {{ form.field1 }}, So i will use <select name="field3" class="div3" id="field3Id">. I have no idea , how can i style them. Any help would be Appreciated. Thank You in Advance. -
Django session | Light & Dark Theme
I have a question about the Django sessions, I've been looking at it for a few days and I want to make a light and dark theme on my website, but I do not want to create users, so I use the Django sessions, then I want to have a button on the main page that by default is and if you press it is I have tried several ways, I had thought to create a variable (true or false) in a HTML button that passes it to the view, and from there to know the user session to save if it is true or false. So that it does not have to be changing between dark and light theme. Thanks. -
Django Testing sycopg2.errors.DependentObjectsStillExist: cannot drop
I am working on Django project with Django 3.2 and I am using PostgreSQL as my database backend. When I am trying to run tests in the python side I am getting an error regarding foreign key constraints. psycopg2.errors.DependentObjectsStillExist: cannot drop constraint activities_activitytype_pkey on table activities_activitytype because other objects depend on it DETAIL: constraint activities_activity_activityType_id_9dd5265d_fk_activitie on table activities_activity depends on index activities_activitytype_pkey HINT: Use DROP ... CASCADE to drop the dependent objects too. That would have made sense to me but the thing is that I even made sure to drop the complete test database through pg_admin before proceeding to run the tests. What do I miss ? Thanks -
"'Connection aborted.', RemoteDisconnected" or not getting any info with urllib3 and Django
I am developing a web scraping application with BeautifulSoup and Django and I am experiencing some 'conexion issues' (I think). The app has to check if any website is satisfying all the SEO requirements, and for that I have to make different 'requests'... first to get the "soup" and then to check if the robots.txt and sitemap.xml, for example, exists... so I guess some sites are blocking my app because of that, and I am keep getting the "'Connection aborted.', RemoteDisconnected" error or in another cases, I don't get the error but the "soup" is empty... is there a way to fix this? I have tried with time.sleep() but doesn't seem to work... This is part of my code: http = PoolManager() r = http.request('GET', "https://" + url, headers={'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36", 'Accept-Encoding': 'br'}) soup = BeautifulSoup(r.data, 'lxml') And where I check if robots and sitemap exists: robots_url = url + "/robots.txt" robot = requests.get(robots_url, headers) if robot.ok: robot = True else: robot = False sleep(5) sitemap_url = url + '/sitemap.xml' sitemap = requests.get(sitemap_url, headers=headers) if sitemap.ok: sitemap = True else: sitemap = False In most of websites the code is working fine … -
HttpResponseRedirect doesn't change url [closed]
HttpResponseRedirect doesn't change the url for me. I can see from the logs that it calls the view which I want to redirect the user to but it never changes the url & sends the user to the other page In my javascript code inside video.html, I send the user to exit view to do some computation video.html navigator.sendBeacon("{% url 'exit' %}", data); def exitView(request): if request.method == 'POST': print("post request inside exit") return HttpResponseRedirect('/') def mainView(request): if request.method == 'GET': print("get request inside mainView") return render(request, 'index.html') My logs look like this post request inside exit get request inside mainView So HttpResponseRedirect does redirect the view from exitView to mainView. However, in the frontend, the user continues to be on main-site/video What I want to do is send the user from main-site/video to main-site/exit & then redirect to main-site/ However, the user continues to stay on the urlpatterns = [ path('admin/', admin.site.urls), path('video/', videoView), path("", mainView, name='index'), path("exit/", exitView, name='exit'), path("accounts/", include('allauth.urls')), ] -
Django Updating Tables
Basically I have an Account table that keeps track of a users balance and then I have a Transaction table that keeps track of all transactions (for all users). When I save data to my Account table 'user: 12' 'type: deposit' 'description: Venmo inc' 'amount: 200.00' I want to update the users current account balance from 'user: 12' balance: 200 to 'user: 12' 'balance: 400.00' The code below works fine: @receiver(post_save, sender=Transaction) def update_account(sender, instance, created, **kwargs): if created: user = instance.user amount = instance.amount a = Account.objects.get(user=user) new_balance = amount + a.balance a.balance = new_balance a.save() But could I also do this? Is this good practice? @receiver(post_save, sender=Transaction) def update_account(sender, instance, created, **kwargs): if created: a = Account.objects.get(user=instance.user) a.balance = instance.amount + a.balance a.save() -
How to redirect a form to a tab (panel)?
I created several tabs with bootstrap in my Django project. I have a form in my second tab (pills-approval-tab). What I want is when a user fills the form, it should redirect the page to the same second tab (pills-approval-tab). I have just 2 tabs. How can I do that? views.py if request.method == 'POST' and request.POST.get('form') == 'risk': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): this_pdf = form.save() ... redirect('????') else: form = PdfRiskForm() ocr.html ... <div class="card-body"> <ul class="nav nav-pills nav-primary" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-ftables-tab" data-toggle="pill" href="#pills-ftables" role="tab" aria-controls="pills-ftables" aria-selected="true">Financial Tables</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-approval-tab" data-toggle="pill" href="#pills-approval" role="tab" aria-controls="pills-approval" aria-selected="false">Approval</a> </li> </ul> <div class="tab-content mt-2 mb-3" id="pills-tabContent"> {% include './financial_tables_tab.html' %} {% include './approval_tab.html' %} </div> approval_tab.html <div class="tab-pane fade" id="pills-approval" role="tabpanel" aria-labelledby="pills-approval-tab"> ... </div> -
DataTables in Django modify columns ordering
I write Django app, where I have a base.html template and I defined var table where I declared order by column 0 with 'desc' (look below) So I currently use it some templates, where I extend base.html. But now I need to sort in new template firstly by the second column, and after that by the first column (like this: "order": [1, 0, 'desc'] ). I don't know how I modify this variable without a duplicate code. Could somebody help me? var table = $('#example').dataTable( { "columnDefs": [ { "targets": 0, "searchable": false, "order": [0, 'desc'], "ordering": true, } ] } );