Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sending SMS to the user using fast2SMS
I want to send an SMS to the user in the Marathi language but in fast2SMS it is been send in the default language that is English. I have gone through the API Documentation of fast2sms but didn't found the answer to my query. please help how can I send the SMS OTP in marathi .enter image description here querystring = { "authorization":"SqbjiJDXHkYR2An46KOl8ZGexFmdsvWVc0fa3h1PgCIou9NMUTK5XiNwGH7jDVrmP6haAxpSZItyl0f3", "sender_id":"KAMALCLS", "message":"ur password is " +pw, "language":"english", "route":"p", "numbers":str(ph) } res = requests.request("GET",url,params=querystring) -
Importing from excel works with django's inbuilt ImportExportModelAdmin but not through user created import view
I have an excel file with data of employees... The unit name field in the excel sheet is linked to the unit table which is another model. Have included the ForeignKeyWidget in resources.py to look for the unit while importing and it works with django's inbuilt ImportExportModelAdmin. While importing through the user made view it throws following error. ['“A Unit” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
how to connect to postgres13 from spinning up docker-compose from inside ubuntu ec2 instance
I am running a ubuntu 20.04 on AWS ec2 instance and I have the following Dockerfile file configuration for my backend application: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /backend COPY requirements.txt /backend/ RUN pip install -r requirements.txt && \ pip install --upgrade pip COPY . /backend/ COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] docker-compose version: "3.3" services: db: image: postgres:latest container_name: db restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - backend_network backend: build: ./backend container_name: backend stdin_open: true tty: true restart: always env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - backend_network volumes: postgres_data: networks: backend_network: driver: bridge settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("POSTGRES_DB"), "USER": os.environ.get("POSTGRES_USER"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), "HOST": os.environ.get("POSTGRES_HOST"), "PORT": 5432, } } .env file # APP POSTGRES_DB=somedbname POSTGRES_USER=someuser POSTGRES_PASSWORD=somepassword # DATABASE # PUBLIC_DB DB_NAME=somedbname DB_USER=someuser DB_PASSWORD=somepassword DB_HOST=xxxx.yyy.us-east-x.rds.amazonaws.com and when after spinning up my docker compose file with the command docker-compose up -d --build it look like my app cannot connect to rds psql: error: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I am … -
Dictionary items not showing up in template in django
I have gathered data from two tables that is Orders and Purchases (joined) and saved that in dictionary, when I'm printing the qty on the console its giving me the value but when I'm trying to print the values on template it not showing up however columns from the orders table like first name last name status address is shown on the template but qty and product from the purchases table is not showing up on the template but can be easily printed on console can somebody help??? Models.py Dispatcher = models.ForeignKey(Dispatchers , null=True, on_delete=models.SET_NULL ) Firstname = models.CharField(max_length=200 , null=True) Lastname = models.CharField(max_length=200 , null=True) Email = models.CharField(max_length=200 , null=True) Address = models.CharField(max_length=200 , null=True) Country = models.CharField(max_length=200 , null=True) State = models.CharField(max_length=200 , null=True) status = models.CharField(max_length=200 , null=True) def __str__(self): return self.Lastname class purchases(models.Model): orders_id = models.ForeignKey(Orders , null=True, on_delete=models.SET_NULL ) product = models.CharField(max_length=200 , null=True) qty = models.CharField(max_length=200 , null=True) price = models.CharField(max_length=200 , null=True) def __str__(self): return self.product views.py file dispatcherOrders = {} orders = request.user.dispatchers.orders_set.all() for order in orders: dispatcherOrders[order] = purchases.objects.get(orders_id = order.id) print(dispatcherOrders[order].qty) return render(request , 'dispatcherOrders.html',{'dispatcherOrders' : dispatcherOrders}) dispatcherOrders.html {%for Orders in dispatcherOrders%} <tr> <th scope="row">1</th> <td>{{Orders.Firstname}}</td> <td>{{Orders.Lastname}}</td> <td>{{Orders.Address}}</td> <td>{{Orders.product}}</td> <td>{{Orders.qty}}</td> … -
Reverse for 'Page' not found. 'Page' is not a valid view function or pattern name
this is the error I got when I wanted to create a dynamic sitemap. sitemap.py class DynamicSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Page.objects.all() models.py class Page(models.Model): city= models.CharField(max_length=40, verbose_name="Şehir") seo = models.CharField(max_length=50, verbose_name="Seo") def __str__(self): return self.city def get_absolute_url(self): return reverse("Page", args=(self.pk,)) urls.py itemaps = { 'static': StaticViewSitemap, 'dynamic': DynamicSitemap } urlpatterns = [ path('sitemap.xml', sitemap, {"sitemaps":sitemaps}, name="sitemaps") ] static sitemap works fine but dynamic sitemap I get the same error. Thank you to those who are interested so far. I'm sorry for my bad english -
Django python request start point - tracing a request from start to finish
This is with related to django in general. I am trying to debug this weird issue in django 2.2/python 3.7. If i set DEBUG=True, i am getting response for all my urls. But if i set DEBUG=True, all urls are throwing 404. I have tried all the existing django solutions like setting ALLOWED_HOSTS etc. But nothing is working. So just wanted to trace the request from start to finish. For example when we enter the url in browser and hit enter what will django do? Which views and methods will be called till a final response is rendered on screen. -
How to Add Chat Between Users in My Django Web Application?
i developing an simple bloger with django now i need to create chat between users in My site -
restore backup of django models reference each other using pg _restore
Faced a problem while restoring pg_restore data, I have two models in django: class Project(models.Model): previewScreenId = models.ForeignKey("Screen", related_name='project_preview', on_delete=models.SET_NULL, default=None, null=True, blank=True) class Screen(models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE) When restoring data, pg_restore throws an error that the secondary key data is not present in the linked table. Thus, I am stumped and have no idea how I can restore the database. I've tried using arguments like --data-only or -t content_screen, but that doesn't help. pg_restore: while PROCESSING TOC: pg_restore: from TOC entry 3550; 0 17205 TABLE DATA content_screen sergey pg_restore: error: COPY failed for table "content_screen": ERROR: insert or update on table "content_screen" violates foreign key constraint "content_screen_project_id_b836412d_fk_content_project_id" DETAIL: Key (project_id)=(5427) is not present in table "content_project". pg_restore: warning: errors ignored on restore: 1 -
Hiding milliseconds from timezone.now() (In HTML)
I am building a BlogApp and I am implementing a feature of expiring post so the post will hide in 2 days, So I am showing user the remaining time in post. Remaining time is showing perfectly BUT It is also showing milliseconds (which i I am trying to hide) The Output is like :- 2 days, 23:43:33.271449 views.py from django.utils import timezone from datetime import timedelta def blogpost_detail(request,blogpost_id): blog = get_objects_or_404(BlogPost,pk=blogpost_id) remaining_time = blog.blog_date_added - timezone.now() + timedelta(days=2) context = {'remaining_time':remaining_time,'blog':blog} return render(request, 'blogpost_detail.html', context} What i am trying to show as output :- I am trying to show like :- 2 days 23 Hours Remaining What have i tried :- I tried Python/Django timestamp including milliseconds Post's Answer by dividing 1000 but when i divide timezone by 1000 like timezone.now()/1000 then it is keep showing unsupported operand type(s) for /: 'datetime.datetime' and 'int' Then i tried hiding milliseconds from template by using time:"h:i a" like {{ blog|time:"h:i a" }} But it is showing nothing as output. Any help would be much Appreciated. Thank You in Advance -
django: how to update models
I want the update a model in django this is a model in models.py: class Article(models.Model): CATEGOTY = ( ('programming', 'programming'), ('other', 'other') ) title = models.CharField(max_length=100, null=False) content = models.TextField(null=False) category = models.CharField(max_length=100, choices=CATEGOTY, null=False) creation = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title for example i want to add slug in this model like this: slug = models.SlugField(max_length=100, null=False) but when i display py manage.py makemigrations; this is shown to me: Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py what should I enter if I select option 1? if i type datetime.date.today() It gives me an error that says: TypeError: function missing required argument 'year' (pos 1) -
Django Dev Server - sleep(N) in Middleware makes requests sleep multiple N seconds
Working on a middleware that slows down dev server response time. To simplify it I've created a very simple example that measures get_response time and then sleeps so the whole request cycle takes approximately 2 seconds. The problem is that when there are multiple requests sent at once, some of them sleep 2xN time (not just a little bit longer, it's multiplicated). I assume it's because of limits of Django's dev server concurrency. Is it possible to make it work? class SnailMiddleware: """ Middleware that throttle responses """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request: HttpRequest): start = now() response = self.get_response(request) elapsed_time = (now() - start).total_seconds() time.sleep(2 - elapsed_time) return response These are the times: Do you know where is the problem and how to make it work? -
How do you mock an object in a list?
I have the following function: signature_request = client.send_signature_request_embedded_with_template( client_id=self.CLIENT_ID, template_id=self.template_id, title=self.title, subject=self.email_subject, message=self.message, signers=self.signers, custom_fields=self.custom_fields ) signature_id = signature_request.signatures[0].signature_id I cannot for the life of me mock the signature_id value in my test. I know that I am properly mocking the correct target because I am successfully mocking another return value from this signature_request object. Any help would be highly appreciated! I have tried the following: send_request_mocked.return_value.signatures.return_value= [PropertyMock(signature_id='signature_id')] send_request_mocked.return_value.signatures.return_value= [Mock(signature_id='signature_id')] etc. -
Django pythonanywhere JS not running
I've made a tally counter at http://fr0gs.pythonanywhere.com/tools/tally-count I've made buttons and script tags, but interestingly, the button's JS execute and the script tag's doesn't!! -
Create a many-to-many item in-line from a django form
I have to two models Directors and JobProject. A JobProject can have multiple directors through a many-to-many relationship. Currently, when I create a new JobProject I choose from the directors I have saved who the director will be. However, I am trying understand how can I code a form/view for creating a JobProject where I can also create a director in-line (in case I don't have the director already saved in the DB). In the admin there is a way to click on green + and open a pop-up, but the same process might not work for my use-case so I was hoping there was a way to create a form that allow users to: Start entering a JobProject details. If the director already exist in the DB - Great If the director doesn't exist, allow users to enter the details of a new director object (probably using Java?) in-line Users go ahead and finish entering JobProject details. Users click save and the BE first save the new director and then save the new project with director pointing at the newly created director. I basically have 1,2,4,5 figured out but I can't understand how to do 3. Any help? These … -
How to remove all permissions from a user in Django Guardian?
I'm trying to reset my user permissions to assign new objects permissions to my user. how to achieve that ? For Example: having 3 chained models School & Grade & StudentRecord Models.py: class School(models.Model): name = models.CharField(_("Name"),max_length=50) # other fields ... def __str__(self): return self.name class Grade(models.Model): code_name = models.CharField(_("Name"),max_length=50) school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='grades') # other fields ... def __str__(self): return self.code_name class StudentRecord(models.Model): code_name = models.CharField(_("Name"),max_length=50) school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='grades') grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="student_records") # other fields ... def __str__(self): return self.code_name When I give a User as a Manager the perms (add,change,view,delete) for all objects of models which belong to specific school that User manage. If I need to change the Manager (User). I need to reset all permissions and reassign for all related objects of this specific school. How To Acheive This Approach? any support will be appreciated. -
Unit test for Django Update form
I do not understand how to manage updates on forms and related unit tests and I would really appreciate some advises =) I have a Company model, and related very simple CompanyForm: class CompanyForm(forms.ModelForm): company_name = forms.CharField(label="Société", disabled=True) class Meta: model = Company exclude = [] The view is very simple too: @user_passes_test(lambda u: u.is_superuser or u.usercomp.is_admin) def adm_options(request, comp_slug): ''' Manage Company options ''' company = Company.get_company(comp_slug) comp_form = CompanyForm(request.POST or None, instance=company) if request.method == "POST": if comp_form.is_valid(): comp_form.save() return render(request, "polls/adm_options.html", locals()) This view works fine, I can update information (it's actually not used for creation, which is done thanks to the Django Admin panel). Unfortunately, I'm not able to build unit tests that will ensure update works! I tried 2 ways, but none of them worked. My first try was the following: class TestOptions(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.user_staff = create_dummy_user(self.company, "staff", admin=True) self.client.force_login(self.user_staff.user) def test_adm_options_update(self): # Load company options page url = reverse("polls:adm_options", args=[self.company.comp_slug]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, "0123456789") self.assertEqual(self.company.siret, "0123456789") # Options update response = self.client.post( reverse("polls:adm_options", args=[self.company.comp_slug]), {"siret": "987654321"} ) self.assertEqual(response.status_code, 200) self.assertContains(response, "987654321") self.assertNotContains(response, "0123456789") self.assertEqual(self.company.siret, "987654321") In this case, everything is OK but the latest assertion. … -
django picture save SuspiciousFileOperation
{SuspiciousFileOperation}The joined path (\.\con) is located outside of the base path component (C:\ig_db\media) The filename I try to save is 'con.soluciones' once changed to 'consoluciones' I don't get this error. Filename can be with "." in windows. -
Python/Django app where urllib is blocked on Azure
I am very new to Azure, so please go easy on me here. I recently deployed a Python/Django app onto Azure. In the app, I use the Python library urllib to retrieve a file on the internet via its URL. I know the code is correct because the app works locally, but when I deploy it on Azure, the request is met by a 403 error which crashes the app: urllib.error.HTTPError: HTTP Error 403: Forbidden Reading around, it seems that Azure blocks urllib requests. So, I created a custom Web App Firewall (WAF) policy where I disabled all firewall rules, and miraculously the app started working! This is obviously not a permanent solution, so I'm asking if someone can help with one of the following, any of which should solve my issue: Can someone tell me specifically which rule, from this Pastebin list, is the one blocking urllib requests? I can't find any documentation or description, beyond the short label, that explain what they do? Is there a way I can create a WAF exclusion for urllib requests? Is there an alternative to using urllib that doesn't run into Azure firewall issues? Once again, I am very new to how … -
Razor pay order_id and payment signature empty
I am trying to integrate Razor pay in my Django App, but the problem is on POST request my order id and verification signature, both are empty, I tried to search resources but I am having trouble understanding where is the issue lies, guess where I am wrong in this, i have also implemented both GET and POST to the gateway on the same page, also I am only making a place order entry when i am getting a response from Razor Pay <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "{{my_key}}", // Enter the Key ID generated from the Dashboard "amount": parseInt("{{request.session.order.cart_total}}")*100, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", // "order_id": "{{order_id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "callback_url": "{{call_back_url}}", "prefill": { "name": "{{request.session.user.first_name}}", "email": "{{request.session.order.contact_info.email}}", "contact": "{{request.session.order.contact_info.mob_no}}" }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); document.getElementById('rzp-button1').onclick = function(e){ rzp1.open(); e.preventDefault(); } </script> my model @csrf_exempt def checkout(request): #process order zipcode= request.session['order']['delivery_info']['zip_code'] quantity= request.session['order']['order_details'][0]['quantity'] total_price = request.session['order']['cart_total'] shipping_details = … -
How to change a list conaining Longitude/Latitude to a list containing Latitude/Longitude - Django?
I searched for hours on the internet to find a solution but without success. The polygons are displayed on the map but not in their actual position because the longitude is diplayed as latitude and the latitude as longitude. Please, is there a solution to change the position of latitude and longitude in the list? Please, see printed result below. models.py: from django.contrib.gis.db import models from django.contrib.auth.models import User from django.contrib.gis.db.models import PointField, MultiPointField, MultiPolygonField class BurnedArea(models.Model): firedate = models.DateField() country = models.CharField(max_length=80) place_name = models.IntegerField() province = models.CharField(max_length=80) yearseason = models.FloatField() geom = MultiPolygonField(srid=4326) visible = models.BooleanField(default=False) @property def lat_lng(self): return list(getattr(self.geom, 'coords', [] ) [::-1] ) print(self.lat_lng) def __str__(self): return str(self.place_name) views.py: def viewer(request): resultba = [] pol2 = 0,0 areas = BurnedArea.objects.all() for ba in areas: balon = str(ba.lat_lng) pol = balon.replace("(", "[") pol2 = pol.replace(")", "]") print(pol2) resultba.append({'pol2':pol2}) context = { 'resultba':resultba, { return render(request, 'app_web/viewer.html', context) printed result : [[[[8.6065550282249, 36.8027181091122], [8.60768086453233, 36.8020611860536], [8.60746659932254, 36.8016392882169], [8.60734205760659, 36.8011823076919], [8.60600897419624, 36.8016267925537], [8.6064362319159, 36.8019699263144], [8.6065550282249, 36.8027181091122]],]] but I want to have it like this : [[[[36.8027181091122, 8.6065550282249], [36.8020611860536, 8.60768086453233], [36.8016392882169,8.60746659932254], [36.8011823076919, 8.60734205760659], [36.8016267925537, 8.60600897419624], [36.8019699263144, 8.6064362319159], [36.8027181091122, 8.6065550282249]],]] viewer.html: <section class="mapid" id="mapid" ></section> <script> {% for area in … -
how to create django model from json response
Im creating a django app which show some btc prices that I get then from a external api, my problem comes when the app is gonna load it need to always make a call to the api to show me data so it takes very long time for the app to load or even when i want to make some changes on the website the app needs to make a call to the api wait for the response so after that it can show me a data, My goal at this time it will be to save that json response into a Django model so the app wouldn't have to be calling the api all the time so the website will load faster. so my questions is which one it will be the best way to archive that? or how can i even try to do that? Views.py def index(request): form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect("index") tasks = Task.objects.all() context = { "task_form": form, "tasks": tasks, "precio_uk": get_price_uk(), "average_uk": get_average_price_uk(), "precio_ves": get_price_ves(), "average_ves": get_average_price_ves(), } return render(request, 'index.html', context) urls.py urlpatterns = [ path('',views.index,name="index"), path("update/<int:pk>", views.update_task, name="update_task"), path("deleted/<int:pk>/", views.delete_task, name="delete_task"), path('multi',views.multiplication, … -
Problem with Telegram webhook on production server
I'm developing Telegram bot based on pyTelegramBotAPI and Django. There is initial code: import json import time from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import telebot from django.conf import settings if settings.DEBUG: WEBHOOK_HOST = 'https://zzzz.ngrok.io' bot = telebot.TeleBot('zzzz') else: bot = telebot.TeleBot('zzzz') WEBHOOK_HOST = 'https://example.com' WEBHOOK_URL = '/telegram_webhook/' @bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to( message, "Привет! Кажется, мы еще незнакомы. Твой номер: "+str(message.chat.id) ) @bot.message_handler(func=lambda message: True, content_types=['text']) def echo_message(message): bot.reply_to(message, message.text) @csrf_exempt def webhook(request): print(request.body.decode('utf-8')) update = telebot.types.Update.de_json(json.loads(request.body.decode('utf-8'))) bot.process_new_updates([update]) return JsonResponse({'message': 'OK'}, status=200) bot.remove_webhook() time.sleep(1) bot.set_webhook( url = WEBHOOK_HOST + WEBHOOK_URL, ) When I running code locally with ngrok it works well, but when I run it on production server, bot just dont answer on messages. https://api.telegram.org/botZZZZ/getWebhookInfo returns {"ok":true,"result":{"url":"https://example.com/telegram_webhook/","has_custom_certificate":false,"pending_update_count":0,"max_connections":40,"ip_address":"194.0.0.0"}} But if I curl production enpoint with request: curl --tlsv1.2 -v -k -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{ "update_id":10000, "message":{ "date":1441645532, "chat":{ "last_name":"Test Lastname", "id":1111111, "first_name":"Test", "username":"Test" }, "message_id":1365, "from":{ "last_name":"Test Lastname", "id":1111111, "first_name":"Test", "username":"Test" }, "text":"/start" } }', "https://example.com/telegram_webhook/" I will receive some answers from telegram bot and error: Traceback (most recent call last): File "/usr/lib/python3.8/json/decoder.py", line 340, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 20 column 2 (char 332) Now I … -
How Django authentication flow works? [a particular case]
I am reading some code found on the Internet, and trying to make sense of it. I don't understand how authentication works here. Here is the code snippets. the root URLConf urlpatterns = [ path('admin/', admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")) ] Then if we look at authentication.urls, we will see this: urlpatterns = [ path('login/', login_view, name="login"), path('register/', register_user, name="register"), path("logout/", LogoutView.as_view(), name="logout") ] Somehow it ends at 'login/' and login_view handles it. I don't understand why? Ok, then if we open login_view: def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg}) we can see that in case of successful authentication, it redirects to "/", which as I understand it, should create a loop. Because, when you go to http://localhost:8000 the first " ", include("authentication.urls")) will match it. And it all starts again. When and why "", include("app.urls") will match? When "", include("authentication.urls") matches, where does 'login/' come from? Redirecting to "/" in login_view() … -
statement failing under try
I'm absolutely baffled by this issue and was wondering if you could help out. This code works in my dev environment, but when I push it to my production server, the statement under 'try' fails and, despite this, the system doesn't even attempt the statement under 'except'. I've probably written 10,000 try/except statements and I've never seen anything like this. try: user_profile = Profile.objects.get(user=kwargs['instance']) except: user_profile = Profile.objects.create(user=kwargs['instance'], busemail=kwargs['instance'].email) Under what circumstances would the system not attempt to execute the except statement? Thanks! -
Typeahead Bloodhound Autocomplete using prefetch + remote when source is a dict from Django
Bloodhound variable for Typeahead that's working nicely: var egDjangoVar = new Bloodhound({ queryTokenizer: Bloodhound.tokenizers.whitespace, datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), remote: { url: '/ajax/eg/%QUERY.json', wildcard: '%QUERY', filter: filterdata } }); We added dict parsing function filter: filterdata because Django requires JSON to be sent as a dict for security: function filterdata(data){ return $.map(data.results, function(results,index){ return results.value; }) } All works beautifully. We now want Prefetch functionality and have added: prefetch: { url: '/ajax/prefetch.json', wildcard: '%QUERY', filter: filterdata }, This doesn't work, despite '/ajax/prefetch.json' serving expected dict. We think it may be due to dataTokenizer issues discussed in this answer, but we don't understand why the tokenizer should differ between remote and prefetch sources, and the suggested datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value)}; didn't work when adding it as an argument of prefetch. We've found that __/ajax/prefetch.json__data in local storage is saved with dict keys matching values like {"datums":{"Apple":"Apple","Banana":"Banana","Orange":"Orange"},"trie":{"i":[],"c":{}}}, whereas the remote data directly viewed is like {"results": [{"value": "Apple"}, {"value": "Banana"}, {"value": "Orange"}]}. Is this unexpected? I'm new to front end / JS, so please forgive me if this is a stupid question. What are we doing wrong?