Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to return pandas null check (df.isnull().sum()) result in django and show on the screen?
I am building a website that shows the missing data statistic. I am using pandas in Django to show missing data statistics of excel files. My view.py file def missing_info(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] df = pd.read_excel(file) missing_data = df.isnull().sum() dic_result = {'data': missing_data} return render(request, 'report.html', dic_result) return render(request, 'upload.html') Report.html file <h1> Missing Data Report </h1> {% for info in data %} {{info.0}} <br> {% endfor %} <p> I noticed that it is taking the displaying missing data space on the screen</p> I am able to return the missing data statistic to report.html but it isn't displayed on the screen. I noticed that missing data statistics displaying on the screen but blank data. website with blank data image -
Django IntegrityError manytomany field
I'm trying to implement hashtags in my django app I have a message model with a field like this hash_tags = models.ManyToManyField(HashTag, related_name='message_hash_tags') And this is the HashTag model hash_tag = models.CharField(max_length=140, primary_key=True) And I'm setting the hashtags to the message like this hash_tags_list = Functions.extract_hashtags(message["message"]) hash_tags = [HashTag.objects.get_or_create(hash_tag=ht) for ht in hash_tags_list] messageObj.hash_tags.set(hash_tags) messageObj.save() But this errors out django.db.utils.IntegrityError: insert or update on table "messaging_message_hash_tags" violates foreign key constraint "messaging_message_ha_hashtag_id_068959e9_fk_messaging" DETAIL: Key (hashtag_id)=((<HashTag: HashTag object (skills)>, True)) is not present in table "messaging_hashtag". Tho I can find the HashTag object (skills) in my messaging_hashtag table: SELECT * FROM messaging_hashtag; hash_tag ---------- skills -
How to filter ManyToManyField in serializer
In my code ServiceListSerializer(many=True, source='service_id') is giving all the services list, instead of services according to its category I have no idea how to retrieve and filter from manytomany field Heres my code: Models.py class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.CharField(max_length=5000, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) View.py class ServicesList(viewsets.ViewSet): def list(self, request): variant_id = request.data.get('variant_id') queryset = Category.objects.all() querysetSerializer = CategoryServiceListSerializer(queryset, many=True, context={'variant_id': variant_id}) return Response({"status": 200, "message": "Success", "data": querysetSerializer.data}) Serializer.py class CategoryServiceListSerializer(serializers.ModelSerializer): variant = serializers.SerializerMethodField() def get_variant(self, instance): variant_id = self.context.get('variant_id') if variant_id: variants = instance.variant_set.filter(pk=variant_id) else: variants = instance.variant_set.all() return VariantServiceSerializer(variants, many=True).data class Meta: fields = ("category_id", "category_name", "category_icon", "category_description", "variant") model = Category class ServiceListSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class VariantServiceSerializer(serializers.ModelSerializer): services = ServiceListSerializer(many=True, source='service_id') # services = serializers.SerializerMethodField() class Meta: model = Variant fields = "__all__" # def get_services(self, obj): # print(obj.service_id) … -
Understanding Django Forms
I am trying to learn server side development of websites. In particular I am looking at forms and acquiring user data. I am trying to learn Django but I am not sure my understanding of the flow with Django forms. Is the following correct? Django forms are a back end application which generates an html form. A user on the client side will click a button such as "Sign Up" which will then trigger a script involving Django forms. The forms module will generate an html form which will be including in the http response that is sent back to the user. Is this correct? Or do html and Django forms conflict? That is, we can only use one? I have tried reading the documentation but it is not helping me understand. TLDR: What is the flow diagram for a dynamic website where we generate forms using Django? -
Similar field to ArrayField in Django to use with SQL Server
I want to connect my Django backend to SQL Server but one of my models require a an array field like the one from PostgreSQL so is there an alternative? -
iterate horizontally through a Django QuerySet
I am working with a sql table and want to iterate through it horizontally. I am currently using the django Q library to create query sets: I am creating and filtering the QuerySets by doing : filtered_table = NewTables07.objects.filter(criterion_date & criterion_location) The model looks like: class NewTables07(models.Model): TestDate = models.CharField(max_length=200) Division = models.CharField(max_length=200) Library = models.CharField(max_length=200) ID = models.CharField(max_length=200) mono_full = models.CharField(max_length=200) mono_simple = models.CharField(max_length=200) mono_brief = models.CharField(max_length=200) mono_complex = models.CharField(max_length=200) mono_vendor = models.CharField(max_length=200) mono_asc = models.CharField(max_length=200) mono_added = models.CharField(max_length=200) class Meta: db_table = 'stat_cat1' I am aware that I can iterate through columns by doing something like: for i in filtered_table: print(i.<column title>) but if i wanted to iterate through the table horizontally, like through the headers for example : 'ID' then 'Library' 'mono_full' ... How would I go about doing that ? -
ValueError: I/O operation on closed file. when saving the qr code to database in Django
Here i want save my qr_code to database but i am facing the following error ValueError: I/O operation on closed file. def qr_code_file_name(instance, filename): return '%s/qr_codes/%s/' % (instance.client_id, filename) class ProductItems(models.Model): item_name = models.CharField(max_length=512) qr_code = models.ImageField(upload_to=qr_code_file_name, blank=True, null=True) def __unicode__(self): return self.item_name def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.item_name) canvas = Image.new('RGB',(90,90),'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = File('qrcode-code1.png') buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname,File(buffer),save=False) canvas.close() -
how to verify the csrf token is working well in the browser while using django and react
I am sorry in advance if the question is more a beginner one but i have built an application with django backend and react frontend, now i am trying to implement the csrf token for the post request on the create endpoint with the codes below. getCookie.js import React from 'react'; const getCookie = (name) => { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const 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; } export default getCookie; CsrfToken.js import React from 'react'; import getCookie from './getCookie'; var csrftoken = getCookie('csrftoken'); const CSRFToken = () => { return ( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} /> ); }; export default CSRFToken; Create.js import React from 'react'; import axios from "axios"; import CsrfToken from './CsrfToken'; const Create = () => { ... const options = { headers: { 'Content-Type': 'application/json', } }; const handleSubmit = (e) => { e.preventDefault(); axios.post("http://xyz/create/", fields, options) .then(response => { ... }; return ( … -
Django update_or_create raises IntegrityError within Serializer
I have the following ModelSerializer with a create method. In this method I call the model's update_or_create method. But when I do this, the serializer's validation raises the error rest_framework.exceptions.ValidationError: [{'non_field_errors': [ErrorDetail(string='The fields user_id, capacity_id must make a unique set.', code='unique')]}, {}]. I thought that since I'm using update_or_create, it would find the row that matches validated data's user_id and capacity_id, and then update that row. But the validation runs before create, and the data is not valid because of the unique constraint. So how do I ignore this constraint? class ActivatedCapacitySerializer(serializers.ModelSerializer): user_id = serializers.IntegerField(required=False) capacity_id = serializers.IntegerField(required=False) class Meta: model = ActivatedCapacity fields = ('user_id', 'capacity_id', 'active') def create(self, validated_data): activated_capacity = ActivatedCapacity.objects.update_or_create( user_id=validated_data['user_id'], capacity_id=validated_data['capacity_id'], defaults = { 'active': validated_data['active'] } ) return activated_capacity Models.py class ActivatedCapacity(models.Model): user_id = models.IntegerField() capacity_id = models.IntegerField() active = models.BooleanField(default=False) class Meta: unique_together = ('user_id', 'capacity_id',) -
dj-rest-auth, email expiration time less than one day
As title says, it's possible to set email confirmation link expire time less than one day? Specifically for dj-rest-auth so far I only found ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 90. Django password has such https://docs.djangoproject.com/en/3.2/ref/settings/#password-reset-timeout for password reset. But I cannot find anything related to email expiration from both official docs/Githubs for this simple task. -
Nginx Static Files doesn't load Django
Nginx won't load Django static files. Nginx config: upstream backend { server localhost:8000; } server { server_name wavera.ru www.wavera.ru; location / { include proxy_params; proxy_pass http://backend; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.wavera.ru/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.wavera.ru/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location /static/ { alias /root/labelEngine/labelApp/static/; } location /media/ { alias /root/labelEngine/media/; } } server { if ($host = wavera.ru) { return 301 https://$host$request_uri; } if ($host = www.wavera.ru) { return 301 https://$host$request_uri; } listen 80 ; server_name wavera.ru www.wavera.ru; return 404; } settings.py of static files: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" And also urls have: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Otherwords, i just want to turn off debug mode and make sure my website and static / media files work correctly. I try to do this by whitenoise, but its didnt support media files, so i try to set up nginx config. What i am doing wrong? -
Serializer's create method with many=True
I have the following model serializer with a create method. class ActivatedCapacitySerializer(serializers.Serializer): class Meta: model = ActivatedCapacity fields = '__all__' def create(self, validated_data): activated_capacity = ActivatedCapacity.objects.update_or_create( user_id=validated_data['user_id'], capacity_id=validated_data['capacity_id'], defaults = { 'active': validated_data['active'] } ) return activated_capacity Models.py class ActivatedCapacity(models.Model): user_id = models.IntegerField() capacity_id = models.IntegerField() active = models.BooleanField(default=False) When I try to create instances in bulk with many=True, I have the error KeyError: 'user_id'. Since I used many=True, the serializer's validated data is a list of OrderedDict, so I should iterate over this list in the create method to create the instances? Shouldn't Django Rest Framework handle this by itself? If so, how do I do it? -
How to hide the Token model from rest_framework.authtoken in django admin panel
I tried to solve the problem using this two methods from rest_framework.authtoken.models import Token admin.site.unregister(Token) ----- from rest_framework.authtoken.models import TokenProxy admin.site.unregister(TokenProxy) But the response is a mistake that says "The model Token is not registered" -
Upload and process files on Django results in 500 error when deploy on Heroku
The website is: https://atw.herokuapp.com It allows users to drop in Microsoft Word files, and once Django receives files, it processes them. I use React to build my frontend, and the code responsible for making the POST request once the user dropped in files is: const onDrop = useCallback((acceptedFiles) => { // Do something const csrftoken = Cookies.get("csrftoken"); var form_data = new FormData(); for (var i = 0; i < acceptedFiles.length; i++) { form_data.append("atw", acceptedFiles[i]); } axios .post("https://atw.herokuapp.com/upload/", form_data, { header: { "content-type": "undefined", "X-CSRFToken": csrftoken, }, }) .then((res) => { window.open("https://atw.herokuapp.com/download/"); }) .catch((e) => console.log(e)); }, []); I have a Django view that handles uploaded files: class Upload(APIView): """ Process Microsoft Word files received through POST requests """ def post(self, request): form = DocumentForm(request.POST, request.FILES) if form.is_valid(): STATE['status'] = 'processing' for f in request.FILES.getlist('atw'): newfile = Document(docfile=f) newfile.save() output_filename = "OUT-ATW.docx" processor = FilesProcessor(output_filename) processor.process() STATE['status'] = 'done' return HttpResponse("Successfully processed files!") else: form = DocumentForm() return render(request, 'myapp/index.html') I use django-cors-headers to handle CORS headers and all that, and have whitelisted herokuapp in my settings.py: ALLOWED_HOSTS = ['.herokuapp.com', '127.0.0.1'] The Problem It works fine locally, but after I deployed the project on Heroku, I cannot upload files successfully. You … -
Django Migration questions
I am new to Django, but every time I do any change to the models, I need to do 'python manage.py makemigrations' then 'python manage.py migrate' makemigrations will create new files under migrations folder: 0001_xx 0002_xx 0003_xx ... My question is, is this the right way to do it? Because if every time there is a change to the DB model, then a new migration file is created, in the end I could end up having many migration files. Then how to do migration when I want to move to production? Just run the 'python manage.py migrate'? -
Is it possible to prepopulate Django FormSets with FileFields?
Thanks for stopping to take the time to read my question. Here's my issue. I am creating attachments on a form. Multiple. All is well and good. Here's the problem...I want to "GET" those attachments on an update form so that they are displayed and can be deleted if the form is approved. This is proving challenging. I am prepopulating forms in some cases by using a dictionary to get the data that I need as initial data. All is working as expected except for FileFields or FieldFile as Django references it. I have read a few similar articles on SO...but nothing is helping. I understand the security issues and I am not trying to "FORCE" uploads..I simply want to grab the attachment name and copy it to another model essentially. My form submits, but the attachments are not being processed. Here's my code.... HTML... <form method="POST" enctype="multipart/form-data" id="forms"> {{ procedure_attachment_form.management_form }} {{ procedure_attachment_form.non_form_errors }} {% for fileform in procedure_attachment_form.forms %} {{ fileform.id }} <div class="inline {{ procedure_attachment_form.prefix }}"> {{ fileform.attachments }} {% if procedure_attachment_form.non_form_errors %} <h3 class="spacer174"> {{ procedure_attachment_form.non_form_errors }} </h3> {% endif %} {% if fileform.attachments.errors %} <h3 class="spacer174"> {{ fileform.attachments.errors }} </h3> {% endif %} {{ fileform.procedure.as_hidden … -
how to create foreign key from multiple models on single field in django
i have multiple models like, class Service1(models.Model) class Service2(models.Model) class Service3(models.Model) class Service4(models.Model) class Orders(models.Model): user = models.ForeignKey(User, on_delete=models.CASECAD) orders = models.ForeignKey((Service1, Service2, Service3, Service4), on_delete=models.CASECAD) how is this possible to create orders with different services like above -
Django query performance slow unless limited
I have a relatively simple view that I use for AJAX requests that takes a simple ORM query and renders it as a string. I did not include the building of the params as I have tested the method and isolated the issue to rendering the query results in the template. Products.objects.filter(**params) return render_as_string('templates/product.html', {'products': products'}, request) The query returns 1255 records, which isn't really much, but takes 31 seconds to complete the AJAX request. However, if I slice/limit the query to 1255 rows as follows: Products.objects.filter(**params)[:1255] return render_as_string('templates/product.html', {'products': products'}, request) then the AJAX request will only take 1.2 seconds. Still less than ideal but I can at least work with that. I plan on setting up pagination to get the time to a comfortable level but I am confused to the underlying issue. I am feeding the same number of rows to render as string. -
How to pass a URL value from a template to a form_valid method inside a Class Based View in Django
I started working with django and I have come across a problem that I am not able to solve. I believe this should be easy but I cannot figure it out. I am getting an Id from a template which I pass through a URL. data.html ... <div class="container"> <form method="GET" action="{% url 'data:next' %}"> <input type="hidden" required name='job_id'> <button type="submit" class="btn btn-primary">Run Next</button> {% csrf_token %} </form> </div> ... url.py app_name = "data" urlpatterns = [ ... ... path('next/', RunNextView.as_view(), name='next'), ] This seems to pass the job_id value to the URL as after selecting a checkbox (in this case with job_id pointing at 44) and clicking on the Run Next button I get to a url such as: http://localhost:8000/data/next/?job_id=44&Some-token which I think is good. Now I want to pass the number 44 to a class based view which is the problem and I was not able to do it. As shown below I need the job_id in order to run the run_next_task task. How do i grab that 44 and pass it to the form_valid method inside the CBV ? views.py class RunNextView(FormView): template_name = 'next.html' form_class = RunForm success_url = reverse_lazy('data:list') def dispatch(self, request, *args, **kwargs): if … -
Django forms - need a form that shows a set of questions each question having a list of possible answers
I have the following three models: models.py class Exam(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name="exams") passing_grade = models.IntegerField(default=85) must_pass = models.BooleanField(default=True) to_next_lesson = models.BooleanField(default=True) display_order = models.IntegerField(default=1) class ExamQuestion(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE, related_name="questions") text = models.CharField('Question', max_length=255) class ExamAnswer(models.Model): question = models.ForeignKey(ExamQuestion, on_delete=models.CASCADE, related_name="answers") text = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) The Form I require would render each question in an exam roughly something like this (sorry couldn't figure out to show rendered html in question: <form> <div> "Quality" is one our core values<br /> <input type="radio"/> True <br /> <input type="radio"/> False </div> <div> What should you do if you see an employee stealing?<br /> <input type="radio"/> Report it to your manager<br /> <input type="radio"/> Call the police<br /> <input type="radio"/> Confront the employee<br /> </div> <div> <input type="submit"> </div> </form> Ignoring the incomplete and possibly stupid HTML (shown bare bones here for the concept) How can I get the Django form language to output each individual question with multiple answers beneath it? Note: The number of questions is variable, some exams might have 3 questions, others could have 5 or 6. The number of answers per question is also variable, some questions might have two answers … -
Django, direct download link in email is not working
Django: direct download link in email is not working Hi, I have a view that looks like this: def download_kit(request): file_path = "path/to/my/file" return FileResponse(open(file_path, 'rb'), as_attachment=True) But the link is not working when I send it in an email. What am I doing wrong? The link works well in a normal page, it works if I type the link directly in the browser too. -
ModuleNotFoundError: No module named 'encodings'. Django Deployment with mod-wsgi and apache
I am Deploying the Django project with mod_wsgi and Apache on Microsoft Windows Server 2019. I am unable to find the proper solution to this on the internet. I don't know why mod-wsgi is not loading python modules? Here is my httpd.conf ServerName xx.xx.xx.xx:80 # Django Project LoadFile "C:/Users/abc/AppData/Local/Programs/Python/Python39/python39.dll" LoadModule wsgi_module "C:/Users/abc/AppData/Local/Programs/Python/Python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/abc/AppData/Local/Programs/Python/Python39" WSGIScriptAlias / "C:/inetpub/wwwroot/myproject/django/myapp/wsgi.py" WSGIPythonPath "C:/inetpub/wwwroot/myproject/django/" <Directory "C:/inetpub/wwwroot/myproject/django/myapp/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/inetpub/wwwroot/myproject/django/static/" <Directory "C:/inetpub/wwwroot/myproject/django/static/"> Require all granted </Directory> When I run command: ./httpd.exe -k start I get this error in logs. And the server doesn't start. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 6896:tid 552] AH00455: Apache/2.4.49 (Win64) mod_wsgi/4.9.0 Python/3.9 configured -- resuming normal operations [Tue Sep 28 19:25:46.975430 2021] [mpm_winnt:notice] [pid 6896:tid 552] AH00456: Apache Lounge VS16 Server built: Sep 12 2021 10:23:43 [Tue Sep 28 19:25:46.975430 2021] [core:notice] [pid 6896:tid 552] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Tue Sep 28 19:25:46.991023 2021] [mpm_winnt:notice] [pid 6896:tid 552] AH00418: Parent: Created child process 9780 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix … -
Django how to show choices in select input
how can I show my choices in the "select" input for a form? And why can't I access the DateInput to set a Input as a datepicker in the form, like I do for "grund" as "Select"? Code: from django import forms from django.forms.widgets import DateInput from .models import expense class DateInput(forms.DateInput): input_type = 'date' class ExpenseForm(forms.ModelForm): class Meta: model = expense CHOICES = ( ('ME', '1'), ('YOU', '2'), ('WE', '3'), ) fields = [ 'datum', 'grund', 'beschreibung_grund', 'summe_ausgabe' ] widgets = { 'datum': DateInput(), 'grund': forms.Select } -
NGINX/gunicorn - password protect whole Django website using NGINX conf
I need to temporarily password-protect a running website using basic auth. The website shouldn't be accessed by anybody (not even existing users) except those who have given credentials, let's say: USERNAME: 'xxx' PASSWORD: 'yyy' I know I can password-protect directories that are indexed by NGINX but is this also possible for NGINX/gunicorn? server { listen 80; server_name www.mysite.com; return 301 $scheme://mysite.com$request_uri; } server { listen 80; server_name www.mysite2.com; return 301 $scheme://mysite2.com$request_uri; } server { server_name mysite2.com mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/futilestudio/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.com-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.com-0001/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } -
django pytest case fails while postman does not
I am writing a test for an API using Django rest framework. The user has to register and then login to acces my endpoint. If I register (post) with postman, then login (post) and I get the access_token that I consequently pass to the post request I get a 200. Also using curl curl --location --request GET 'localhost:8000/api/v1/signals/' \ --header 'Authorization: token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE2MzI4NTc2MzIsImlhdCI6MTYzMjg1NzMzMn0.WCjjg3jSZ4TO_Q51hGwZmj04iFeV9ffRnp9GaFch_IM' \ --header 'Cookie: csrftoken=HrgKpprN95ExIPmm6Y2Qqc3WvDrfqQRgqUY9v4bTN9gT7nETEuBjhtY6IS7Sv9Ky; sessionid=ml04spqh6gmjuicp8vnda1t0lqopnuvx' \ --data-raw '' but If I write a test, it fails def test_get_signal(client): form_data = { "username": "testuser", "password": "mytestpassword", } CustomUser.objects.create_user(**form_data) response = client.post("/accounts/login/", form_data, follow=True) assert response.status_code == 200 response_content = json.loads(response.content) token = response_content["access_token"] headers = { "Authorization": "Token " + token, "Content-Type": "application/json", } response = client.get( path="/api/v1/signals/", headers=headers, ) assert response.status_code == 200 I get a 403. what am I doing wrong?