Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django Admin site renders PostGIS coordinates incorrectly?
Django Admin site renders coordinates as: { "type": "Point", "coordinates": [ 2599546.894950558431447, 7276499.344635636545718 ] } When it should be: { "type": "Point", "coordinates": [ 25.99546894950558431447, 72.76499344635636545718 ] } Why is that so? -
How to upload my Postgres database to Django Heroku app?
I want to upload my local postgres database in an existing heroku Django app. I run this: $ PGUSER=postgres PGPASSWORD=mypass heroku pg:push postgres://localhost/newschool DATABASE_URL But it shows this: The local psql command could not be located. For help installing psql, see ! https://devcenter.heroku.com/articles/heroku-postgresql#local-setup How to get psql? I have pgadmin and postgres installed on my pc already. What should I do? In the docs mentioned above, they just ask to install postgres for windows. I have done that already! ps.newschool is the database name -
How do I pass a response from an asynchronous celery task that's running in the background in django to a socket that's running in the front end?
I am running an asynchronous task using celery and RabbitMQ in django. After the successful execution of the task I should send a response to a socket that listening in front-end. I found tutorials and examples for running async task in django but I could find no blog or tutorial for my need. Thanks in advance! -
Django Multiple Databases CreateSuperUser - django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly config
I am Building a Django application using python 3.7.6 and Django 3.0.5. This solution has multiple applications each application will have its own standalone database configured. I was able to successfully complete migrations. However I am Unable to CreateSuperUser. It is failing with following error - django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. My Settings file has following DB configurations - DATABASE_ROUTERS = ['ISMABlogs.Db_Router.Db_Router'] DATABASE_APPS_MAPPING = {'Blogs': 'blog', 'ISMATutorials':'tutorial'} DATABASES = { 'default': { }, 'blog': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'isma_blogs', 'USER' : 'abc', 'PASSWORD': 'something', 'HOST': 'localhost', 'PORT':3306 }, 'tutorial': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'isma_tutorials', 'USER' : 'xyz', 'PASSWORD': 'something', 'HOST': 'localhost', 'PORT':3306 } } DEFAULT_DB_ALIAS='blog' And My Router file has following configuration - class Db_Router(object): """ A router to control all database operations on models in the user application. """ def db_for_read(self, model, **hints): """ Attempts to read ISMATutorials models go to ISMATutorials. """ if model._meta.app_label == 'Blogs': return 'blog' elif model._meta.app_label == 'ISMATutorials': return 'tutorial' return 'blog' def db_for_write(self, model, **hints): """ Attempts to write user models go to users_db. """ if model._meta.app_label == 'Blogs': return 'blog' elif model._meta.app_label == 'ISMATutorials': return 'tutorial' return 'blog' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if … -
Not Authenticated Error in Django using Stripe
I am creating for the very first time a payment for an e-commerce website using stripe, I am following a guide and have reviewed every step carefully but always getting Not Authenticated Error and I'm unclear what is going wrong. I am new to Django so I'm trying to learn as much as possible from my errors. Here is my views.py class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) context = { 'order': order } return render(self.request, "payment.html", context) # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your Order was Successful ! ") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") # Since it's a decline, stripe.error.CardError will be caught return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate Limit Error") return redirect("/") … -
Efficent way to update a random value for django models
I'm using Django with PostgreSQL and I want to know if there is a way to update a certain number of models, that have uniques fields, with random values. My problem is I need to update 5k of users changing his emails and usernames with random values. These fields are uniques, which means two instances can't have the same values. My logic is: for each user, (1) generate random email string, then if there isn't any user with that email, use that string, else back to 1 # Python2.7 Django 1.11, but everything helps from django.contrib.auth.models import User from django.utils.crypto import get_random_string for user in User.objects.order_by('-pk')[:5000].iterator(): # Generate random email while True: random_email = get_random_string(10) if not User.objects.filter(email=random_email).exists(): user.email = random_email break # Generate random username while True: random_username = get_random_string(10) if not User.objects.filter(username=random_username).exists(): user.username = random_username break user.save() -
Play video uploaded by user with formset in Django
I'm not able to play videos from list made with formset in django. I want to make a video playlist with videos uploaded by user (a sort of udemy . com). Users can add fields to upload more videos or let only one field by default (there is script in javascript for that). I havent problem to upload videos, everything is ok about that (videos are uploaded correctly). The problem is to play videos. Here my models.py from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify class Cours(models.Model): titre = models.CharField(max_length=100) slug = models.SlugField(max_length=100) auteur = models.CharField(max_length=42) comment = models.TextField(null=True) link = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Cours, self).save(*args, **kwargs) class Meta: verbose_name = "cours" db_table = "cours" ordering = ['date'] def __str__(self): return self.titre class Categorie(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Plan_simple(models.Model): partie = models.CharField(blank=True, max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") vid = models.FileField() cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE) def __str__(self): return self.partie class Meta: db_table = "plan_simple" my form.py from django import forms from django.forms import ModelForm from django.template.defaultfilters import slugify from django.forms import formset_factory from … -
Error Install Django-Admin (Running setup.py install for screen ... error)
I was having no problem running django but when I was about to run 'django-admin startproject', it says there is no 'django-admin' directory in my Python folder. So I ended up trying to install using pip install django-admin. Here is the error: C:\Users\syahm>pip install django-admin Collecting django-admin Using cached django_admin-2.0.1-py2.py3-none-any.whl (7.6 kB) Collecting django-excel-response2>=3.0.0 Using cached django_excel_response2-3.0.2-py2.py3-none-any.whl (4.4 kB) Collecting django-excel-base>=1.0.4 Using cached django_excel_base-1.0.4-py2.py3-none-any.whl (4.0 kB) Requirement already satisfied: django-six>=1.0.4 in c:\users\syahm\appdata\local\programs\python\python37-32\lib\site-packages (from django-excel-response2>=3.0.0->django-admin) (1.0.4) Requirement already satisfied: xlwt in c:\users\syahm\appdata\local\programs\python\python37-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (1.3.0) Collecting screen Using cached screen-1.0.1.tar.gz (8.6 kB) Requirement already satisfied: pytz in c:\users\syahm\appdata\roaming\python\python37\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (2019.2) Installing collected packages: screen, django-excel-base, django-excel-response2, django-admin Running setup.py install for screen ... error ERROR: Command errored out with exit status 1: command: 'c:\users\syahm\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\syahm\\AppData\\Local\\Temp\\pip-install-o89ws43u\\screen\\setup.py'"'"'; __file__='"'"'C:\\Users\\syahm\\AppData\\Local\\Temp\\pip-install-o89ws43u\\screen\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\syahm\AppData\Local\Temp\pip-record-t_rdgtfv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\syahm\appdata\local\programs\python\python37-32\Include\screen' cwd: C:\Users\syahm\AppData\Local\Temp\pip-install-o89ws43u\screen\ Complete output (18 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\screen copying screen\compat.py -> build\lib.win32-3.7\screen copying screen\old_str_util.py -> build\lib.win32-3.7\screen copying screen\__init__.py -> build\lib.win32-3.7\screen running build_ext building 'screen.str_util' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\syahm\appdata\local\programs\python\python37-32\include … -
Getting rid of port in URL for django installation in production
I'm trying for the first time to deploy my Django application on a server but so far I wasn't able to get rid of port in my URL. Right now I'm using Gunicorn with Nginx with the following configuration. Nginx /etc/nginx/sites-enabled/site.conf server { listen 8000; server_name example.com; location = /favicon.ico {access_log off;log_not_found off;} location /static/ { root /home/webapp/um; } location /media/ { root /home/webapp/um; } location / { include proxy_params; proxy_pass http://unix:/home/webapp/um/um.sock; } } /etc/nginx/proxy_params proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; Gunicorn /etc/systemd/system/gunicorn.service Description=gunicorn service After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/webapp/um/ ExecStart=/root/um/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/webapp/um/um.sock um.wsgi:application [Install] WantedBy=multi-user.target Gunicorn binding gunicorn --bind 0.0.0.0:8000 um.wsgi:application Changing port 8000 with port 80 in /etc/nginx/sites-enabled/site.conf gives me a 404 on nginx. Using port 8000 I'm able to see the site using http://example.com:8000/myapp but I'm aiming at using http://example.com/myapp as my address. As a side note, the VPS I'm installing the app on came with Plesk already installed with which I'm also not familiar with. I don't know if Plesk might be interferring in catching traffic from port 80. Thanks in advance -
Override parent css settings using child gives unknown property name
I'm trying to override the parent settings of a dropdown menu using a child class in CSS. Unfortunately, when I try to do this it gives me an "unknown property name" error on the child class, even though I use the exact same property on the parent class. The CSS code looks like: .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; overflow: hidden; min-width: 160; min-heigth: 100; background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; z-index: 1; left:20%; } .test { min-width: 1080; min-heigth: 480; } .dropdown:hover .dropdown-content { display: inline-block; } And the HTML code (django template format) looks like: {% for info in infos %} <div class="dropdown"> <a href="#">dropdown item</a> <div class="dropdown-content"> {% if info.2 == "img" %} <!-- display image --> {% elif info.2 == "gif" %} <div class="test">Gifs and Videos are disabled for preview.</div> {% endif %} </div> </div> {% endfor %} In which info.2 will always contain either the string "gif" or "img". I have not yet implemented the image yet. However, if I use inspect element I get the following error: Which does not make any sense to me, as the css within the dropdown-content class … -
How to make media types for media shared and private
Currently, I want to make a media types which is shared and private. For media shared, all project can view the media while for media private only certain project can view it. I dont why its not working. These are my coding views.py def CONprojectnewknowledgecenter(request, id): project_dat = get_object_or_404(project_db, pk=id) if request.method == 'GET': all_format = Format.objects.all() all_category = Category.objects.all() all_mediatype = MediaType.objects.all() return render(request, 'dashboard/CONprojectnewknowledgecenter.html', {'all_format': all_format, 'all_category': all_category, 'all_mediatype': all_mediatype, 'project_dat': project_dat}) if request.method == 'POST': print("Creating new Kc, format: ", request.POST.get('format_id')) formatinstance = get_object_or_404(Format, pk=request.POST.get('format_id')) print("Creating new Kc, category: ", request.POST.get('category_id')) categorylist = get_object_or_404(Category, pk=request.POST.get('category_id')) print("Creating new Kc, media type: ", request.POST.get('mediatype_id')) mediatypes = get_object_or_404(MediaType, pk=request.POST.get('mediatype_id')) kc_submission = Kc.objects.create() image = None try: print("Checking for Kc Image ... ") image = request.FILES['image'] except: print("Error: No Kc Images Found. Revert to NULL value.") finally: print("Checking for Kc Filetype ... ") if formatinstance.filetype == 'File': print("Filetype:File") if categorylist.category == 'Category': print("Category selected") if mediatypes.mediatype == 'Media': print("Media Type selected") try: print("Checking for Kc Filesource ... ") my_uploaded_file = request.FILES['inputmediafile'] except: print("Error: No Kc Filesource Found. Redirecting back to input page.") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) inputmedia = my_uploaded_file.name status = gcp("write", file_path="project/" + str(kc_submission.id) + "/" + inputmedia, item=my_uploaded_file.read()) else: print("Filetype:Link … -
django : nombre de choice field dynamique et pas fixe
Bonjour, Alors voila je fait un formulaire dans django et j'aimerais pouvoir faire une commande d'articles. Je ne sais pas à l'avance combien d'articles l'utilisateur va vouloir, exemple N articles. Je ne sais pas du tout comment dynamiquement les déclarer dans le form pour que plusieurs case s'affiche. En gros pour l'url articles/5/ je voudrais que 5 forms.MultipleChoiceField apparaissent, pour artciles/7/ il y en ai 7. Je sais deja comment récuperer N en fonction de l'url, mais je sais pas les déclarer. J'ai essayer une list mais rien ne s'affiche dans mon site on dirait que ca ne marche pas. Mon code dans forms est : class ArticlesForm(forms.Form): article = [] def NumArticles(self, nbArticles): self.nbArticles = nbArticles MyProp = ((1, 'Item title 1'), (2, 'Item title 2'), (3, 'Item title 3'), (4, 'Item title 4'), (5, 'Item title 5')) for i in range(nbArticles): self.article.append(forms.MultipleChoiceField(choices = MyProp)) nom = forms.CharField(max_length=100) Ici y'a un charfield nom qui s'affiche, mais la list article semble toujours vide, quand je l'appel je fait form = ArticlesForm(request.POST or None) form.NumArticles(nbArticles) Et normalement dans ma tete la list d'article est modifié mais il semble que non ? est-ce que quelqu'un à une idée de comment afficher dynamiquement … -
How to store upperbound to infinite DecimalRangeField
from django.contrib.postgres.fields import DecimalRangeField Django3 and Postgres11 I need to store inf in the DecimalRangeField() from django.contrib.postgres.fields import DecimalRangeField from psycopg2.extras import NumericRange class Premium(models.Model): sum_insured = DecimalRangeField() NumericRange with small number is work def test_range_field(self): Premium.objects.create( sum_insured=NumericRange(3, 12), ) self.assertEqual(1, Premium.objects.count()) Problem: Premium.objects.create( sum_insured=NumericRange(3, float('inf')) ) It raises error django.db.utils.ProgrammingError: syntax error at or near "Infinity" Question: How do I store the inf in the DecimalRangeField? -
function() got an unexpected keyword argument 'name1'
I am keep getting this typeerror:fun() got unexpected keywar arg, can someone tell what is the issue. Thanks in advance def register(request): if request.method =='POST': nm=request.POST['nm'] email1=request.POST['email'] pass1=request.POST['pass1'] pass2=request.POST.get('pass2') num=request.POST['num'] if pass1==pass2: new=register(name1=nm,email=email1,password=pass1,phone=num) new.save() #message.success(request,"You are register Successfully!") print("User Register") else: return redirect('/register') else: return render(request,'register.html',) -
Django models error: ValueError: Field 'cat' expected a number but got '-'
i just add 2 models to my class and i got this error: ValueError: Field 'cat' expected a number but got '-'. my code: # Create your models here. class News(models.Model): title = models.CharField(default=',', max_length=50) name = models.CharField(default=',', max_length=50) short_txt = models.TextField() body_txt = models.TextField() date = models.CharField(default=',', max_length=12) writer = models.CharField(max_length=50) catname = models.CharField(max_length=20, default='-') catid = models.IntegerField(max_length=10, default=0) def __str__(self): return self.name I had a cat model, but I removed it before... Thank you for your time<3 -
Django custom authentication using an external API endpoint
I have an API endpoint from my company that takes username and password and returns 200 response if the user is authenticated. The response body has all details about the user like user_id, name etc. Another endpoint allows a GET request with user_id as a parameter and tells if user is authenticated. For login: I use the first endpoint with POST request to check response code and also set user_id in my session so that i can later use this user_id to send a GET request to see if user is still authenticated. How can I use this in combination of login_required decorator to make sure user is authenticated for all the views in my application? Or is there any other way I can customize middleware.py for this functionality? -
get_initial() function simplification
I am populating a form with instance objects of another model like this: class ProcessingCreate(generic.CreateView): model = ProcessingActivityInstance template_name = 'dpapp/processing-create.html' fields = '__all__' def get_initial(self): initial = super(ProcessingCreate, self).get_initial() initial.update({'processing_toptype': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_type': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_description': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_purpose': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_category': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_legalbasis': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_retention': ProcessingActivity.objects.get(id=self.kwargs['pk']), }) return initial This code works but I suspect there is a cleaner way to reach the same result and I don't find it. Could someone enlighten me please? Thank you very much ! -
Best Way To Manage Model Instances Based On Attributes In Django Admin
Lets say I have a model: class Applicant(models.Model): name = models.CharField() status = Models.CharField(choices=Choices) Lets say Choices gives the choices of Reviewed, Rejected, Accepted. I want to be able to declare a choice for an instance in the admin panel, and once I save the choice, the instance is moved to another section, preferably another admin folder such as Reviewed Applicants, Rejected Applicant, etc etc. Whats the best way to achieve this? Thank you -
Cron jobs from DB in Django
I have some DB records like class Rules(models.Model): server = models.ForeignKey(Servers, on_delete=models.CASCADE) rule_text = models.CharField(max_length=2000) i.e. some rules, linked with server. Each rule is a crontab string like 0 9-17/2 * * 1-5 I want to call server_stop(server) and server_start(server) basing on all the rules, I have in DB (and add/edit/delete rules) Is it possible? -
Django serializer not returning all fields in response
I have following serializer in Django. The serializer is however not returning all the fields in the response. 'amount' and 'amount_ordered' are not returned, all other fields are.. key point: these are the only 2 fields I have in my model. So I thought I only need to add them in the fields list? class AdminOrderItemSerializer(serializers.Serializer): purchase_order = serializers.CharField(source="get_purchase_order") reference = serializers.CharField(source="get_reference") class Meta: model = OrderItem fields = [ "purchase_order", "reference", "amount", "amount_ordered", ] def create(self, validated_data): pass def update(self, instance, validated_data): pass Model: class OrderItem(models.Model): ordered_amount = models.IntegerField(validators=[MinValueValidator(0)]) amount = models.IntegerField(default=0) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) def get_purchase_order(self): return self.order.purchase_order def get_reference(self): return self.order.reference -
Is it possible to add permission to a group given by the admin to see this view?
I have a problem with adding permission for a group of users ('judges') and I would like to ask if there is any possibility to add such a decorator enter image description here enter image description here -
How to run a python script in the background django
I have a python script (ml.py)that generates some data. I want it to run it in the background daily at 1 AM. How to achieve that ? I tried installing django-background-tasks and created the following files tasks.py from background_task import background @background(schedule=1) def hello(): execute('./scripts/ml.py') hello(repeat=Task.Daily) In the shell, I executed the following command: python manage.py process_tasks Now I get an error saying that the name execute is not defined My other questions are : Do I have to write the command python manage.py process_tasks everyday ? Can I exit out of the command window and does the process still run everyday ? -
Django radio buttons appearing as bullet point list, inside mark_safe()
Background I have used 'mark_safe()' inside a form in order to display bullet points in my form label: class FormFood(forms.Form): CHOICES = [ (1,'Yes'), (2, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect, label=mark_safe("Do you like any of these foods? <ul><li>Pasta</li><li>Rice</li><li>Cheese</li><</ul>"), choices=CHOICES) This outputs as: The problem As you can see above, bullet points are now also appearing next to 'Yes' and 'No' despite me not wanting this. Inspecting the elementing reveals that this is because they are also structured inside an unordered list tag (somehow?): <form method="POST"> <label for="id_response_0">Do you like any of these foods? <ul> <li>Pasta</li> <li>Rice</li> <li>Cheese</li> </ul> </label> <ul id="id_response"> <li> <label for="id_response_0"> <input type="radio" name="response" value="1" required="" id="id_response_0"> Yes </label> </li> <li> <label for="id_response_1"> <input type="radio" name="response" value="2" required="" id="id_response_1"> No </label> </li> </ul> <input type="hidden" name="csrfmiddlewaretoken" value="FaOTY4WlVLFMl3gNtut8BJihJKub1Is0wRJRxxLck1e2eJocJVXRiGoOLDr9jdvx"> <input type="submit"> </form> Is there a way I could stop this and just maintain the bullet points on the 'Pasta', 'Rice' and 'Cheese' whilst removing the bullet points/ list from 'Yes' and 'No'? -
IndexError: pop from empty list Django Rest Framework
I have an existing object but I want to create an object in the nested serializer, unfortunately, I am getting an error while creating object. What I have done so far here: class AppealSerializer(serializers.ModelSerializer): resolutions = ResolutionSerializer(many=True, allow_null=True, required=False) class Meta: model = Appeal fields = ['id', 'appeal_unique_id', 'short_name', 'category', 'dept', 'state', 'appeal_desc', 'location', 'address', 'created_at', 'updated_at', 'resolutions', 'user'] def update(self, instance, validated_data): bp_data = validated_data.pop('resolutions', []) bps = (instance.resolutions).all() bps = list(bps) instance.state = validated_data['state'] instance.save() for b_p in bp_data: bp = bps.pop(0) bp.user = b_p.get('user', bp.user) bp.comment = b_p.get('comment', bp.comment) bp.is_read = b_p.get('is_read', bp.is_read) bp.save() return instance here I am going to create many to one object by updating an existing object. with this code, in another project, I can cope with it but it does not work for this project. please if anything is not clear let me know I will try to explain in more detail. The keyword is to create an object by updating an existing object. Thanks in advance -
Tell Django tests.py to use fixture instead of actual database
I need to test my database without adding or deleting elements. For this I have created a fixture. Loading the fixture seems to be fine, at least it is not giving any errors. Now, how do I tell the test functions to interact with the test database instead of the real database. Also, how do I propagate this infomration to the functions that are being tested? This is my current code: """Module to test upload app.""" import os import wave from django.test import TestCase, Client from django.urls import reverse, resolve from equestria.settings import BASE_DIR from .views import UploadProjectView from .models import File from django.core.management import call_command from scripts.models import Project from django.core.files.uploadedfile import SimpleUploadedFile class TestUpload(TestCase): """Test the upload app.""" fixtures = ['equestria/upload/db.json'] def setUp(self): self.project = Project.objects.all()[0] self.url = reverse('upload:upload_project', args=[self.project]) self.client = Client() def test_upload_url_resolves(self): self.assertEquals( resolve( self.url ).func.view_class, UploadProjectView) def test_redirect_before_auth(self): response = self.client.get(self.url, follow = True) redir_url = response.redirect_chain[0][0] redir_code = response.redirect_chain[0][1] self.assertRedirects(response,'/accounts/login/?next=/upload/1',status_code=302, target_status_code=200) self.assertEqual(redir_code, 302) self.assertEqual(redir_url, '/accounts/login/?next=/upload/1') def test_valid_file_ext_upload(self): self.client.login(username='test', password='secret') initial_files = len(File.objects.all()) audio_file = wave.open(os.path.join(BASE_DIR, "upload/test_files/test.wav"), "rb") data = { 'f':audio_file } response = self.client.post(self.url, data, format='multipart') current_files = len(File.objects.all()) print(initial_files) print(current_files) self.assertEqual(initial_files + 1, current_files) self.assertEqual(response.status_code, 200) All tests run just fine …