Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply filter after the retrieve methods?
I'm currently overriding the list method of the ModelViewSet and using filter_fields but I realized that the filter is applied before the list, so my list method is not being filtered by the query param. Is it possible to apply this filter after the list method? class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer filter_fields = ('country__name') filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) queryset = Account.objects.all() def list(self, request): if request.user.is_superuser: queryset = Account.objects.all() else: bank_user = BankUser.objects.get(user=request.user) queryset = Account.objects.filter(bank=bank_user.bank) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) When I do request using this URL http://localhost:8000/api/account/?country__name=Germany, it returns all the accounts filtered by bank but not by country. -
django convert Html to pdf, better library than pdfkit?
I am working on task using django and this task is to allow users to download a pdf document with there user informations. So I am using django template to fill in the user info with the render context. Then I convert the html into pdf using pdfkit and whtmltopdf. But this library is not good enough to take into account some of the css files. So the displayed pdf is not really good. Is there a more powerful library to do this ? Or any other idea to carry out this task ? -
ProgrammingError in Django: object has no attribute, even though attribute is in object
I am working in Django, and have a model that needs to contain the field "age" (seen below) class Result(models.Model): group = models.ForeignKey(Group, null=True) lifter = models.ForeignKey("Lifter", null=True) body_weight = models.FloatField(verbose_name='Kroppsvekt', null=True) age_group = models.CharField(max_length=20, verbose_name='Kategori', choices=AgeGroup.choices(), null=True) weight_class = models.CharField(max_length=10, verbose_name='Vektklasse', null=True) age = calculate_age(lifter.birth_date) total_lift = models.IntegerField(verbose_name='Total poeng', blank=True, null=True) The age is calculated with a method in utils.py, called "calculate_age": def calculate_age(born): today = date.today() return today.year - born.year((today.month, today.day < (born.month,born.day)) The lifter.birth_date passed to the calculate_age method comes from this model (in the same class as the Result-model) class Lifter(Person): birth_date = models.DateField(verbose_name='Fødselsdato', null=True) gender = models.CharField(max_length=10, verbose_name='Kjønn', choices=Gender.choices(), null=True) However, I get the error 'ForeignKey' object has no attribute "birth_date". I have tried tweaking the code to get rid of it, but nothing seems to be working. Does anyone know why I might be getting this error? Thank you for your time! -
OSError [Errno 2] No such file or directory
Output : OSError at /treedump/ [Errno 2] No such file or directory Request Method: GET Request URL: http://xxx.xxx.xxx.xxx/ekmmsc/treedump/ Django Version: 1.10.7 Exception Type: OSError Exception Value: [Errno 2] No such file or directory Exception Location: /usr/local/lib/python2.7/site-packages/Django-1.10.7-py2.7.egg/django/utils/_os.py in abspathu, line 31 Python Executable: /usr/local/bin/python Python Version: 2.7.6 TreeDump Views from django.shortcuts import render import time from . import scripts # Create your views here. y=time.strftime("%d_%m_%Y") print (y) l=y.split("_") date=l[0]+l[1]+str((int(l[2])%100)) def index(request): num_visits=request.session.get('num_visits', 0) request.session['num_visits'] = num_visits+1 return render( request, 'index.html', context={'num_visits':num_visits}, ) def printx(request): if(request.GET.get('mybtn')): strx= "HELLO required Executed" time.sleep(5) return render(request,'printx.html', context = {'strx':strx},) import os from django.conf import settings from django.http import HttpResponse,Http404 def download(request): scripts.tree70dump() file_path ='/data1/ekmmsc/webapp/ekmmsc/treedump/DumpFiles'+"EKM_TREE70DUMP_"+date+".zip" if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404("Does not exist") Please help.... -
Error: No module
Made a pull from GIT. But the new setup does not run while there are 2 other setups of the same project on the same server and all 3 are running under virtual env. Using runserver for the new setup throws this error.Error: No module named service_centre Have checked the setting.py files on both the other setups its same as the one for the new one with just the project and template directory paths changed. Thanks in advance. -
Django: How to handle exception if something wrong in database credential which is specified in setting.py file.
I am using MySQL as a database in Django application. I want to throw an exception if something went wrong in database credential setting in setting.py. For example: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'customuser2', 'USER': 'john', 'PASSWORD': 'xyzabc', 'HOST': 'xxx.xxx.xx.x', 'PORT': 'xxxx', } } So if I entered wrong host or a port name, there will be an error in application. is there any way to throw the exception? -
Calling some functions if Generic View is success
I use generic views/class-based views in my project and I want to call some functions if view is done successfully. I use for this def get_success_url() method. But I can't reach the model in that function. How can I get rid of this, or are there any other way to do this? My codes: class MyModelUpdate(UpdateView): model = MyModel fields = ['details'] def get_success_url(self, **kwargs): add_log(form.model, 2, 1, request.POST.user) return reverse_lazy('model-detail', kwargs = {'pk' : self.kwargs['model_id'] }) -
Django - correct way to convert list to combined OR for Q object
I have QueryDict with list 'value': ['1', '2', '3', '4', '5'] - number of elements is unknown. I need convert this list to filter model using OR condition: Poll.objects.get(Q(value__icontains=option[0]) | Q(value__icontains=option[1])) In SQL: AND (value LIKE '%1%' OR value LIKE '%2%') How to achieve this correct and easy way ? -
Django Foreign Key of Auth.User - column "user_id" does not exist
I have looked at all relevant resources but I'm unable to make any headway. Situation: I am building a simulation model using Django and am looking to store simulation data as well as sets of parameter data. Many sets of simulation data should be linked to each user, and many sets of parameter data can be linked to each simulation. Thus, I have tried to model this under 'models.py' of my Django app. from django.db import models from django.conf import settings # Create your models here. class Simulation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) date = models.DateTimeField() # Each simulation has only one graph # Graphing parameters hill_num = models.CharField(max_length=3) div_type = models.CharField(max_length=10) s3_url = models.CharField(max_length=256) def __str__(self): return str(self.sim_id) class Parameter(models.Model): # Each simulation can have many sets of simulation parameters simulation = models.ForeignKey('Simulation', on_delete=models.CASCADE) lsp = models.PositiveIntegerField() plots = models.PositiveIntegerField() pioneer = models.BooleanField() neutral = models.BooleanField() # for pioneers p_max = models.PositiveIntegerField() p_num = models.PositiveIntegerField() p_start = models.PositiveIntegerField() # for non-pioneers np_max = models.PositiveIntegerField() np_num = models.PositiveIntegerField() np_start = models.PositiveIntegerField() def __str__(self): return str(self.param_id) ./manage.py makemigrations works but when I try to populate the database with python manage.py loadtestdata auth.User:10 divexplorer.Simulation:40 divexplorer.Parameter:300, it throws this error: auth.User(pk=72): JshtkqSzw3 auth.User(pk=73): … -
Django 1.11 enter_transaction_management alternative
We are using django as our main backend, we use django-nose as our unit test framework. We have recently upgraded from django 1.3 to 1.11, a huge change, we are facing the following issue. When we are django 1.3, the unit tests ran fine, but with django 1.11, it's throwing the below error. transaction.enter_transaction_management(using=db) AttributeError: 'module' object has no attribute 'enter_transaction_management' We found that there is an opened issue going on in django-nose github. I thought of two solutions for this problem. 1. As I can understand that enter_transaction_management and managed functions are deprecated/removed in django 1.11, were there any replacements or alternatives provided in 1.11??? 2. What are the good alternatives to django-nose?? Please help These are the github issues. https://github.com/django-nose/django-nose/issues/226 https://github.com/django-nose/django-nose/issues/289 https://github.com/django-nose/django-nose/pull/258 -
Accessing friends without taggable_friends permission using django and Facebook API
I am using Facebook Sdk in Django 1.11.5. I have tried hard but could not get the permission to access the friend profile using the facebook Graph API as facebook didn't approved my request for accessing the taggable_friend. I would like to know whether it is possible to access my profile and then get the friend profile without using the facebook API. I am not talking about illegal Facebook Scraping. What I am talking about is that whether I can access my profile using the app and my credential and then access the friends section of my facebook. Is it at all possible to enter or login facebook with the App ID and secret ket and access_token with simple permission of public_profiles and email and then login the facebook and extract the friend list from the profile friends tab. Can anyone suggest an idea for this concept? I am using Python 2.7 -
django: rest-auth and allauth for Facebook registration API requires CSRF token
Using allauth and django-rest-auth to create a facebook login api. I've followed the both packages documentations and using example from rest-auth doc. I've followed all the steps and I can successfully use this API from DRF browse-able API view and it is successfully performing the registration. When I try this API from somewhere else like postman it asks for CSRF token. I tried to use csrf_exempt decorator but that doesn't seem to be effective on this url. Here is my url config: url(r'^rest-auth/facebook/$', csrf_exempt(FacebookLogin.as_view()), name='fb_login'), Rest of the things are same as they mentioned in the documentation for django-rest-auth. I can't figure out what am I missing, or where should I look for a fix. Any help to diagnose the issue would be appreciated. -
Need a calculated value in models in Django
I want a calculated value in models.py. Below is the file models.py. I manage to get the price as expected but the price doesn't appear as one of the field. What I mean is, when I enter delivery_price and support_price, the price field should be calculated and be shown in the below page itself (attached image). Is this possible or am I getting something wrong? delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) #def get_price(self): # "Returns the price." # return (self.delivery_price + self.support_price) #price = property(get_price) price = models.DecimalField(max_digits=10, decimal_places=0,editable=False) def save(self, *args, **kwargs): self.price = self.delivery_price + self.support_price super(Product, self).save(*args, **kwargs) -
Django+Apache+ModWSGI Hangs Indefinitely
I have a Django 1.11 site served from Apache 2.4.18 + ModWSGI on Ubuntu 16 and it hangs indefinitely. What's odd is that if I stop Apache, only then does it return the request, which renders the page perfectly, implying Django is correctly returning the request, but something's preventing Apache from sending out the data. My Apache site.conf: <VirtualHost *:80> ServerName www.mysite.com ServerAlias www.mysite.com ServerAdmin sysadmin@mysite.com DocumentRoot /usr/local/mysite AllowEncodedSlashes On Alias /media/ /usr/local/mysite/media/ Alias /static/ /usr/local/mysite/static/ <Directory /usr/local/mysite> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny Allow from all # New directive needed in Apache 2.4.3. Require all granted </Directory> <Directory /> Options FollowSymLinks AllowOverride None </Directory> LogLevel debug ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined # Stop GIL deadlocks from crashing Python/Modwsgi due to Python C-extensions? # Without this, you may get a "Premature end of script" error. # https://code.google.com/p/modwsgi/wiki/ApplicationIssues#Python_Simplified_GIL_State_API WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess www.mysite.com python-path=/usr/local/mysite/.env/lib/python2.7/site-packages processes=1 display-name=%{GROUP} user=www-data group=www-data WSGIProcessGroup www.mysite.com WSGIScriptAlias / /usr/local/mysite/wsgi/mysite.wsgi <Directory /usr/local/mysite/wsgi> Order allow,deny Allow from all </Directory> </VirtualHost> My Django wsgi: import os import time import traceback import signal import sys from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings.settings' os.environ['CELERY_LOADER'] = 'django' sys.path.append(os.path.join(os.path.realpath(os.path.dirname(__file__)), '../src')) sys.path.append(os.path.join(os.path.realpath(os.path.dirname(__file__)), '../src/mysite')) try: application = get_wsgi_application() print 'WSGI without exception' except Exception: print … -
How to perform Left Outer Join in Django ORM ?
I have the following models: class CandidateDetail(models.Model): full_name = models.CharField(max_length=128, null=True) email_id = models.CharField(max_length=64, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Retake(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) candidate_detail = models.ForeignKey('CandidateDetail') is_expired = models.BooleanField(default=False) owner_detail = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I want to perform the following Left Outer Join Query: SELECT s.*, r.* FROM app_candidatedetail s LEFT OUTER JOIN app_retake r ON (s.id = r.candidate_detail_id) The DB is Postgresql. I could do the query using qset = CandidateDetail.objects.raw('SELECT s.*, r.* FROM app_candidatedetail s LEFT OUTER JOIN app_retake r ON (s.id = r.candidate_detail_id)') The id field of CandidateDetail table is the default id of Django which is an IntegerField acting as primary key. But, I want to use this in serializer to return the result as JSON, which I couldn't find out. Please help me with this issue on how to write ORM query for this as well as how to make a serializer for this query. Thanks. -
how to authenticate a user for a delete action in django testing
I'm getting an error while trying to login via a test. On the frontend I am able to delete a cartItem without no issue but on testing, the test suite can't logged in to do a delete action. error with self.login(username=user.username, > password=user.password): applications/startupconfort/tests/test_frontend.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ env_python3/lib/python3.6/site-packages/test_plus/test.py:238: in login return login(self, *args, **credentials) env_python3/lib/python3.6/site-packages/test_plus/test.py:66: in __init__ "login failed with credentials=%r" % (credentials) E AssertionError: False is not true : login failed with credentials={'username': 'helloworld', 'password': '(password)'} test.py def test_auth_user_can_delete_his_cartitem(self): user = mixer.blend( User, username='helloworld', password='(password)', email='adddd@gmail.com') products = mixer.cycle(3).blend( CartItem, customer=user) self.assertTrue(user.is_authenticated()) #login attempt with self.login(username=user.username, password=user.password): response = self.delete('startupconfort:delete_this_item', products[0].pk) self.assertEqual(200, response.status_code) urls.py url(r'^delete/(?P<pk>\d+)/$', CartItemDeleteView.as_view(), name="delete_this_item"), template(html) <form class="right" method="POST" action="{% url 'startupconfort:delete_this_item' cartitem.id %}"> I am using django-test_plus -
Sum columns in python
I have a text file. It should match with string in column1 and add with colum2,3,4 and prints it in a different file. Input: abc,1,1,1,1,0 def,1,0,0,0,1 abc,1,0,0,0,1 def,0,0,0,0,1 xyz,1,1,1,1,0 output abc,2,1,1,1,1 def,1,1,1,1,2 xyz,1,1,1,1,0 Any help would be appreciated. -
Tastypie POST Does not FAIL
So I created a simple model as follows class Titles(models.Model): titleID = models.CharField(max_length=20,primary_key=True) title = models.CharField(max_length=100) class Meta: verbose_name = "Titles" verbose_name_plural = verbose_name def __str__(self): return self.title Exposed it as a API as class TitlesResource(AT.MultipartResource,AT.WrapView,ModelResource): class Meta: queryset = coreModels.Titles.objects.all() authentication = AT.cxenseAMSAPIAuthentication() authorization=Authorization() resource_name = 'titles' allowed_methods = ['get','post','put','patch'] include_resource_uri=False limit=1000 When I try to create a new object it works but if I mess up any of the fields it still works eg: http://localhost:8000/core/titles/ { "I_am_not_suppling_a_correct_feild": "2", "title_not": "dept 1" } [27/Oct/2017 10:54:12] DEBUG [django.db.backends:90] (0.001) UPDATE "core_titles" SET "title" = '' WHERE "core_titles"."titleID" = ''; args=('', '') Shouldnt this fail as I am not supplying the needed fields? -
Is it possible to receive a post_save signal that comes from a particular modelform's save() instead of simply anytime the instance is saved?
If a model has w, x, y, z attributes, and a modelform based on this model has fields only for w and x, how can I wire up a post_save_receiver(or similar) for only the modelform? I'd like the receiver to ignore save()s to y and z. And only carry out the code within the post_save function if a particular form or particular field was updated. The following code should carry out depending on the fields saved, or modelform saved: def profile_post_save_receiver(sender, instance, created, *args, **kwargs): ... post_save.connect(profile_post_save_receiver, sender=Profile) And here are two separate modelforms. The post_save code should happen only when PreferenceUpdateForm is updated, and ignore changes to ProfileUpdateForm: from .models import Profile from django import forms class PreferenceUpdateForm(forms.ModelForm): class Meta: model = Profile fields = [ "preference1", "preference2", ] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = [ "bio", "profile_image", ] If this isn't the ideal way to go about this, how else can I achieve similar results? -
Dockerized Django app getting error: failed to open python file my_project/wsgi.py
I am trying to create a Dockerized version of a DJang app. The app was created with the following command: docker build -t my-app . The app was started using: docker container run --name my-app --detach my-app Everything runs fine when DJango is running with the tool under PyCharm. It is only when trying to convert the regular DJango app to one that is Dockerized that the problems take place. I am new to the DJango mixed with Docker - so - I am currently uncertain what the error means or why it is taking place. How can I fix this? The info is below. I am getting the following errors in the error log when starting the app: PEP 405 virtualenv detected: /venv Set PythonHome to /venv Python main interpreter initialized at 0x559036d279e0 python threads support enabled your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 434688 bytes (424 KB) for 16 cores *** Operational MODE: preforking+threaded *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 1) spawned uWSGI worker 1 (pid: 5, cores: 8) spawned uWSGI worker 2 (pid: 6, … -
Maximum site limit with Django and ModWSGI?
I recently added an 18th Django site to my Apache+ModWSGI server, and now none of site load. Attempting to bring up the site doesn't return any kind of error in the browser. It just seems to hang indefinitely, like the server's establishing a connection but never returning a response. My Apache error log just shows a bunch of messages like: [Thu Oct 26 23:40:36.090400 2017] [wsgi:error] [pid 14439:tid 140256804280064] (11)Resource temporarily unavailable: [client 10.180.252.171:9389] mod_wsgi (pid=14439): Unable to connect to WSGI daemon process 'mysite' on '/var/run/apache2/wsgi.13512.0.1.sock'. along with a lot of messages like: [Thu Oct 26 23:54:43.331667 2017] [rewrite:trace1] [pid 15761:tid 139797226026752] mod_rewrite.c(476): [client 10.150.142.51:15247] 10.150.142.51 - - [10.153.212.241/sid#7f252e331948][rid#7f251c68a0a0/initial] pass through / [Thu Oct 26 23:54:43.331904 2017] [rewrite:trace2] [pid 15761:tid 139797226026752] mod_rewrite.c(476): [client 10.150.142.51:15247] 10.150.142.51 - - [10.153.212.241/sid#7f252e331948][rid#7f251c67e0a0/subreq] init rewrite engine with requested uri / [Thu Oct 26 23:54:43.331985 2017] [rewrite:trace3] [pid 15761:tid 139797226026752] mod_rewrite.c(476): [client 10.150.142.51:15247] 10.150.142.51 - - [10.153.212.241/sid#7f252e331948][rid#7f251c67e0a0/subreq] applying pattern '^.*$' to uri '/' [Thu Oct 26 23:54:43.332078 2017] [rewrite:trace1] [pid 15761:tid 139797226026752] mod_rewrite.c(476): [client 10.150.142.51:15247] 10.150.142.51 - - [10.153.212.241/sid#7f252e331948][rid#7f251c67e0a0/subreq] pass through / What does this mean, and what's causing it? I haven't changed my Apache configuration, and the error doesn't list anything wrong with my Django … -
django https 502 bad gateway error
nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } I am holding my head for the past two days. Don't understand what is happening. I have uninstalled and installed Django around 10 times. I am able to view the website through http://example.com:8000 on running from cli python manage.py runserver 0.0.0.0:8000 But unable to access from https://example.com. It shows 502 bad gateway nginx error. Please help me out. -
html template wont render in python django
I know this is a very noob question but need help with this when I try to render my product template it returns with this error , the first two pages were rendered correctly such as about , home and contact but when I tried to add another app for for my products page it wouldnt load. **THE ERROR** Page not found (404) Request Method: GET Request URL: http://localhost:8000/%7B%25%20url%20'products'%7D Using the URLconf defined in trydjango.urls, Django tried these URL patterns, in this order: 1. ^admin/ 2. ^$ [name='home'] 3. ^about/$ [name='about'] 4. ^products/$ [name='products'] 5. ^contact/$ [name='contact'] 6. ^accounts/ 7.^static\/(?P<path>.*)$ 8.^static\/(?P<path>.*)$ The current URL, {% url 'products'}, didn't match any of these. **This is the structure** src >> contact >> products >> migrations >> templates >> products.html >> profiles >> migrations >> templates >> about.html >> base.html >> home.html >> navbar.html **from the products app this is the views.py** def products(request): context = {} template = 'products.html' return render(request, template,context) **This is the config for urls** from profiles import views as profiles_views from contact import views as contact_views from products import views as products_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', profiles_views.home, name='home'), url(r'^about/$', profiles_views.about, name='about'), url(r'^products/$', products_views.products, name='products'), url(r'^contact/$', contact_views.contact, … -
Setting up a cas server on django with django-mama-cas and django-cas-ng
I've recently come across a problem in my app where I need to implement SSO. Never had to do this before - zero experience with SSO - and all of the answers here I've read are a bit vague. Example: Setting up django-mama-cas and django-cas-ng Which is the best I've found. The answer is good, but it leaves out a few details I'm not sure about. Once I spin up the other django instance, which I only need to serve as a cas server, do I just leave it dry with only the cas urls included in that projects urls.py file - since it's simply meant to be the cas server? Then in my other project I install django-cas-ng and point the CAS_SERVER_URL to use that url otherdomain.com/cas? Now, if that's fine what about the django-mama-cas services it talks about in the documentation? Are these just my other domains I'm allowing for sign in with the cas server? It's not immediately clear to me how the other domains are linked back into the cas server for authentication being shared across them. Expanding on this, I have a bunch of domains pointing to my main django project, which are proxied to … -
over ride django session middleware
Is it possible to override the django session middleware to set the login cookie for an app that is cross-domain? Meaning a user logs in on one site and then I site the cookies on the other domains, by overriding the middleware, so that they are logged in to all domains my app uses. I tried overriding this to iterate allowed_hosts variable in settings to set the cookie to all domains but still was presented with the option to login / register. I'm trying to integrate my login / registration system (allauth) to work cross domainw ith using a CAS server, openid, SSO etc My attempt (process_response): class SessionMiddleware(MiddlewareMixin): def __init__(self, get_response=None): self.get_response = get_response engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check if we need to delete this cookie. # The session should be deleted …