Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter model based of context data using django filter
I have a detail view of a model that I want to display together with a list of products and Im trying to integrate django_filter within this view. Error Message TypeError at /collections/christmas/?category=mens, get context data takes exactly 2 arguments (1 given) Filter class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['categories'] Detail View class collection_detail(DetailView): model = Collection def get_context_data(self, **kwargs): context = super(collection_detail, self).get_context_data(**kwargs) context['collection_list'] = ProductFilter(request.GET, queryset=Product.objects.filter(collection=self.object.id).filter(structure='parent')) return context What am I specifically doing wrong here? Is it possible to even do this? -
Heroku csv file not getting recognised in settings.py
i am trying to deploy my site using heroku. Being a starter just following the steps given on a website. In settings my csv and database default is not getting recognised. ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } -
LDAP (2, 'No such file or directory') error using DJANGO
I am implementing a Django app, I am trying to fetch data from an LDAP server. Here is my code in views.py.I have supplied all the necessary information below, but yet I am facing (2, 'No such file or directory') error. What Am I missing here? LDAP_USERNAME = "" LDAP_PASSWORD = "" LDAP_BASEDN = "" try: l = ldap.initialize('') l.protocol_version = ldap.VERSION2 l.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD) search_filter = "(cn=*)" search_attribute = None search_scope = ldap.SCOPE_SUBTREE ldap_result_id = l.search(LDAP_BASEDN, search_scope, search_filter, search_attribute) result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) print result_set except ldap.LDAPError, e: print e -
How do I save form progress and resume later in Django form-tools?
I have been using formtools in Django to render lengthy forms for my application. I have managed to do this(Fill in forms and submit data into the DB). Something got me thinking, what if I didn't complete all the steps in filling up the forms and want to save the progress and resume filling some other time? I have searched online for such information and haven't succeeded. First, Is this possible with formtools? If yes, How do I go about this? Thanks in advance for the help. -
python logging: How to replace the output file of a FileHandler?
I have a Django project, and I use logging.config.dictConfig(CONFIG) to get the logging that I want when running the Django app as a server. I have my own module in mycore.logging, and it creates a logger object at import-time. This is all great. However, Django has independent 'management commands' and I want to log each management command to its own separate file. The logfile name would be the name of the management command + ".log". I've searched and googled and not found any examples of this. Is it really so unusual? Or have I just not found the prior art? I think I know how to remove the existing FileHandler, instantiate a new one with my desired output file, and add it as a handler on the logger object. But it seems like a clunky thing to do. Any advice will be welcome. import logging import logging.config from logutils.colorize import ColorizingStreamHandler from django.conf import settings class ColorHandler(ColorizingStreamHandler): def __init__(self, *args, **kwargs): super(ColorHandler, self).__init__(*args, **kwargs) self.level_map = { # Provide your custom coloring information here logging.DEBUG: (None, 'blue', False), logging.INFO: (None, 'green', False), logging.WARNING: (None, 'yellow', False), logging.ERROR: (None, 'red', False), logging.CRITICAL: ('red', 'white', True), } try: CONSOLE_LOG_LEVEL = settings.CONSOLE_LOG_LEVEL except … -
Django filter list using a slider
I am new newbie to web development and have been trying to learn django and python and currently working on a problem that if someone could give me the right direction to towards I have a simple model like this class Books(models.Model): articleid = models.CharField(primary_key=True,max_length=20) author = models.CharField(max_length=300) title = models.CharField(max_length=500) rating = models.FloatField(blank=False, null=False) I would basically like to have a slider that I can then use the following query as an example to filter the list to display books that are within the range Books.objects.filter(rating__gte=5, rating__score__lte=8) Would really appreciate if anyone can point me to the right direction and the simplest solution would be ideal since I am still trying to figure out web development Thanks, Mark -
Django: how to get a model instance by id within a template
Just a quick question - I was wondering if it were possible to return a model instance by id within a template e.g., If I had a list of comments associated to posts by the post Id, and did something like: {% for comment in comments %} {{ request.post.get_by_id(id == comment.object_id).title }} {% endfor %} I'm working within a tags.py "pseudo-view" using the following: @register.inclusion_tag('blog/frame/latest_comments.html') def show_latest_comments(count=5): latest_comments = Comment.objects.all()[:count] return { 'latest_comments': latest_comments} Should I work within the tags.py file to maybe loop over the latest_comments object and extract everything I need, including the blog post it is associated to and then dump this in the context as a new dictionary...? -
Migration issue causing internal server error 500 during AWS Elastic beanstalk deployment
I have deployed my Django application on AWS Elastic beanstalk and is now facing an issue due to migrations.I have created a python config file in the .ebextensions folder which has container_command that allows migration initially. After i ran the app with DEBUG=True in production: I got a ProgrammingError that tells it's beacuse of relation not created which I think is due to database tables not being created for my Django app. How can I allow migration for my app just like I would do in local server with python manage.py makemigrations command. my python.config file: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /opt/python/run/venv/bin/activate && python manage.py createsu" leader_only: true 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "mysite.settings" "PYTHONPATH": "./src" "aws:elasticbeanstalk:container:python": WSGIPath: mysite/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" Also I am using postgres both locally and in production.In local it works completely fine. -
Handling a send button
@staff_member_required @csrf_exempt def send(request, request_id=None): import ipdb; ipdb.set_trace() req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) if context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return JsonResponse({ 'success': True, 'message': u'%s' % _('Message sent'), 'redirect_to': reverse('messages:detail', args=[obj.pk]), }) Actually, this method could send a certain email with EmailFromTemplate. I pass this function inside an url. # -*- coding: utf-8 -*- from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from loanwolf.messaging.views import MessagingIndexView, send app_name = 'messaging' urlpatterns = [ url(r'^$', login_required( MessagingIndexView.as_view()), name='index'), url(r'^send/(?P<request_id>[0-9]+)/$', send, name='send'), ] So I use the function send inside a template .html. The principal is simple. I have a button when once we click on it, it will send that message under certain condition. My problem is located if a guy click hundred times on that button, it will occur hundred of sending messages. How could I escape this issue? In fact, a solution of that would be handling in disactivating the button for 5mins each time it'll be used, but I don't even know how to do that. <a href="#" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-button" data-turbolinks="false" data-copy-to="{{ folder.pk … -
Python encoding problems: zip csv buffers (Django)
In a Django view, I want to create some csv files in memory, and zip them to download. I'm using Django 1.11 / Python 2.7. My code: import csv import zipfile import StringIO files = [] csv_buffer = StringIO.StringIO() writer = csv.writer(csv_buffer) writer.writerow(["val1", "str1"]) csv_buffer.seek(0) files.append(csv_buffer) zipped_file = StringIO.StringIO() with zipfile.ZipFile(zipped_file, 'w') as zipper: for i, file in enumerate(files): file.seek(0) zipper.writestr("{}.csv".format(i), file.read()) zipped_file.seek(0) # response = HttpResponse(csv_buffer, content_type='text/csv') # response['Content-Disposition'] = 'attachment; filename=results.csv' response = HttpResponse(zipped_file, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip' return response With this code, the csv is encoded utf-8 but my editor complains about 'invalid characters'. If I just return the csv file, I get an empty csv. No idea why.. I think the StringIO buffer has a wrong encoding, but I don't know how to make this work. If I do: csv_buffer = StringIO.StringIO("") I can create a readable CSV file, but then the zip part of the code fails: 'ascii' codec can't decode byte 0xd4 in position 10: ordinal not in range(128) Any explanation what's going wrong here would be appreciated! Edit: Typo Edit 2 : Added zip error message -
How do I import an object into its own manager?
I realize that my logic is flawed and its causing a circular import. Here's what I am trying to accomplish: managers.py (kept separate from models.py) class TicketManager(models.Manager): def create_in_atom(self, ticket): if type(ticket) is not Ticket: raise Exception('Not a Ticket object.') This produces this error: NameError: global name 'Ticket' is not defined And so then I tried to import it: from models import Ticket Which produces: ImportError: cannot import name Ticket How do I check to see if an argument passed to a function of the TicketManager is of the type "Ticket", which the TickerManager falls under? -
Django REST framework
We need to implement the API on the site, chose the REST framework. Auto-cutting done through Token (rest_framework.authtoken) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'Rest_framework.permissions.IsAdminUser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'Rest_framework.authentication.TokenAuthentication', ), } view.py @api_view(['GET', 'POST']) def task_list(request): if request.method == 'GET': tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) Gives an error message "Detail": "Authentication credentials were not provided." If you add 'rest_framework.authentication.SessionAuthentication' in 'DEFAULT_AUTHENTICATION_CLASSES' ' Then the GET method works, POST returns a "detail" error: "CSRF Failed: CSRF token missing or incorrect." How to fix this error and prevent the GET method -
can't add values from field into database Django
I would like to add data filled into database and output it. But i have no idea where is wrong because my data was't saved into database at all. In views.py, Scholarship is just one scholarship object, LScholarship is displaying all the data in Scholarship. I have similar code for other models and views but i have no idea what i did wrong in here, making the data can't be saved into database. Could anyone please advice me where am i wrong arscholar.html <div align="center" > <form method="POST" onsubmit="return validation()" action=""> {% csrf_token %} {{ form.errors }} <p>Upload File: {{scholarship.doc}} <input id="doc" type="text"> </p> <p>Faculty: {{scholarship.faculty}} <input id="faculty" type="text"> </p> <p>Opening date: {{scholarship.openDate}} <input id="odate" type="date" > </p> <p>Closing date: {{scholarship.closeDate}} <input id="edate" type="text" > </p> <button type="submit" name="AddUser" value="Add Scholarship" onclick="add()" >Add Scholarship</button> </form> </div> <form method="POST" action=""> {% csrf_token %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th> Scholarship </th> <th> Faculty </th> <th> Open Date </th> <th> Close Date </th> </tr> {% for item in query_results %} <tr align="center"> <td>{{item.doc}}</td> <td>{{item.faculty}}</td> <td>{{item.openDate}}</td> <td>{{item.closeDate}}</td> </tr> {% endfor %} </table> </form> models.py #consists of all the details of the scholarship under the 'Add/Remove Scholarship' class Scholarship(models.Model): doc = … -
Why Is This Method Not Visible from Django Custom Manager?
I have two Django models, one that stores promotion codes and another that tracks who redeemed a particular promotion code. I'm trying to create an instance method that determines whether or not a specific user has redeemed a specific code. The problem is that I'm not seeing one of my PromotionManager methods, 'redeemed_by_user'. Here are my classes: from django.contrib.auth.models import User from django.db import models class PromotionManager(models.Manager): def redeemed_by_user(self, promotion, user): redemption_count = PromotionRedeemed.objects.filter(promotion=promotion, redeemer=user).count() if redemption_count == 1: return True elif redemption_count == 0; return False else: raise ValueError('Invalid redemption count') class Promotion(models.Model): code = models.CharField(max_length=16) objects = PromotionManager() class PromotionRedeemed(models.Model): promotion = models.ForeignKey('Promotion') user = models.ManyToManyField(User) If I start the the Django extension shell_plus and do the following: In [1]: user = User.objects.get(username='smith') In [2]: promotion = Promotion.objects.get(code='bigsale') and then I do this: In [3]: dir(promotion) I don't see the redeemed by user method. I was under the impression that I could move methods like this from my class to a custom manager class. Is that not the case? If so, can anyone explain why? As I understand it, class manager methods are supposed to act on table-level queries and class intance methods on row-level objects. Isn't objects.filter … -
Served blank page instead of django template when using nginx
So I am trying to set up a "public server" at home on ubuntu with nginx, gunicorn and django. My domain andreastollanes.com successfully point to my IP and I can see that the django view get's called(printed out to console) But no error messages get logged in nginx and I get served a blank.html file: <html><HEAD> </HEAD><FRAMESET border='0' ROWS='*,1'> <FRAME SRC='http://82.164.163.241'><FRAME SRC='blank.html'> </FRAMESET> </html> If I go directly to my page with just the IP, I get forwarded to the server hosted on localhost:8000. So nginx does work as intended, just not with my domain. Which it did yesterday. Here is the nginx config so far, it's not completely set: server { listen 80; server_name andreastollanes.com; location / { proxy_pass http://localhost:8000; } location /static/ { alias /home/andreas/sites/andreastollanes.com/static/; } } I'm fairly new to server hosting other than local game servers. -
Celery with multiple nodes not working properly with supervisor
I'm facing a difficulty that I don't understand. I've got 2 workers started through supervisor: [program:celery-worker] environment=DISPLAY=":1001",DJANGO_SETTINGS_MODULE=victoria.settings.production directory = /home/victoria/current command = /home/victoria/virtualenv/bin/celery -A victoria worker -l info stdout_logfile = /home/victoria/celery-worker.log loglevel=warn [program:secondapp-celery-worker] environment=DJANGO_SETTINGS_MODULE=settings.live directory = /home/victoria/webapps/app/src command = /home/victoria/webapps/app/.venv/bin/celery -A celery_app worker -l info -n cs-worker stdout_logfile = /home/victoria/secondapp-celery-worker.log loglevel=info The secondapp workers work perfectly but the first ones don't. At first I was having a message that I need to differentiate the name when using the same node. Which I did as you can noticed. Now when I stop the workers from supervisor and run them manually celery -A victoria worker -l info I don't have the warning about name / node anymore and it's working. But not through supervisor... I'm running out of ideas about what to do, any ideas? -
cannot server static files with nginx in django
I am running a django with nginx as a web server. After configuration its seems that I am always getting 404 for static files. Here is my configurtaion base.py STATIC_ROOT = os.path.join(PROJECT_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static_files'), ] nginx.conf upstream django { server unix:///tmp/mysite.sock; } # configuration of the server server { listen 5000; server_name server localhost:5000; address or FQDN charset utf-8; client_max_body_size 75M; location /static { alias /Users/del/projects/app-backend/static/; } location ~ ^/(images|javascript|js|css|flash|media|static)/ { autoindex on; root /Users/del/projects/app-backend/static/; } location / { uwsgi_pass django; include /Users/del/perso/django/library/uwsgi; } } I have made sure to run python manage.py collectstatic, and the files are actually generated under /static/ folder -
Getting Django Tables2 to work
I'm trying to get django_tables2 to work, but I keep getting an error. I already have it installed and it's already in my settings. models.py class Schedules(models.Model): course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus') location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A') start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today) start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am') end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am') instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale') total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six') hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half') frequency = models.CharField(max_length=128) status = models.CharField(max_length=128, choices=STATUS_CHOICES) interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day') initiated_by = models.CharField(max_length=128, null=True) schedule_id = models.IntegerField(default=0) def save(self, flag=True, *args, **kwargs): super(Schedules, self).save() if flag: self.schedule_id = self.id + 10000 self.save(flag=False, *args, **kwargs) tables.py import django_tables2 as tables from schedule.models import Schedules class ScheduleTable(tables.Table): class Meta: model = Schedules views.py from schedule.models import Schedules from schedule.tables import ScheduleTable def search_Schedule(request): context_dict = {} if request.method == 'POST': query = request.POST['course_name_search'] results = Schedules.objects.filter(course_name=query) table = ScheduleTable(results) if query: context_dict['table'] = table else: context_dict['no_results'] = query return render(request, "schedule/search_schedule.html", context_dict) search_schedule.html {% extends 'base.html' %} {% load django_tables2 %} {% block main_content %} <form method="post" action=""> {% csrf_token %} <label for="course_name_search">Course Name:</label> <input type="text" name="course_name_search" id="course_name_search"> <input type="submit" name="submit"> </form> <div id="result_panel"> {% … -
'filesystemfinder' is not iterable
I am using django to creat a website, and am trying to load my template, but it keeps giving me the error TypeError at /stocks/ 'FileSystemFinder' object is not iterable Does anyone know where this problem could be coming from -
Display data form mysql database in Django
I have tried to display data from my Mysql database using Django. The user enters the required data through addSubscriber.html page to save in the database and is redirected to a page 'report.html' where all the data from the table (in this case subscribers) is displayed. Here are my files: views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views import generic from .models import Subscribers from .forms import addSubsForm @login_required def dashboard(request): user = request.user context = {'user': user} template = 'dashboard.html' return render(request, template, context) @login_required def addSubscriber(request): template = 'addSubscriber.html' if request.method == 'POST': form = addSubsForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.save(using='db2') data = Subscribers.objects.all() return redirect('report', {'entries': data}, 1) else: form = addSubsForm() return render(request, template, {'form': form}) @login_required def report(request): context = locals() template = 'report.html' return render(request, template, context) forms.py from .models import Subscribers from django import forms class addSubsForm(forms.ModelForm): class Meta: model = Subscribers fields = '__all__' report.html {%extends 'base.html'%} {% block content %} <h2 class="page-header">Subscribers List</h2> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>Bill Number</th> <th>Name</th> <th>Area</th> <th>Phone Number</th> <th>Header</th> </tr> </thead> <tbody> <tr>{% for entries in Subscribers %} <td>{{ entries.billNumber }}</td> <td>{{ entries.name }}</td> <td>{{ entries.area }}</td> <td>{{ … -
How do I include an external CSS file as a rule for a class inside a .scss file?
I want to use bootstrap-3.3.7.min.css rules for only a particular section of my page. So, I downloaded it, created a new file called bootstrap.scss and tried to add this rule to it. I use django on my site, so I installed sass and added precompiler rules to my settings. In my bootstrap.scss file, I added this rule to affect all bs3 classes: .bs3 { @include bootstrap-3.3.7.min.css; } bootstrap-3.3.7.min.css is in the same directory as bootstrap.scss, so I'm not sure if I still need to specify full path. In my templates: <link href="{% static "css/bootstrap.scss" %}" rel="stylesheet" type="text/css" /> <input id="example" type="submit" class="bs3 delBtn" value=" " rel='popover' data-placement='right' data-content='Some message'/> The idea is to get that .scss file rules working only for elements with a class of bs3. As you have guessed, this isn't working. I don't see changes to that class whatsoever. But if I add body{background-color: red;} to bootstrap.scss, I can see that change, so I know that the scss file is being loaded. I tried a couple of fixes from other stackoverflow questions, such as: Using import instead of include - @import "full/path/to/file.css" Using import without .css in the end of the file Neither of those things worked. … -
Django not returning session id in headers for android
I am using django for my android app. When I try to login, I do not receive session id in header. If i try the same using requests python library or browser, I am getting session id, but only for android it is missing. -
Django nested serializer doesn't save as expected
I want to tag users in an image and save it, I used nested serializer since you can tag more than one user in an image. The problem is that the image is saved without the tags(they are none). Here is the codes: models.py class TagUsername(models.Model): # the tag is person tag = models.ManyToManyField(User, related_name='tag_username') image = models.ForeignKey(Image) # # De tection Rectangle specs(width,height, coordinate x & coordinate y) # width = models.FloatField() # length = models.FloatField() # xCoordinate = models.FloatField() # yCoordinate = models.FloatField() # who added this tag user = models.ForeignKey(User, on_delete=models.CASCADE) serializers.py class TagUsernameSerializer(serializers.ModelSerializer): tag = UsernameTagSerializer(read_only=True, many=True) user = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field="username") image = serializers.CharField(source='image_id') class Meta: model = TagUsername fields = ('tag', 'user', 'image') UsernameTagSerializer: class UsernameTagSerializer(serializers.ModelSerializer): # username = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field="username") class Meta: model = User # fields I want only fields = ('username', ) Any idea whats wrong ! -
Django won't set HttpOnly for csrftoken cookie
In my Django's settings.py I have SESSION_COOKIE_HTTPONLY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 15768000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SESSION_COOKIE_AGE = 2 * 24 * 3600 However https://detectify.com has found that this flag isn't set for csrftoken cookie. I checked what Chrome tells about the cookie, and if I understand correctly, the empty HTTP column confirms that the two cookies are not HTTP-only: Also, if I do document.cookie in chrome's console, the csrftoken value is shown. I wonder why this could be the case. I have Django running on uwsgi and nginx. The nginx configuration is as follows, and the site in question is https://rodichi.net: server { listen 443 ssl http2 default_server; server_name rodichi.net; ssl_certificate /etc/letsencrypt/live/rodichi.net/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/rodichi.net/privkey.pem; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_protocols TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; ssl_ecdh_curve secp384r1; ssl_session_cache shared:SSL:10m; ssl_session_tickets off; ssl_stapling on; ssl_stapling_verify on; charset utf-8; ... # location settings follow here ``` -
Django Authentication - What sets request.user? This is being overridden temporarily
In a Django wizard form we're capturing the username and password of not the currently logged in user in a case where the business wants a second member of staff to verify a manual process has been completed without error. To do this there's a step in a wizard which is a simple form with a couple of CharFields for the username (email address in our case) and a password. These are then passed to django.contrib.auth.authenticate to verify the credentials are correct (or not) and the process continues or an error is displayed. This is all working great except for the weird side-effect that request.user appears to be temporarily overridden with the second (authenticating) user rather than the actual currently logged in user. I'd happily do something to workaround this (such as re-applying the logged in user back on the request) but I can't find where this is being carried out. Where is request.user set or changed by calling authenticate()? We have our own backend: class EmailAuthBackend(ModelBackend): """ Authentication backend that uses email as username """ def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = get_user_by_email(email_address=username) if user is None: raise UserModel.DoesNotExist if user.check_password(password): if user and hasattr(user, …