Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create two models with required ForeignKey fields to eachother?
I have two models, both of them with a ForeignKey field to eachother. from django.db import models class County(models.Model): capital = models.ForeignKey("Municipality", on_delete=models.PROTECT, related_name="capital_of") class Municipality(models.Model): county = models.ForeignKey(County, on_delete=models.CASCADE, related_name="municipalities") With these models, I'm unable to create nor an instance of County or Municipality. What should I do to fix it? -
Django + Dockerfile + Cron
I have been working on a task for a few days. Building a separate Dockerfile (not using docker-compose just a stand alone Dockerfile) that is supposed to produce an image and run a cron job which I have not done before. I believe I am almost there, but running into a config/settings issue when running the script. I have a short Dockerfile here... FROM python:3.7.8-alpine RUN apk update RUN apk add --no-cache libpq postgresql-contrib python3-dev RUN apk add --no-cache supervisor postgresql-dev RUN python3 -m pip install --upgrade pip ADD ./app/requirements.txt /files/requirements.txt ADD ./app/reqs/ /files/reqs/ RUN python3 -m pip install -r /files/requirements.txt RUN touch /var/log/cron.log ADD cronjobs/crontab.txt /crontab.txt ADD cronjobs/cron_script.sh /cron_script.sh ADD ./script.py /script.py COPY cronjobs/entry.sh /entry.sh ADD ./script.py /app COPY ./script.py /app RUN chmod +x /script.py RUN chmod 755 /script.sh /entry.sh RUN /usr/bin/crontab /crontab.txt COPY . /cron_app CMD ["/entry.sh"] crontab.txt file here.. * * * * * /cron_script.sh > /dev/stdout entry.sh file here. #!/bin/sh echo "Docker container running....." /usr/sbin/crond -f -l 8 Script which calls the main python script. #!/bin/sh echo "Python script running..." cd /cron_app python3 send_email.py echo "python script has finished..." The script sends an email, which uses django's settings, and email config in my settings file which … -
Unable to create using .object.create() in DJANGO 3.5+
I am having trouble creating objects using '.objects.create()' in Django v3.5+ here is my create function - order = Order.objects.create( txn_id = txn_id, user = request.user, payment_id = pay_id, gateway_order_id = str(gateway_order_id), gateway_signature = str(signature), amount = basket.get_total_price(), payment_option = "Wallet", order_status = True,) Here are they values captured and trying to populate - 9 teddy pay_HbkHTcQsUzT0Rb order_HbkH3jmcvfhQR8 53fa5704b595832d472ccc08e193d2b686078d78ca7fa7e403f763c753568433 90.00 Wallet True and here is the corresponding model class Order(models.Model): txn_id = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="order_txn") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") payment_id = models.CharField(max_length=100, null=True, blank=True) gateway_order_id = models.CharField(max_length=100, null=True, blank=True) gateway_signature = models.CharField(max_length=100, null=True, blank=True) amount = models.DecimalField(max_digits=5, decimal_places=2) payment_option = models.CharField(max_length=200, blank=True) order_status = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ("-created",) def __str__(self): return str(self.created) any assitance would be appreciated. Many Thanks in Advance! -
Django OAuth Toolkit refresh token using okta workflow API Connector
I have successfully created an oauth provider and can verify that I am able to get a token and refresh token using django-oauth-toolkit. While using [okta workflow api connector][1] OAUTH option, it is able to get the token after going through the initial setup. However, once that initial token expires, it is not getting a refreshed token as expected. The scope that the connector is setup with is an additional scope that I added to the settings.py of my django project via the SCOPES setting similar to how the doc's show in [this link][2]. As I am new to django-oauth-toolkit. My first question is does a new scope added via this method need to have additional configuration in order to allow an oauth2 connection to get a refresh token? I am using django-oauth-toolkit 1.5.0 [1]: https://help.okta.com/wf/en-us/Content/Topics/Workflows/function-reference/HTTP/http_authorization.htm [2]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html -
Applying and managing Django migrations in Skaffold development environment
I'm not satisfied with my current workflow related to managing Django migrations and it really feels like there should be a better way. As part of my environment setup shell script, it creates a .venv and adds env vars to it for DB connection strings and the such. When I work on models and need to migrate this gives me the ability to run ./manage.py migrate in the local environment to apply them. This is really the only purpose it serves. It also adds the same env vars to Kubernetes secrets for the cluster. I came across this where someone had a similar issue, but was kubectl exec into the Pod: How to keep Django 2.2 migrations on Kubernets while developing? That would mitigate the need to run ./manage.py locally and thus have the env vars, but kubectl exec into the Pod just to run ./manage.py migrate seems like an even bigger hassle. It seems like there should be a better way. Suggestions? -
Django Rest Framework URL filter only specific fields from Database
I did try to search my problem in StockOverflow or Google, but I can find only how to make Search results and how to make search on specific fields, but I need API output with specific fields with URL request. I have DB with those fields: date = models.DateField(['%Y-%m-%d']) channel = models.CharField(max_length=255) country = models.CharField(max_length=255) os = models.CharField(max_length=255) impressions = models.IntegerField() clicks = models.IntegerField() installs = models.IntegerField() spend = models.FloatField() revenue = models.FloatField() I did create different filters which can be used to GroupBy, ordering and another good features. The problem is: for example I have task to: Show the number of impressions and clicks that occurred before the 1st of June 2017, broken down by channel and country, sorted by clicks in descending order. If I use this: http://127.0.0.1:8000/api/stock?date_to=2017-05-19&groupby=channel&groupby=country&ordering=-clicks It will give me this result: "results": [ { "channel": "adcolony", "country": "US", "impressions": 101292, "clicks": 2479, "installs": 445, "spend": 743.6999999999999, "revenue": 965.12, "CPI": "1.67" }, It was Grouped by "channel" and "country" for specific date in DESC order. But how to make additional URL inputs (like show only "impressions" and "clicks")to show ONLY those: "results": [ { "channel": "adcolony", "country": "US", "impressions": 101292, "clicks": 2479, }, This is my … -
sudo apt install python3-dev for windows
I'm trying django-oscars demo and I'm wanted to test it out but I'm literally stuck on the first part lol. I need help since I can't use sudo for windows what should I do then? "sudo apt install python3-dev" djang-oscar -
KeyError at /home 'assets', using webpack loader
I'm working on a small project using Django and VueJS, i just install django-webpack-loader and "webpack-bundle-tracker": "^0.4.3", and i got an error while rendreding : KeyError at /home 'assets' This is my code : {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello</title> </head> <body class="sidebar-enable vertical-collpsed"> <!--<h1>Vue JS</h1>--> <div id="app"></div> {% render_bundle 'app' %} </body> </html> -
Page not found, request method: get using Django when all pages correctly in urls.py
I know there are many similar posts, but having tried: Page not found (404) Request Method: GET Django -Page not found (404) Request Method: GET Method Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about I'm still not able to solve this problem. This is a practice sample from cs50w. I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in airline.urls, Django tried these URL patterns, in this order: admin/ flights/ users/ The empty path didn’t match any of these. I have a main urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path("flights/", include("flights.urls")), path("users/", include("users.urls")) ] urls.py in flights: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.book, name="book") ] and in users, url.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout") ] My settings.py: """ Django settings for airline project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os … -
Django with dropzone multiple images do not upload in CBV
Im working on bulletin board for sporting shoes with django. For now my goal is to give an opportunity for users create and post their own bboards with information from models through model.Forms. And the biggest problem is upload propely multiple images using dropzone.js, i spend lots of time for this problem. The first part on 'addpage.html' is usual forms with text and selected inputs, but the second one is the dropzone js div class, cause i know i cannot affort to use 2 forms straight on current page. My question is how am i have to organize my CreateView at views.py for uploading images on server. For now i have only traceback 'AddCardCreateView' object has no attribute 'object!!! And dictionary of images is empty So let's see my code. We will start from models.py (ImagePhoto fk to Card) class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, verbose_name='Пользователь') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд') boots_model = models.CharField(max_length=100, db_index=True, verbose_name='Модель бутс') description = models.TextField(verbose_name='Описание') slug = AutoSlugField('URL', max_length=70, db_index=True, unique_with=('created', 'boots_model', 'size', 'color', 'price'), populate_from=instance_boots_model, slugify=slugify_value) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена') created = models.DateTimeField(auto_now_add=True, db_index=True) updated = models.DateTimeField(auto_now=True) size = models.DecimalField(max_digits=4, decimal_places=1, verbose_name='Размер') NEW = 'new' USED = … -
Django ModelForm Widget attributes generation in HTML
What is the proper way to have Django rendering widgets to html elements with correct attributes? Following the documentation I did the following for my class: CLASS: class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='TravelsApp/profile_pics',blank=True) phone_number = models.CharField() credits = models.PositiveIntegerField(default=10) exp_date = models.DateField(default = timezone.now) ..... FORM class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('profile_pic', 'phone_number', 'exp_date') widgets = { 'profile_pic': forms.ClearableFileInput(attrs={'class': "w3-btn w3-blue w3-center"}), 'phone_number': forms.TextInput(attrs={'class': "w3-input", 'required':'True'}), 'exp_date': forms.DateInput(attrs={'class': "w3-input", 'required':'False', 'disabled': 'True'}), } ....... VIEW: def register(request): ....... # GET: Just render the forms as blank. user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'TravelsApp/registration.html', {'user_form':user_form, 'profile_form':profile_form, }) When register() gets called and the code after #GET is executed the 'exp_date' UserProfileInfoForm is not rendered properly : HTML: <p><label for="id_exp_date">Exp date:</label> <input type="text" name="exp_date" value="2021-07-21" class="w3-input" disabled="True" required id="id_exp_date"> <input type="hidden" name="initial-exp_date" value="2021-07-21 20:06:53+00:00" id="initial-id_exp_date"></p> The attribute 'required' is present (hence meaning required = true) while it should be set to false (It also generates this 'initial-exp-date' which is hidden and I think it's added just for security reasons) I tried to play around for one long evening then I noticed that if I change the form definition removing the 'exp_date' from the 'fields' … -
Add a button along save buttons in Django Admin Change Form
I have this code for a custom change_form: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block after_related_objects %} <button>Another button</button> {% endblock %} {% block submit_buttons_bottom %} {{ block.super }} <!-- import script --> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} which produces this view: It works fine but I wanted to add it inside the button row below: I tried to change the code to: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block submit_buttons_bottom %} <button>Another button</button> {% endblock %} {{ block.super }} <!-- import script --> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} but it's giving me an invalid block error. How do I add the button element to produce the result in the image above? -
Django custom user error when registering: get_session_auth_hash() missing 1 required positional argument: 'self' (new user can otherwise log in)
I am aware of this answer: TypeError: get_session_auth_hash() missing 1 required positional argument: 'self', but I am not using a custom backend and the error in question happens when registering a new user through a Django form, not when logging in. Further, whilst the user does not remain logged in when registering and is not automatically redirected to the main page as intended, logging in from the log in form seems to function normally. The error happens on this line in my registration view: login(request, User) And traces back to this line in django.contrib.auth: if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() <<<<<<<<< This line I think because I'm using a custom user, there's something else I need to modify in the default code, but I'm not sure what this should be. I think the custom user model should be interchangeable with the default user model, but it isn't and I'd welcome someone with more experience than me pointing me in the right direction. My code as follows: Custom user model and manager in models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password = None, active = True, staff = False, superuser … -
Django get all objects whose many to many filed contains a filter
I have 3 models: City: indicating a city Titles: indicating job titles Contacts: indicating people. A person can have multiple titles and multiple cities Now, given an city object and a title object, I want to query for all people that have those objects in their instance. Basically something like "All Lawyers in NY". class City(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name=models.CharField(max_length=40) state=models.CharField(max_length=15) class Title(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title_name=models.CharField(max_length=40) class Contact(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name_surname = models.CharField(max_length=60) title = models.ManyToManyField(Title) city = models.ManyToManyField(City) -
Django models create multiple choices field with status
I have a question about my models, I need to create a post request in which I select a couple of people for one POST and I want to add a status to each of them assigned to a given person my models.py class Daily(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.CharField(choices=utils.TEAM, max_length=8, default=None, blank=False) person1 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) person2 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) person3 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) date = models.DateField() class Meta: ordering = ('-date',) constraints = [ models.UniqueConstraint(fields=['user', 'date'], name='name of constraint') ] so my question is how to optimize it, for every record will be choices 2 or 3 person, but now i wanna add status choices for each of them and be unique for choices person -
How to reformat a Nigerian phone number in Javascript or Python function [closed]
I received phone numbers in different formats and I will like to convert them to a particular format before using them.These are the following formats users will always submit: +234 816 312 1111 234 816 312 1111 +2348163121111 2348163121111 0816 312 1111 08163121111 I will like to always reformat the number to No 6. i.e 08163121111. The implications of this are: '+' signs are removed spaces between the numbers are removed. country code (234) are removed. '0' are added at the beginning of the numbers after removing country code. How do I achieve this in javascript or using a python function. -
How can I create submit form in Django with dropping down list?
I am just starting to work with Django and I have some problems with forms and dropping lists. So, let me explain my problem: I have a model with two attributes, I want to display one of the attributes in a dropping down list (This one will be unchangeable) and another one in a text field (This one will be changeable). Also, I have a submit button, so I want to change a second attribute in a text field and by pressing on the button. I have no idea how to do this, can somebody type examples? Thank you! -
Using django model in django template javascript json error
I want to use django model in template javascript and people say I need to make it into json and then pass it so I made json object from models.py and views.py like this. models.py from django.db import models from django.utils.timezone import localdate class Posts(models.Model): address = models.CharField(max_length=100, null=True) lat = models.CharField(max_length=50, null=True) lng = models.CharField(max_length=50, null=True) name = models.CharField(max_length=50, null=True) title = models.CharField(max_length=50, null=True) pick_date = models.DateField(null=True) create_date = models.DateField(auto_now=True, null=True) music = models.CharField(max_length=100, null=True) mood = models.CharField(max_length=50, null=True) description = models.CharField(max_length=300, null=True) image = models.ImageField(upload_to="images/", null=True) # H E R E # def to_json(self): return { "address": self.address, "lat": self.lat, "lng": self.lng, "name": self.name, } def __str__(self): return str(self.title) views.py import json def post_list(request): posts = Posts.objects.all() context = { "posts": posts, "posts_js": json.dumps([post.to_json() for post in posts]), } return render(request, "posts/map_marker.html") map_marker.js // this js file is linked to map_marker.html let posts = JSON.parse("{{ posts_js | escapejs }}"); console.log(posts); I want to see how the posts object looks like but it keeps saying json error JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data It's hard to find a reason as I can't look through how the json object looks like. … -
Perform action from a form or link without refreshing the page/view with django
I'm developing a project where I need to add members to a group, for that, I go through all registered members and present them in my html template. Each member has the "add" button next to it, but always when doing this it refreshes a page... I would like to know how to do this without needing to refresh, ie click on add and it is already added automatically. views.py def add_members(request, id): plan=Plan.objects.get(id=id) users = User.objects.all() # extended django's default user model return render(request,'site/add_members.html', {'plan':plan, 'users':users}) add_members.html {% extends 'base.html' %} {% block title %} Add Members {%endblock%} {% block content %} <div class="row"> {% for i in users %} <h4>{{i.first_name}}</h4> <form method="POST"> {% csrf_token %} <input type="submit">Add</input> </form> {%endfor%} </div> {%endblock%} -
css is not working in my blog page only other pages working properly in my django project
I am working on a django project. All css working well on my local server but when i am hosting on pythonanywhere.com then css of only /blog url not working properly. I can't able to find the error. Please help me. You can visit my hosted website at http://sauravportfolio.pythonanywhere.com/blog/ and you can see my entire code at github https://github.com/saurav389/portfolio . you can see my all css code at portfolio/src/portfolio/static/css/ folder. and my bootstrap is not working in chrome browser too. Please do something for me. -
Django filter Logging to slack channel
I am trying to implement a function to filter the error message that sent to Slack channel. I still want it to log in .log file just dont want it sent it out to Slack. This is what i have tried so far: def contains_url(record): if 'abc' in record.request.path: return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[{levelname}] {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': {'format': '[{levelname}] -- : {message}', 'style': '{',}, }, 'filters': { 'contains_url': { '()': 'django.utils.log.CallbackFilter', 'callback': contains_url, } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.log', 'formatter': 'simple', }, 'slack_admins': { 'level': 'ERROR', 'filters': ['contains_url'], 'class': 'django_slack.log.SlackExceptionHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'slack_admins'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), } } so basically, i would want all the error message from an url that contain 'abc' log to the log.log as usual but just not want it in slack channel. I added slack_admins -> filters but it didn't help. Any suggestions ? Thanks -
Getting an error when attempting to run my utility script
I am trying to build a database load utility for my project. The old application is running and has MySQL dB records that I want to import into the Django mysql instance. I started writing a script and was able to connect to my old (outside of Django) DB just fine, but wanted to use the models in my new Django project so that I can create objects and use the save routines/methods etc. Just in the beginning stages, but when I attempt to import the models from my Django site in my new utility app, it says module not found...? Am I missing something? I did a python manage.py startapp db_load to create my app. The code resides there in a file named db_load.py. Here is what it looks like: #!/usr/bin/env python ################################ # This utility will load old records from a Production db # stored in local host into the Django database on local host # ################################ import MySQLdb from trackx_site.models import Program db_old_trackx = MySQLdb.connect( host= "localhost", db = "old_db", user = "root", passwd = "blah blah", charset='utf8mb4') db_django_db = MySQLdb.connect( host = "localhost", db = "new_project_blah", user = "root", passwd = "blah") sql = "select ......" … -
ModuleNotFoundError: No module named 'music_controller.api'
When I run the server, I am getting the following error: from music_controller.api.models import Room ModuleNotFoundError: No module named 'music_controller.api' I think the problem is from the import in the views.py: from django.shortcuts import render from rest_framework import generics from .serializers import RoomSerializer from .models import Room # Create your views here. class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer I made sure that the app name is included in INSTALLED_APPS in the settings.py. The following is the tree of my project: -
How to get just the relational fields of a model?
Here is my model, the question is below. from django.db import models # ... class County(models.Model): name = models.CharField(max_length=50, verbose_name=_("Numele județului")) capital = models.ForeignKey("Municipality", on_delete=models.PROTECT, null=True, blank=True, related_name="capital_of", verbose_name=_("Reședința")) region = models.ManyToManyField(Region, related_name="counties", verbose_name=_("Regiunea")) area = models.IntegerField(verbose_name=_("Suprafața")) population = models.IntegerField(verbose_name=_("Populația")) description = models.TextField(verbose_name=_("Descrierea")) north = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_south", verbose_name=_("Nord")) northeast = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_southwest", verbose_name=_("Nord-est")) east = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_west", verbose_name=_("Est")) southeast = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_northwest", verbose_name=_("Sud-est")) south = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_north", verbose_name=_("Sud")) southwest = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_northeast", verbose_name=_("Sud-vest")) west = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_east", verbose_name=_("Vest")) northwest = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_southeast", verbose_name=_("Nord-vest")) class Meta: verbose_name = _("Județ") verbose_name_plural = _("Județe") def __str__(self): return self.name @property def neighbours(self): neighbour_counties = {} for field in self._meta.fields: if field.related_model == County: neighbour_counties[field.name] = field return neighbour_counties neighbours.fget.short_description = _("Vecinii") In this example I want to add two instances: Olt and Teleorman. If I create Olt and specify Teleorman as its eastern neighbour, how can I automatically set the western neighbour of Teleorman to Olt? My idea was to get a list with the eight neighbour fields as a property and it works fine until I try to get … -
How to prevent "Frame load interrupted" Safari browser console error upon form-initiated download?
I have tried all the answers I could find regarding this Safari browser console error: Failed to load resource: Frame load interrupted and so far, none of the suggestions have prevented the error. To summarize, I have an advanced search page that presents search results on the same page as the search form. When there are results, I include a separate download form (with a hidden element containing the DB query (in the form of JSON) and a visible button named "Download". There are 2 classes involved: the advanced search class (AdvancedSearchView) and the advanced search download class (AdvancedSearchTSVView). The download works. So all I want to do is prevent the error from appearing in the browser console. Here are the snippets that I believe are relevant: views.py class AdvancedSearchView(MultiFormsView): template_name = "DataRepo/search_advanced.html" download_form = AdvSearchDownloadForm() ... def form_valid(self, formset): download_form = AdvSearchDownloadForm(initial={"qryjson": json.dumps(qry)}) return self.render_to_response(self.get_context_data( ... download_form=download_form)) class AdvancedSearchTSVView(FormView): form_class = AdvSearchDownloadForm template_name = "DataRepo/search_advanced.tsv" content_type = "application/text" success_url = "" basv_metadata = BaseAdvancedSearchView() def form_valid(self, form): cform = form.cleaned_data qry = json.loads(cform["qryjson"]) now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") filename = (qry["searches"][qry["selectedtemplate"]]["name"] + "_" + now.strftime("%d.%m.%Y.%H.%M.%S") + ".tsv") res = performQuery(qry, q_exp, self.basv_metadata.getPrefetches(qry["selectedtemplate"])) response = self.render_to_response(self.get_context_data(res=res, qry=qry, dt=dt_string, …