Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to format labels and form boxes when using django_filter
Very new here to django/python. I have a web page that makes use of django_filters for filtering a product view by category, and then orders them by price. I am not sure how to actually format the output in the template. Any help is appreciated: views.py class HomeView(ListView): model = Post #indicating which model to use from models.py template_name = 'home.html' #specify which html file to use as the template context_object_name = 'all_posts_list' #Default: object_list ordering = ['price'] #reorder by price paginate_by = 16 #queryset = Post.objects.all() #Default: Model.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = PostFilter(self.request.GET, queryset=self.get_queryset()) return context filters.py class PostFilter(django_filters.FilterSet): CHOICES = ( ('highToLow', 'Highest-to-Lowest'), ('lowToHigh', 'Lowest-to-Highest'), ) ordering = django_filters.ChoiceFilter(label='Price', choices=CHOICES, method='filter_by_order') class Meta: model = Post fields = ['category'] def filter_by_order(self, queryset, name, value): expression = 'price' if value == 'highToLow' else '-price' return queryset.order_by(expression) html template {% load bootstrap %} {% block menubar %} <form class="form-inline" method="GET" style="color: white; font-weight: bold;"> {{ filter.form|bootstrap }} &nbsp;&nbsp;<button type="submit" class="btn btn-warning">Go</button> </form> {% endblock %} template output I am not sure how to actually format the labels and dropdowns being produced by the filter.form, other than adding the bootstrap |, which still does not help with … -
Forbidden (CSRF token missing or incorrect.) | Django and AJAX
:( I am making ajax requests, but I get this error: Forbidden (CSRF token missing or incorrect.): /manager/ajax/ [23/Jun/2020 00:00:46] "POST /manager/ajax/ HTTP/1.1" 403 2517 [23/Jun/2020 00:01:18] "GET /manager/test/update/3/ HTTP/1.1" 200 10249 Forbidden (CSRF token missing or incorrect.): /manager/ajax/ [23/Jun/2020 00:01:18] "POST /manager/ajax/ HTTP/1.1" 403 2517 [23/Jun/2020 00:01:22] "GET /manager/test/update/3/ HTTP/1.1" 200 10249 Forbidden (CSRF token missing or incorrect.): /manager/ajax/ [23/Jun/2020 00:01:23] "POST /manager/ajax/ HTTP/1.1" 403 2517 JS: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); fetch('/manager/ajax/', { method: 'POST', body: JSON.stringify({ csrfmiddlewaretoken: csrftoken, title: 'hello!!!! :(', }), headers: { "Content-Type": "application/x-www-form-urlencoded" } }) .then(response => response.json()) .then(json => console.log(json)) My view: def delete_exam_question(request): print(request.method) if request.is_ajax: print(request.POST) #exam_question = ExamQuestion.objects.get(title = request.POST.get('title')) #exam_question.delete() return JsonResponse({'deleted': True}) I tried to fix it like in this question ("application/x-www-form-urlencoded"), I already tried indicating "application/json", but it does not work... :( I … -
How to use python schedule on a Django application
I'm new to Django and web frameworks in general. I have an app that is all set up and works perfectly fine on my localhost. The program uses Twitter's API to gather a bunch of tweets and display them to the user. The only problem is I need my python program that gets the tweets to be run in the background every-so-often. This is where using the schedule module would make sense, but once I start the local server it never runs the schedule functions. I tried reading up on cronjobs and just can't seem to get it to work. How can I get Django to run a specific python file periodically? -
Add search for all models in django admin
I am using Django 2.2.23.In django admin i want search for all models. I know it can be done using ModelAdmin in admin.py. However the no of models is large(approx 50) and it is tedious task to add the class for every model. Is there a way to add search globally in django admin. -
How to Update Django Model Object Field?
So basically I'm scraping using BeautifulSoup and placing the data into a Model. I have a loop that creates objects that don't already exist and if they do then don't create anymore. for obj in objs: title = obj.find(class_='result-title').text url = obj.find('a').get('href') if obj.find(class_='result-price'): price = obj.find(class_='result-price').text else: price = 'N/A' image_url = 'https://pixelz.cc/wp-content/uploads/2019/02/bugatti-chiron-sport-110-ans-uhd-4k-wallpaper.jpg' if models.Product.objects.filter(Name=title, Price=price, Link=url, Image=image_url): continue else: models.Product.objects.create(Name=title, Price=price, Link=url, Image=image_url) My question is say if I decided to change the image_url in the future, how could I write a loop that basically checks if the Image field of the model object is equal to the image_url and if its not then update the Image field to the current value of image_url. if models.Product.objects.filter(Name=title, Price=price, Link=url, Image=image_url): if models.Product.objects.filter(Image=image_url) != image_url: models.Product.objects.filter(Image=image_url).update(Image=image_url) else: continue else: models.Product.objects.create(Name=title, Price=price, Link=url, Image=image_url) I made this loop and it works but the only issue it has is that it creates new model objects instead of updating the existing object fields. How could I modify this loop to check if the current Object Image field is equal to image_url and if it isn't then update the object image field instead of creating a brand new model object. Thank You. -
Trying to create infinate scroll gallery
I'm trying to follow this tutorial https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html to create an infinite scroll gallery. In the guide they use a class based view but I have a function based view. Other than that I believe I've done everything the same however it's still rendering all images at once. views.py def model_images_view(request): paginate_by = 5 context = { "images": Image.objects.all(), } return render(request=request, template_name="models/images.html", context=context) template.html {% load static %} <script src="{% static 'js/noframework.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> <div class="col-12"> <div class="card"> <div class="card-header card-header-success"> All Images </div> <div class="card-body infinite-container"> <table class="table"> <tbody> {% for image in images %} <tr class="infinite-item"> <td><img src="{{image.image.url}}" class="model-image-preview"></td> <td class="td-actions text-right"> <form method="POST" action="{% url 'models:delete_image_view' image.pk %}"> {% csrf_token %} <button type="submit" rel="tooltip" title="Remove" class="btn btn-white btn-link btn-sm"> <i class="material-icons">close</i> </button> </form> </td> </tr> {% endfor %} <div class="loading" style="display: none;"> Loading... </div> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ images.next_page_number }}">More</a> {% endif %} </tbody> </table> </div> </div> </div> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> -
Python Social Auth Django installation failure
I am trying to install Python Social Auth for Django, but it is not succesful. Server OS: Ubuntu 14.04.5 LTS (GNU/Linux 2.6.32-042stab141.3 x86_64) Python version: 3.4.3 Django version (if it matters): 2.0.8 I use pip install social-auth-app-django, and the installation is starting, but after a while I get some errors. ... Building wheels for collected packages: cffi Building wheel for cffi (setup.py) ... error ERROR: Complete output from command /home/ks/priroda-venv/bin/python3.4 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-7c3p58ht/cffi/setup. py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replac e('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec '"'"'))' bdist_wheel -d /tmp/pip-wheel-an_3ux86 --python-tag cp34: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.4 creating build/lib.linux-x86_64-3.4/cffi copying cffi/recompiler.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/commontypes.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/api.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/vengine_gen.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/model.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/error.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/ffiplatform.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/verifier.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/pkgconfig.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/lock.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/__init__.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/cparser.py -> build/lib.linux-x86_64-3.4/cffi copying cffi/_cffi_include.h -> build/lib.linux-x86_64-3.4/cffi copying cffi/parse_c_type.h -> build/lib.linux-x86_64-3.4/cffi copying cffi/_embedding.h -> build/lib.linux-x86_64-3.4/cffi copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-3.4/cffi running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-3.4 creating build/temp.linux-x86_64-3.4/c x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototype s -g … -
task receive but doesn't excute
I'm learning Django. recently I tried to use celery. the problem that I'm facing with it is tasks are receiving but they don't execute. settings.py: # Celery application definition CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Tehran' celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf.settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py: from celery import task, shared_task from django.core.mail import send_mail from .models import Order import logging # Get an instance of a logger logger = logging.getLogger(__name__) @shared_task() def order_created(order_id): logger.error('msg received') """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) order = Order.objects.get(id=order_id) subject = f'Order nr. {order.id}' message = f'Dear {order.first_name},\n\n' \ f'You have successfully placed an order.' \ f'Your order ID is {order.id}.' mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email]) logger.error('mail sent') return mail_sent running task in views.py: # launch asynchronous task logger.error('before task') order_created.delay(order.id) logger.error('after task') cmd log after running celery with celery -A myshop worker -l info: (venv) E:\Workspace\django-shop\myshop>celery -A myshop worker -l info -------------- celery@DESKTOP-F7E0RGJ … -
Installing Django and modules in virtual environment
My question is do i have to install django every single time in my virtual environment in order to run my python files? and is this taking up bunch of space on my machine? My project also uses "matplotlib" and every virtual environment i create it also asks me to import the matplotlib module too. its getting annoying. do i have to do this every time? Im new to Django. I wanted to run some python files in django but they weren't working, so after some research i found out i needed to run my pycharm project in a virtual environment in order to run these python files. my folders look like this pycharmProjects -> my project I enter pycharmProjects and I set up virtual environment using "pienv shell". Then i run "python3 manage.py runserver". It turns out i must install django in the virtual environment before the files run. -
Sending data from views py to ajax
I am sending some data from html template to views.py via ajax.From the id sent to views.py I am creating sql records. However I was wondering if there is any way to send data from views.py to template to notify that the data is added to sql. code- $('#tn1').click(function(){ var msg=''; alert('inside alert'); if ($('textarea#message') != "") { var message = $('#notesarea').val(); alert(message); msg=message; } $.ajax({ url: 'post_note', data: { 'note': msg }, success: function (data) { alert(data) } }); views.py ` def post_note(request,id): post_id = request.GET['note'] print(post_id) //sql insertion code,once its done i want to notify to the front end..print some alert message. return render(request, './profile.html') -
How to refresh a datetime tag every second in a Django?
I use Django 3 + Bootstrap 4 + MySQL 5.7 on a Laragon server, all on Windows 10. I have a view with a variable dt_now = timezone.now() displayed in a Template with a simple <p>{{ dt_now }}</p> tag. I want to refresh this tag every second automatically without reloading all the htlm page. Is there a simple way to do that with Django or Bootstrap ? Or maybe should I prefer to use a jQuery methode ? At last, should I write a custom function ? -
passing variable from JavaScript to Django view
** I'm having a variable in Javascript which is needed to send in Django view.py to perform some operations. Is there any way I can send that variable to Django View? ** -
how to make an HTML table in mulitple page follow the page margin
I have an HTML table that can extend according to the elements inside an array. This array is provided by django rest framework and vue will add the rows to the table to represent the data. I got an issue that sometimes there are too many elements to fit on a letter size page to print and more pages are needed. When the table extends it doesn't follow the page's top and bottom margins. Since the height of the rows are determined by its content I cant predict which row will be the one that splits at the bottom of the page. So my doubt is: Is there a css property/something I can use in order for the table to not go into the bottom and top page margins? -
Django s3direct + TinyMCE
I'm successfully using s3-direct and django-tinymce in several user-facing Django projects (not just the admin). I'd like to add file uploading functionality. In the docs, django-tinymce says you can use django-filebrowser to add upload functionality https://django-tinymce.readthedocs.io/en/latest/installation.html. But will django-filebrowser work with s3-direct? A lot of the advice around this is several years old (and using old versions of Django/packages). Has anyone done this recently, or have best practices here? Should I replace s3-direct (which I'm using for all my user file uploading at this point) -
Django save a file from an html form file field
in my django project i create my models like thisone: class v_candidatura(models.Model): c_data = models.DateTimeField(auto_now=True, verbose_name="Upload") c_tit = models.CharField(max_length=5, verbose_name="Titolo") c_sur = models.CharField(max_length=100, verbose_name="Cognome") c_name = models.CharField(max_length=100, verbose_name="Nome") c_dob = models.CharField(max_length=50, verbose_name="Data di nascita") c_res = models.CharField(max_length=200, verbose_name="Residenza") c_email = models.CharField(max_length=100, verbose_name="Email") c_mansione = models.CharField(max_length=50, verbose_name="Mansione") c_en = models.CharField(max_length=50, verbose_name="Conoscenza EN") c_de = models.CharField(max_length=50, verbose_name="Conoscenza DE") c_pres = models.TextField(null=True, blank=True, verbose_name="Presentazione") c_cv = models.FileField(upload_to='villagemma/static/docs', max_length=254, validators=[FileExtensionValidator(['pdf']),validate_fsize], verbose_name="CV") class Meta: verbose_name = "Candidature" verbose_name_plural = "Candidature" def __str__(self): return str(self.c_sur) whell i have a long html for with a file field for upload file: ... <input type="file" class="form-control input_login custom-file-input" id="inputCv" name="inputCv"> ... in my view.py i would save data and file in my table so i do: if request.method == "POST": #try to save data into db a = v_candidatura(c_tit = request.POST['inputTitolo'], c_sur = request.POST['inputCognome'], c_name = request.POST['inputNome'], c_dob = request.POST['inputDtNascita'], c_res = request.POST['inputComune'], c_email = request.POST['inputEmail'], c_mansione = request.POST['inputMansione'], c_en = request.POST['inputEN'], c_de = request.POST['inputDE'], c_pres = request.POST['inputPresentazione'], c_cv = request.POST['inputCv'] ) a.save() but i get multidictate error on inputCv value. How can i save my form data into table and also file uploaded from form? So many thanks in advance -
Should I disable BroswableAPIRenderer for production environment?
Hi Guys I am deploying a django project to elastic-beanstalk on AWS it currently is working fine, however I would like to know if it's a good or bad practice to allow the BrowsableAPIRenderer to be able to handle requests on my browser, I try to find anything related to it but there is really not too much documentation if not any at all. My App has a really strict permission policy, even when I access through the browsable API, it returns the following: { "detail": "Authentication credentials were not provided." } however it displays some sort of "information" about the endpoint. It's in that part where I find it difficult to define if I should allow it so that other developers can easily know what is going on, or on the other hand if it is a big risk to be accessible to the public. -
Rel.to deprecated in Django 2.0
I am trying to upgrade the django-accounting (https://github.com/dulacp/django-accounting) to the last version of django as I would like to use it in my app. One item, I am trying to resolve that has been deprecated in django 2.0, is rel.to. [https://github.com/dulacp/django-accounting/blob/master/accounting/apps/books/mixins.py][1] Line 44: field, m, direct, m2m = model._meta.get_field_by_name(source) has now been replaced by field = model._meta.get_field(source) Line 45: rel = field.rel if not rel: # next field continue rel_model = rel.to try: rel_model._meta.get_field_by_name(self.relation_name) has now been replaced by: rel = field.remote_field if not rel: # next field continue remote_field = rel.to try: remote_field.model._meta.get_field_by_name(self.relation_name) I have an error ManyToOneRel' object has no attribute 'to'. It will probably bring me to the next field to modify but if anybody got an idea how to resolve this, it could be great. Thanks -
Use HTML dropdown to change which variable loads in django template
I am currently creating a pretty basic application using python django. Currently I have a context that looks like this: {'sheets': ['StockSummary(2)', 'StockSummary', 'Coverpage', 'Black-listedcountries', 'listingRCT', 'Longestlines'], 'StockSummary(2)': 'test1', 'StockSummary': 'test2', 'Coverpage': 'test3', 'Black-listedcountries': 'test4', 'listingRCT': 'test5', 'Longestlines': 'test6'}} The first part 'sheets, is being used to create a dropdown list. When the drop down is changed I would like the associated string from the context to be loaded. I have tried using string methods in a javascript function, like below, to load the variable: function Loader(Val){ var holder = document.getElementById('dataframe') holder.innerHTML = '{{'.concat(Val,'}}') } In the above picture 'Val' is the value sent from the dropdown list. Unfortunately django doesn't render this how I would want. Does anyone have any idea on how to do this? Thanks, James -
How to add placeholder to forms.widgets.DateInput with attrs={'type': 'date',} in Django?
I cannot add a placeholder to DateInput widget inside a form if I pass 'type': 'date' to attrs. However, if I don't pass 'type': 'date' to attrs the field behaves like a TextInput. It looks super simple but I can't understand what's going wrong. forms.py class QueryClientsForm(forms.Form): initial_date = forms.DateField( widget=forms.widgets.DateInput( attrs={'placeholder': 'Initial date...', 'type': 'date', })) query_clients.html <div class="container h-50"> <div class="row justify-content-center"> <div class="register_card" style="display: inline-block;"> <form method="POST" action=""> {% csrf_token %} <div class="input-group"> {{form.initial_date}} <input class="btn login_btn" type="submit" style="margin-left: 10;" value="SEARCH"> </div> </form> </div> </div> </div> What I've to change? -
TypeError: Field 'maintenance_costs_once' expected a number but got (4,)
I have an array of arrays. Each of the nested arrays contains information about a student. I'm then iterating over it and saving each of the arrays into a student object and persisting that into my DB. students = [ ["James", "Smith", 4, 10], # more students here ] for s in students: student = Student() student.first_name = s[0], student.last_name = s[1], student.classroom = s[2], student.grade1 = s[3], student.save() The field classroom in the Student class is defines as a FloatField. I'm getting following error: TypeError: Field 'classroom' expected a number but got (4,). What can be the cause for this? -
Having trouble displaying image source url in the api's response (Django-Rest-Framework)
I'm currently having an issue using the django-rest-framework. I'm currently developing a website for a contractor and my main goal is to be-able display the past jobs he has completed. I'm using django-rest-framework for my backend and react for my frontend. My main problem is that the api response shows all of the fields except the image field with their corresponding url. My logic behind the code is that the rest-api sends the image urls so that I can then get the urls to display them on my react-app. My model "Project" has all the corresponding fields. I also created another model called "Project Details" that allows the "Project" model take several images that pertain to it. My model code below: # Project Model class Project(models.Model): # Project's Title title = models.CharField(max_length=50) # Project's Address address = models.CharField(max_length=50) # Project's Client client = models.CharField(max_length=50) # Is the Project Commercial? commercial = models.BooleanField(default=False) # Is the Project Residentail? residential = models.BooleanField(default=False) # Is the Project Completed? completed = models.BooleanField(default=False) def __str__(self): return self.title # Project Detail's Model (A.K.A Images) class ProjectDetails(models.Model): # Assign to Project model project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='projects' ) # Image model field image = models.ImageField( upload_to='static/', … -
Django using the wrong Timezone for the data imported from MySQL
I use Django 3 + Bootstrap 4 + MySQL 5.7 on a Laragon server, all on Windows 10. My setting in Django : TIME_ZONE = 'Europe/Paris' My setting in MySQL : TIME_ZONE = SYSTEM (My system is configured with 'Europe/Paris') When I use a timezone.now() in Django, or a CURRENT_TIMESTAMP in MySQL, I have no problem, the right time is displayed. But my data imported from MySQL are displayed wrongly: with a +2 hours error. For what I have read on the subject, the cause can be the absence of data in MySQL time_zone table, on the server. What's your point of view ? Am I on the good track ? I don't want to make a mistake, so I prefer to have a confirmation first. And do you think it's good to keep the setting so in MySQL. Shouldn't I prefer TIME_ZONE = 'Europe/Paris' instead of TIME_ZONE = SYSTEM ? -
How to make trailing / in url optional Django
I have registered my urls in django and noticed that the trailing / is not optional, meaning that if I register like so: path('home', homepage), Then I can't go to home/ How do I allow both? Do I have to register both for each url? Thanks!! -
PDF.JS zoom in pdf viewer
I Am using pdf.js to show in my template, multiples files together, in single view. It works fine. But, now I need to add zoom function on click, but don't know how. I have a working script (without zoom function). <div> <button id="prev">Anterior</button> <button id="next">Siguiente</button> &nbsp; &nbsp; <span>Página: <span id="page_num"></span> / <span id="page_count"></span></span> &nbsp; &nbsp; <button id="zoominbutton" title="Zoom Out" onclick="zoomOut()"> - </button> <button id="zoomIn" title="Zoom In" onclick="zoomIn()"> + </button> <span id="scaleSelectContainer"> <select style="min-width: 142px;" data-style="btn-primary" id="scaleSelect" title="Zoom" tabindex="23" onclick="zoomSelect()"> <option value="0.5">50%</option> <option value="0.75">75%</option> <option value="1">100%</option> <option value="1.25">125%</option> <option value="1.5">150%</option> <option value="2">200%</option> <option value="3">300%</option> <option value="4">400%</option> </select> </span> </div> <div> <canvas id="the-canvas"></canvas> </div> JS (in Django template) var urls = {{ urls|safe }}; var pdfjsLib = window['pdfjs-dist/build/pdf']; pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'; var pdfDocs = [], /** * @property {PageInfo} */ current = {}, totalPageCount = 0, pageNum = 1, pageRendering = false, pageNumPending = null, scale = 1.5, canvas = document.getElementById('the-canvas'), ctx = canvas.getContext('2d'); /** * Get page info from document, resize canvas accordingly, and render page. * @param num Page number. */ function renderPage(num) { pageRendering = true; current = getPageInfo(num); // Using promise to fetch the page pdfDocs[current.documentIndex] .getPage(current.pageNumber).then(function (page) { var viewport = page.getViewport({scale: scale}); canvas.height = viewport.height; canvas.width … -
Searching across multiple indices and serializing multiple document types with django-elasticsearch-dsl-drf
I have the following setup: Django 3.0.7 Elasticsearch 7.7 django-elasticsearch-dsl django-elasticsearch-drf So far I have created 4 different document types and serializers and also 4 different search endpoints. I have not been able to figure out how to create one endpoint for returning serialized search results from all 4 indices. The serialized search results are all slightly different with different custom fields. While the endpoints work fine I am not sure how to handle the search without making 4 requests on the front-end each time a search request is submitted. I would also like the results to be paginated so having 4 endpoints is most likely not going to work. Does anyone have experience with a similar scenario?