Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Can't get nginx to cache uwsgi result
I'm trying to cache a view in my uwsgi django app using nginx uwsgi caching. It mostly seems like nothing is getting written to the cache. The /data/nginx/cache/temp cache folder get's created but nothing gets written to it. I also applied the from django.views.decorators.cache import cache_page cache_page django decorator to the my_cached_page view so the result get's properly cached by django it self and the browser. But I want nginx to cache and return the result for everyone. I used uwsgi_ignore_headers to ignore the Set-Cookie header from the uwsgi app but doesn't seem to have any affect. I'm trying to better understand in which case a result get's cached ( or more importantly, not cached ). I think perhaps the django app is not returning the right headers for nginx to cache the result. Nginx version 1.11.2 http { include mime.types; log_format main '[$time_local] "$request" $status - $body_bytes_sent - $upstream_cache_status'; charset utf-8; client_max_body_size 300M; access_log /var/log/nginx/access.log main; uwsgi_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; sendfile on; sendfile_max_chunk 512k; tcp_nopush on; tcp_nodelay on; gzip on; gzip_min_length 1000; gzip_comp_level 6; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml; gzip_buffers 16 8k; uwsgi_buffering on; uwsgi_buffers 8 16k; keepalive_timeout 65; … -
Django: max, min value with additional fields from selected row
I have a data set of products and those products have different price levels over time. (think an Amazon product) I'm trying to write a Django query to get the max and min prices for each product along with the date/time that it was that price. I can get the max and min with aggregate() but I can't include the date_seen field. Any ideas? models.py Class Product(models.Model): title = models.CharField(max_length=255) Class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date_seen = models.DateTimeField(auto_now_add=True) price = models.IntegerField(blank=True, null=True) -
psycopg2 import error when ubuntu upgraded to 17.10 (from 17.04)
Everything was working great until I upgraded the OS to Ubuntu 17.10. Now my Django project won't run (python manage.py runserver) because psycopg2 won't import. psycopg2 is already installed with pip (nothing has changed there). To be exact this is the error: lib/python3.5/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference -
How to use MultiPartParser in Django Rest Framework
I need to upload a file and some JSON associated with it. But I don't understand how to save the different parts, specifically the JSON part i.e. I'm able to save the image but not the JSON. I read that I need to use a MultiPartSerializer but I can't figure out how to integrate it correctly into my serializer class. Here is the multi-part request that my Server is receiving: <QueryDict: {'geo': ['{"point" : { "type:" : "Point", "coordinates" : [11.51350462236356, -22.70903491973877]}}'], 'picture': [<TemporaryUploadedFile: photo3.jpg (image/*)>]}> Here is the view: class UserUploadedPicture(APIView): def post(self, request, format=None): print(request.data) print("\n\n\n") serializer = PictureSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) Here is the serializer: class PictureSerializer(GeoFeatureModelSerializer): class Meta: model = Pictures geo_field = "point" fields = ('picture', 'processed', 'flagged', 'point') Here is the model: class Pictures(models.Model): objects = models.GeoManager() picture = models.ImageField(null=True, default=None, blank=True) processed = models.BooleanField(default=False) flagged = models.BooleanField(default=False) point = models.PointField(null=True, default=None, blank=True) Can anyone please tell me how to serialize the point field correctly? Maybe I need to change the JSON format? Maybe I need to change the serializer? -
Deploying django app with static content on AWS EB
I am trying to deploy a django app with static files to AWS EB following this guide https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/ I have the standard folder structure with project and app set up. I am using sqlite so no database set up on AWS is required. My python.config file looks like this container_commands: 01_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "myappproject.settings" "PYTHONPATH": "/opt/python/current/app/myappproject:$PYTHONPATH" "ALLOWED_HOSTS": "myappawseb.eu-central-1.elasticbeanstalk.com/" "aws:elasticbeanstalk:container:python": WSGIPath: "myappproject/wsgi.py" NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" I previously did pip freeze and have my requirements.txt file in the project folder. After eb deploy I get an import error for my views.py on myapp.eu-central-1.elasticbeanstalk.com/: ImportError at / cannot import name 'views' Request Method: GET Django Version: 1.11.3 Exception Type: Traceback: ImportError Exception Value: cannot import name 'views' Exception Location: /opt/python/current/app/myapp/views.py in , line 5 Python Executable: /opt/python/run/venv/bin/python3 Python Version: 3.4.3 Python Path: ['/opt/python/run/venv/lib64/python3.4/site-packages', '/opt/python/run/venv/lib/python3.4/site-packages', '/opt/python/current/app/myapp, '/opt/python/current/app', '', '/opt/python/run/baselinenv/local/lib64/python3.4/site-packages', '/opt/python/run/baselinenv/local/lib/python3.4/site-packages', '/opt/python/run/baselinenv/lib64/python3.4', '/opt/python/run/baselinenv/lib/python3.4', '/opt/python/run/baselinenv/lib64/python3.4/site-packages', '/opt/python/run/baselinenv/lib/python3.4/site-packages', '/opt/python/run/baselinenv/lib64/python3.4/plat-linux', '/opt/python/run/baselinenv/lib64/python3.4/lib-dynload', '/usr/lib64/python3.4', '/usr/lib/python3.4'] My eb error log looks like this: File "<frozen importlib._bootstrap>", line 2237, in _find_and_load [Thu Oct 26 23:41:07.082933 2017] [:error] [pid 10378] File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked [Thu Oct 26 23:41:07.082935 2017] [:error] [pid 10378] File "<frozen importlib._bootstrap>", line 1200, in … -
Understanding cookies, sessions, and subdomain routing in django
I've read a lot of answers here but none of them really go in depth of what's happening and I don't have a good understanding due to this. If I have a django app hosted on heroku. Let's say the appname is "name" so it's available and being served at name.herokuapp.com. Now, let's say I have multiple domains 1.com1, 2.com, etc which all point to this app. My login on the main domain 1 won't be shared across 2 etc. Similarly, session data such as a session based shopping cart wouldn't be either. But, let's say I changed these to subdomains and set the SESSION_COOKIE_DOMAIN to be .1.com and had the other domains 2 and beyond go to subdomains. So, now 2.1.com etcetera. Would the login be shared since the cookie is set at the top level domaina nd similarly the session data such as the shopping cart? Now, if I can't change these to subdomains how would I solve the above issues of login and sharing the cart between the domains pointed to my app? -
Is it safe to use @csrf_exempt to send data from a Wordpress (or other external) site if there is no user authentication?
I’m making a simple Django app that takes data from a user submitted form, creates an image based on the data and displays the image to the user. The problem is that the form needs to be on an existing Wordpress site. The app will only perform this one task, and the image will be discarded, so there will be no user authentication, sessions, or anything like that. Is it safe to use @csrf_exempt to make this work? Some of the answers to Do CSRF attacks apply to API's? suggest that a csrf token is not necessary if there is no user auth. However, some of the answers also suggest that there should be some other form of authentication in place instead. And the answer to Django - CSRF verification failed - send data from form on static website to my django app suggests that there is a way to add a csrf token to a third party site, and this would make @csrf_exempt unnecessary. Which of these approaches is right? If my understanding of csrf is correct it makes sense to me that there is no risk of csrf without user authentication. Such an attack would not be able … -
How do you prefetch django user groups for permissions checks
I have a class that has permissions are checked over and over. Each time the request user's groups are re-queried from the database instead of caching them making thing really slow. How can I prefetch or cache the groups in the request user? class Object(models.Model): ... def has_object_read_permission(self, request): if ('test' not in request.user.groups.all()): return False return True -
Extendings Django's UserCreationForm
I'm trying to extend Django's django.contrib.auth.forms.UserCreationForm to include email and name fields. My similar extension of the UserChangeForm works fine, but UserCreationForm still only shows the default username, password1, and password2 fields. Any ideas what I'm doing wrong? forms.py class AuthorCreation(UserCreationForm): class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email', 'groups', 'is_staff') class AuthorChange(UserChangeForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'groups', 'is_staff') admin.py class AuthorAdmin(UserAdmin): """Admin class for creating and managing Authors""" inlines = [AuthorInline] fieldsets = ( (None, { 'fields': ('username', ('first_name', 'last_name'), 'email', 'password', 'groups', 'is_staff') }), ) class Media: css = { 'all': [ 'css/codenotes-admin.css', ] } def get_form(self, request, obj=None, **kwargs): if obj is None: return forms.AuthorCreation else: return forms.AuthorChange admin.site.unregister(User) admin.site.register(User, AuthorAdmin) Again, the AuthorChangeForm correctly displays all the fields, but AuthorCreationForm only displays the username, password1, and password2 fields (plus the inline forms, which works fine on both). I assume the problem is with the fieldsets, but I can't figure it out from the docs.