Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django celery/Celery to send emails at a particular time
I want to use celery to handle sending of mails at a particular minute, hour or day. I set up CELERYBEAT_SCHEDULE to send the mails every 30 minutes but it doesn't work, rather it sends in less than 30seconds. I also set up crontabs and periodic tasks in my django admin but it doesn't work. I really don't know what I am doing wrong. It's my first time working with celery. Here are my codes: settings.py from __future__ import absolute_import from celery.schedules import crontab INSTALLED_APPS = [ 'djcelery', ........, ] BROKER_URL = 'redis://h:pa318d80536cde1a525616ac73eeb981a1b57cab3b72d4@ec2-107-21-8-30.compute-1.amazonaws.com:25389' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' import djcelery djcelery.setup_loader() CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERYBEAT_SCHEDULE = { 'add-every-30-minutes': { 'task': 'nueoffshore.tasks.SendEmailTask', 'schedule': crontab(minute='*/15'), 'args': (16, 16), }, } celery.py from __future__ import absolute_import from django.conf import settings import os from celery import Celery, signals # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mycareer.settings') os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('mycareer') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from celery import task from celery.task import Task from django.core.mail import EmailMessage class SendEmailTask(Task): def run(self, content): … -
Send email to address getting from HTML input via Django
I'm searching for solution to this problem for many hours but can't find anything related. I want to get user's email from input and send mail from admin to that email address. Here are my codes: views.py: def index(request): context = { 'questions': Question.objects.all(), 'applicants': Applicant.objects.filter(status=1), 'empty_cards': range(4 - Applicant.objects.filter(status=1).count()) } if request.method == "POST": if request.POST.get('message_text'): Message.objects.create( sender_name = request.POST.get('sender_name'), sender_email = request.POST.get('sender_email'), message_text = request.POST.get('message_text')) if request.method == 'POST': subject = 'Welcome !' message = 'We will back to you.' from_email = settings.EMAIL_HOST_USER recipient_list = 'don't know how to get email' send_mail(subject, message, from_email, recipient_list) return render(request, 'index.html', context) -
What kind of view is best for handling a form posted 'message' from a DetailView template in django
I have a Model 'Vacancy' and I have a DetailView that shows an instance of vacancy in the template 'vacancy_view.html'. This works fine Also in this template 'vacancy_view.html' I added a small form. So a user can write a message for this vacancy. <form action="{% url 'message_create' %}" method="post" > {% csrf_token %} <input type="hidden" name="vacancy_id" value="{{ vacancy.id }}"> <textarea name="message" cols="10" rows="4"></textarea> <button class=" btn btn-primary mt-3">Verstuur</button> </form> This form posts th 'id' of the current vacancy in a hidden field and the message is a large textfield as you can see. I have set up the urls.py so it can find the right view. The message should be saved in a new instance on a ManyToMany model that I have set up between 'Vacancy' and 'User'. In the View I have to : -1- compute the form-data, -2- create a new instance of Message and save it and -3- create the right succes url. I want to do this with a Class based View. Can this be done with a FormView? After half a day trying to get this to work I am totally lost. It seems like a standard problem. How is this best done. All the … -
Django model error. `no such table: django_session`
Making a simple Django model and showing the data on one page. After messing up my model, I commented the bad code out, removed all migration files except the __init__.py file, and deleted the db.sqlite3 (as described here: https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html). However, I started getting this Error no such table: django_session on my admin page. I still have 17 unapplied migration(s) How I messed up the model? I put in DecimalType without a default, the CLI gave me three options: they assign a value, I assign a value, or leave it blank. I chose the first option and ever since I've gone down the rabbit hole 🐇HELP It has been suggested that the route to my db.sqlite3 is wrong so here's my file tree and settings code: Model from django.db import models from django.conf import settings from django.utils import timezone from multiselectfield import MultiSelectField from decimal import Decimal class BuildingProduct(models.Model): # CHOICES SCHOOL_CHOICES = [ ('MBO', 'MBO'), ('VMBO', 'VMBO'), ('HBO', 'HBO'), ('OPLEIDINGSBEDRIJF', 'Opleidingsbedrijf'), ] CATEGORY_CHOICES = [ ('MATERIALS', 'Materials'), ('COURSE', 'Course'), ] # DATABASE FIELDS name = models.CharField(max_length=200) description = models.TextField() categories = MultiSelectField(choices=CATEGORY_CHOICES, blank=True) schooltype = models.CharField( max_length=20, choices=SCHOOL_CHOICES, default='MBO', ) # price = models.DecimalField( # max_digits=10, decimal_places=2, default=Decimal('0.0000') # ) … -
how to install msodbcsql17_17.4.2.1-1.deb driver for django mssql connection?
i am trying to connect django with MSSql server database using pip3 install django-pyodbc-azure but when i install driver msodbcsql17_17.4.2.1-1.deb it produce following error : Selecting previously unselected package msodbcsql17. (Reading database ... 340765 files and directories currently installed.) Preparing to unpack msodbcsql17_17.4.2.1-1.deb ... Unpacking msodbcsql17 (17.4.2.1-1) ... dpkg: dependency problems prevent configuration of msodbcsql17: msodbcsql17 depends on unixodbc (>= 2.3.1); however: Package unixodbc is not installed. dpkg: error processing package msodbcsql17 (--install): dependency problems - leaving unconfigured Errors were encountered while processing: msodbcsql17 any possiblity to connect django with mssql-server ? -
VS Code Python Django debugging in a dev container
I am developing a Python Django app in a Dockerized container. I have successfully setup remote debugging to attach to my Django server inside of a container. Me configuration is as follows. launch.json { "name": "Remote Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/app" } ], "port": 9001, "host": "localhost" } manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'llf_api.settings') try: from django.core.management import execute_from_command_line from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 8001)) print("Attached remote debugger") except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() docker-compose.yml services: api: image: ${DOCKER_IMAGE_BASE}:${DOCKER_TAG} build: context: . dockerfile: ./Dockerfile.development env_file: - .env environment: - DATABASE_URL=postgres://username:password@db/db_name volumes: - .:/app command: > bash -c "wait-for-it --service db:5432 && python3 manage.py runserver 0.0.0.0:8000" ports: - "9000:8000" - "9001:8001" depends_on: - db tty: true stdin_open: true The problem is that I run VS Code inside of a dev container (the Dockerfile.development above). So VS Code is essentially running … -
Resolving Missing Variable on Django Form
I'm restructuring an e-commerce that is using saleor 1.0. What I'm trying to achieve is reducing the redundancy in the steps to make a payment on an item. The architecture for checkout/payment for saleor 1.0 requires the customer from the payment page to go to a separate page to select payment a type (e.g. stripe, braintree, razor etc) using a radio button and then submit that selection which then processes the order and goes to the confirmation page. OBJECTIVE: What I'm trying to do is remove the step of sending the customer to a page to select their payment type, but rather include that option on the payment page, which i feel makes the experience more seamless. ISSUE: When including stripe to the payment page, I am receiving an error message which is displayed on the page: << MISSING VARIABLE "form.payment_method_id.as_hidden" >> Also, stripe appears to be functioning, but when i submit credit card information i'm not redirected to the confirmation page. Payment.html - the syntax commented is what shipped with saleor: {% block paymentcontent %} <div class="row checkout"> <div class="col-lg-10 m-auto checkout__payment"> {% if order.user == user or not order.is_fully_paid %} {% if not order.is_fully_paid and order.billing_address %} {% … -
How can I create a (select image) like field inside django form?
I am creating an order-app which enables the user to order custom name tags. I need to create a field that enables the user to select his/her desired background. Every background will have a key or id. I am currently representing this field using a PositiveIntegerField because there is going to be a 100 plus backgrounds so it is time-consuming to import them as choices inside a list. from django.db import models class Sticker(models.Model): Lan = [ ('ar', 'عربي'), ('en', 'English'), ] name_field = models.CharField(max_length=40) school_field = models.CharField(max_length=40) grade_field = models.CharField(max_length=40) quantity = models.PositiveSmallIntegerField() language = models.CharField(choices=Lan, max_length=2) sticker_number = models.PositiveIntegerField() #image = models.ImageField(max_length=1, null= True) status = models.BooleanField(default=False) and this is how the form looks like, just used a simple ModelForm class to pass the fields. from .models import Sticker, CustomerDetails, DeliveryDetails class Meta: model = Sticker fields = ('name_field', 'school_field', 'grade_field', 'quantity', 'language', 'sticker_number') So I need a way to show the user images and to be able to select an image. I am trying to build this project without using previously build templates or forms and I am still a beginner in python and django. -
Django global camera device object
I'm using a camera device to capture images and display them on in my django web app. I can only create one instance of this device or else it will give an error saying the device is already attached to another client. My understanding is if django spawns multiple processes, the same code will be executed multiple times, which is what I don't want to happen. What is the best way to set this up so I can get images from the device, but without django attempting to create multiple instances of the device object? -
Django Crispy Forms CustomLayout with Fieldset
So I want to build a custom layout, that extends LayoutObject for a form that I have. class NewBookForm(LayoutObject): template = 'library/layouts/new_book_layout.html' def __init__(self, fields, template=None, *args, **kwargs): self.fields = fields # Overrides class variable with an instance level variable if template: self.template = template def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) template = self.get_template_name(template_pack) return render_to_string(template, {'fields': fields}) And I'm calling it using self.helper.layout = Layout( NewBookForm(Fieldset('book_id', 'name', 'author)) ) Right now Django is saying "template does not exist." However, this is not getting me the result I'm looking for. -
How to disable options in form based on current data in database in Django?
I have a form where users can enter a timestamp whenever they have messed up the time they submitted previously. I am changing it so that the timestamp submitted can be either an entry or an exit, based on the button the user clicks. Right now, I have two boxes for the user to enter their timestamp, to know whether is an entry or an exit timestamp, like shown below: <div class="checkbox"> <label for="chk"><input type="checkbox" value="0" id="chk" /> Requires manager approval</label> </div> <div style="padding-top: 10px; text-align: center; display: none" id="appreq"> <input type="checkbox" value="0" id="modinchk" /> Modify Entry <div style="display: none" id="modin"> <label>Time In</label> {% standard_input form.modified_in datetimepicker=True hide_label=True %} </div> <input type="checkbox" value="0" id="modoutchk" /> Modify Exit <div style="display: none" id="modout"> <label>Time Out</label> {% standard_input form.modified_out datetimepicker=True hide_label=True %} </div> </div> Is there a way to change it so that there is some sort of temporary variable, so that I can have only one box where they enter the date/time and when they click either enter or exit, the temporary variable data moves to either modified_in or modified_out? I imagine this second part would be handled in views, but I don;t know how I can have a temporary variable instead … -
Send email to application users via Djano
So, in my case users enter their name, email, motivation letter and so on. When they click button, the users only with status=3 should accept email from admin's email address. I did this task as follows, but can't get any email. index.html: <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <input type="text" name="name" required minlength="3"><br /> <input type="email" name="email" required minlength="10"><br /> <textarea rows="5" name="motivation_letter" required></textarea><br /> <input type="submit" value="Send" class="apply-button"> </form> models.py: class Applicant(models.Model): name = models.CharField(max_length=20) birth_date = models.DateField(blank=False) email = models.EmailField(max_length=40) motivation_letter = models.TextField(max_length=200) status = models.ForeignKey(ApplicantStatus, on_delete=models.CASCADE, default=3) def __str__(self): return self.name views.py: def email(request): if request.method == 'POST': subject = 'Welcome!' message = 'We'll back to you.' email_from = settings.EMAIL_HOST_USER recipient_list = request.POST['sender_email'] send_mail(subject, message, email_from, recipient_list) return redirect('index.html') urls.py: urlpatterns = [ path('', views.index, name='index'), path('', views.email, name='email'), ] -
Use of parameters in URL depending on their existence django rest framework
I'm using DRF and Django, I have uid and full_name in my database, how to insert parameters into the URL depending on their emptiness or on None? For instance if full_name of record is None or is empty string then url should be like this: http://localhost:8000/something/{uid} Else if full_name is okay then url should be like this: http://localhost:8000/something/{full_name} -
Django FullCalendar with Django 2.x or 3.x
Okay, I know that this question has been asked a lot of times, but it seems that I can't understand it by myself. I need to implement FullCalendar into my Django application, and after I downloaded FullCalendar with all the statics and stuff, and after rendered it on my page, I just can't add new Events by any chance. I have my Event model, with start_date, end_date, id, and title, like someone explained it here. After that, I made a function in my views.py called all_events, where event = Event.object.all(), and put that in the context variable. I have no forms at this time, I just want to render it after I enter the data from my admin page - for now. Want to be as simple as possible. This is my code : models.py class Events(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name views.py def events(request): all_events = Events.objects.all() context = { "events": all_events, } return render(request, '.../selectable.html', context) urls.py path('.../add_event', add_event, name='add_event'), And my html page : {% block content_row %} <!DOCTYPE html> <html> <head> <script src="{% … -
What's the best way to handle(or alternative) the use case of creating multiple table from single model in Django
I have a use-case where a client registers to my platform and I have to give them a separate table in a database using a common model in Django. Although I have been able to create multiple tables from a single model on runtime, I don't think its the best solution to the problem and I have seen some issues with it on my testing like when doing migrations of the model and Django admin pages, etc. Are there any other alternatives to this problem? How do other companies handle such issues? -
Loading audio file to template causes ConnectionResetError: [Errno 54] Connection reset by peer (Django, Python)
I am making an audio player webapp using Django. The audio files are uploaded by admin via a model that adds the file to my Media directory. Then in my template the audio files are displayed with an individual audio player. {% for song in songs %} <audio class="player" controls> <source src="{{ song.audio_file.url }}" type="audio/wav"> </audio> {% endfor %} Now, the website works as intended. The audio players all become visible and are working correctly. However in my terminal, every time the page is loaded I get errors of this type (depending on how many audio files that are to be displayed, if there only is one file i get this for example): [13/Dec/2019 12:03:31] "GET /media/ap/song.wav HTTP/1.1" 200 1626112 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 60242) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 696, in __init__ self.handle() File "/Users/oscarjonsson/python-virtual-environments/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/oscarjonsson/python-virtual-environments/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer What could be the cause of this? Would appreciate any … -
Converting a String into Datetime with Hour and Minute
In my python project, I have a date field: event_date = models.DateField(auto_now=False, default=None, null=True, blank=True) in the controller, I convert string and save as follows: event_date = body["event_date"] # <- string date = datetime.datetime.strptime(event_date, "%Y-%m-%dT%H:%M:%S.%fZ").date() works fine, but it saves as "2019-02-12" - which is also normal date() function returns only that part. What I want is to save as "2019-02-12 20:05". How can I achieve this with Python? Thank you. -
Show user error message if form is not filled via HttpResponseRedirect
I'm trying to create the functionality so that a user is returned to the url with an error message if they don't fill in the forms. My urls from django.urls import path from content import views urlpatterns = [ path('readerpage/<int:content_id>', views.readerpage, name='readerpage'), path('readerpage/<int:content_id>/add_review', views.add_review, name='add_review'), ] My view def add_review(request, content_id): content = get_object_or_404(Content, pk=content_id) if request.POST['readability'] and request.POST['readability_rating'] and request.POST['actionability'] and request.POST['actionability_rating'] and request.POST['general_comments']: review = Review() review.readability = request.POST['readability'] review.readability_rating = request.POST['readability_rating'] review.actionability = request.POST['actionability'] review.actionability_rating = request.POST['actionability_rating'] review.general_comments = request.POST['general_comments'] review.avg = (float(review.readability_rating) + float(review.actionability_rating)) / 2 review.content = content review.save() return redirect('home') else: return HttpResponseRedirect(reverse('readerpage', args=(content_id,))) Right now the user gets returned but doesn't get an error message I've tried with the return render, instead of the HttpResponseRedirect return render (request, 'content/readerpage', {'error': 'You need to fill in all information'}) But that send the user to the wrong url, creating an error, as it adds the add_review to the to URL http://127.0.0.1:8000/content/readerpage/41/add_review Is there any way to pass along the error with the HttpResponseRedirect? Or is there another alternative? Thanks for reading this -
Django - Model is not defined
With the following I get "Plant is not defined" class Resource(models.Model): resources = models.ForeignKey(Plant,related_name='resources',on_delete=models.PROTECT) class Plant(models.Model): resources = models.ForeignKey(Resource,related_name='plant',on_delete=models.PROTECT) When I turn them around, I get "Resource is not defined" Thank you for any help -
When I save a Django model, I get an error with regards to the date time field requiring bytes or string
I am getting an error "TypeError: expected string or bytes-like object" when saving an object. The view looks like: person = Person.objects.get(id=request.data["person_id"]) firstname = request.data["firstname"] lastname = request.data["lastname"] dateofbirth = request.data["dateofbirth"] datetimeDOB = parser.parse(dateofbirth) try: person.firstname = firstname, person.lastname = lastname, person.dateofbirth = datetimeDOB person.save() The model looks like: class Person(models.Model): firstname = models.CharField(max_length=50,default='',blank=False) lastname = models.CharField(max_length=50,default='',blank=False) dateofbirth = models.DateTimeField(null=False) dateadded = models.DateTimeField(auto_now=True) def __str__(self): return self.firstname I have tried adding the date without the parse function, but that still gets rejected. If I forget about updating the dateofbirth field then it saves, but I get strange characters in the firstname and lastname fields. For example "first", "last" becomes "('first');","('last');". If I change the code to create a new person record to test the database object and the posted data using code as below then it creates a new person correctly, "first","last" and dateofbirth correctly formatted as date time. Person.object.create( person.firstname = firstname, person.lastname = lastname, person.dateofbirth = datetimeDOB ); This is why I am really confused as I use the same method to update other objects and don't get this issue. Also if I can create, why can't I update it without these errors? -
Invalid Requirement ERROR while installing a local git repository of Django
I am trying to install the development version of Django in a virtual environment. A local repo lives inside: "C:\Users\AARYAN DEWAN\Desktop\localdjango\django" I first created a virtual environment inside "C:\Users\AARYAN DEWAN\Desktop\virualenvs" using py -m venv .\djangodev. Then I activated it. Now when I try to follow the Django Docs and install the local django repo inside this virtual environment, using py -m pip install -e C:\Users\AARYAN DEWAN\Desktop\localdjango\django, it throws up an error saying: ERROR: Invalid requirement: 'DEWAN\\Desktop\\localdjango' Hint: It looks like a path. File 'DEWAN\Desktop\localdjango' does not exist. I have tried replacing the path with this: py -m pip install -e C:\Users\AARYAN DEWAN\Desktop\localdjango, but it still does not work!? What should I do? -
AttributeError: module 'allauth.models' has no attribute 'Group'
views.py def teachers(request): group = models.Group.objects.get(name='teachers') list_teachers = group.user_set.all() return render( request, 'teachers.html', { 'list_teachers' : list_teachers } ) Internal Server Error: /teachers/ Traceback (most recent call last): File "C:\python 3.7.4\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\python 3.7.4\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python 3.7.4\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Homie\Desktop\defenseMilestone\defense\milestone\views.py", line 55, in teachers group = models.Group.objects.get(name='teachers') AttributeError: module 'allauth.models' has no attribute 'Group' [13/Dec/2019 16:50:51] "GET /teachers/ HTTP/1.1" 500 66823 -
Django ArrayField Filtering with contains matching
I'm using Django Postgres ArrayField response_headers = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) Let's suppose our object has the following data: obj1 : response_headers = ["dubai","sydney","nyc"] obj2 : response_headers = ["mumbai","kerela","dubai"] MyModel.objects.filter(response_headers__contains=['dubai'] would return obj1 & obj2 but MyModel.objects.filter(response_headers__contains=['duba'] won't return any objects <QuerySet []> How do I achieve the ability to search with the partial pattern across all indexes of ArrayField? -
Folder creation in docke-compose volume
I have a Django project running with docker-compose for dev env. I'm struggling with file/folder creation on an aws server (AMI ubuntu-bionic) I mounted a volume on my backend_container with the projects files. On my local computer, file/folder creation from django inside the container and to the volume works well. On the server everything seem to work as expected (no errors whatsoever), but when I ls to find my folders/files, they aren't there. I tried to debug it myself, but so far : when I exec into the container, I can create folders ~/project-backend$ docker exec -it project_backend_container /bin/bash root@d34b85516a59:/code# mkdir test root@d34b85516a59:/code# ls __pycache__ app manage.py static test uploads project when I run the shell with django, I can also create folders root@d34b85516a59:/code# python manage.py shell Python 3.7.4 (default, Sep 12 2019, 15:40:15) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import os >>> os.makedirs('my/awesome/dirs') >>> now exiting InteractiveConsole... root@d34b85516a59:/code# ls __pycache__/ app/ manage.py my/ static/ uploads/ I tried to override django storage class to log errors, but everything is going fine. From the django side, everything looks alright. My knowledge on docker layers and filesystem management for volume is clearly lacking … -
Django custom middleware not adding custom header
So I'm trying to add a custom header to every request in my Django app, I followed this question, and my setup looks like this: middleware.py: from django.utils.deprecation import MiddlewareMixin class ReverseProxyLocalMiddleware(MiddlewareMixin): def process_request(self, request): request.META['User-Id'] = 1 settings.py: ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'myapp.middleware.ReverseProxyLocalMiddleware', ] However, anytime I try and access the new header in a test I get: def list(self, request): > user_id = request.META['User-Id'] E KeyError: 'User-Id' Does anyone have any idea what I'm doing wrong?