Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using instance data in signal handler django
Can I user model instance data in signal handler to create different profile models as per user type? I tried it but its not working and only one kind of profile is being created the Student profile even if the user_type is institute. In models.py class User(AbstractUser): type_choices = ( ('Student', 'Student'), ('Institute', 'Institute') ) user_type = models.CharField(max_length=2,choices=type_choices,default='Student') class Profile(models.Model): bio = models.CharField(max_length = 200, null = True, blank = True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) image = models.ImageField(upload_to=user_image_path, blank=True) class Iprofile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_incorporation = models.DateField(null=True, blank=True) logo = models.ImageField(upload_to=user_image_path, blank=True) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def update_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == "Student": Profile.objects.create(user=instance) instance.profile.save() elif instance.user_type =="Institute": Iprofile.objects.create(user=instance) instance.iprofile.save() @receiver(post_save, sender=settings.AUTH_USER_MODEL) def save_user_profile(sender, instance, **kwargs): if instance.user_type == "Student": instance.profile.save() elif instance.user_type == "Institute": instance.iprofile.save() In forms.py user_type_choices = ( ('Student', 'Student'), ('Institute', 'Institute'), ) class SignUpForm(forms.Form): user_type = forms.ChoiceField(choices = user_type_choices) def signup(self, request, user): user.user_type = self.cleaned_data['user_type'] user.save() -
TypeError: a bytes-like object is required, not 'str' when using urlparse
I'm getting this error on my model function. Here's my model: def Post(models.Model): ... imageURL = models.URLField(null=True, blank=True) @property def video_source(self): print(self.imageURL) #https://www.youtube.com/watch?v=abcdefghi t = urlparse(self.imageURL).netloc #this line fires the error domain = '.'.join(t.split('.')[1:]) print(domain) return True I'm trying to create a function for my template like so: {% if instance.imageURL.video_source %} #something {% else %} #something else {% endif %} any idea what the problem is? -
parsed_pattern.pattern.groups = 1 AttributeError: can't set attribute
Here is my code def convert_regexp_to_noncapturing_parsed(parsed_pattern): res_data = [] for key, value in parsed_pattern.data: if key == sre_constants.SUBPATTERN: index, subpattern = value value = (None, convert_regexp_to_noncapturing_parsed(subpattern)) elif key == sre_constants.GROUPREF: raise ValueError('Regular expressions with back-references are not supported: {0}'.format(pattern)) res_data.append((key, value)) parsed_pattern.data = res_data parsed_pattern.pattern.groups = 1 parsed_pattern.pattern.groupdict = {} return parsed_pattern here in line parsed_pattern.groups = 1 i'm getting a error AttributeError: can't set attribute I dont know whats wrong -
"detail": "Method \"GET\" not allowed. on calling endpoint in django
I'm using django.rest_framework. I have a get_or_create method for a particular view, class LocationView(views.APIView): def get_or_create(self, request): try: location = Location.objects.get(country=request.data.get("country"), city=request.data.get("city")) Response(location, status=status.HTTP_200_OK) except Location.DoesNotExist: serializer = LocationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the location Model, class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class Meta: unique_together = ('country', 'city') This is my url, url(r'^location/$', LocationView.as_view(), name='location'), When I call this endpoint in the following way, http://127.0.0.1:8000/api/v1/bouncer/location/?country=USA&&city=Sunnyvale&&latitude=122.0363&&longitude=37.3688 This is what I get, { "detail": "Method \"GET\" not allowed." } What am I missing here. -
Adding a variable into a a path in django
I am making my first website in Django but my tutorial was created long ago. I need to add the variable question_id into the following path: path('<question_id [0-9]>/',views.detail, name = "detail") the function detail looks like this: def detail(request, question_id): return HttpResponse('Leo is the best') This is what the error looks like: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <question_id = [0-9]>/ [name='detail'] polls/ <question_id>[0-9]/result [name='result'] polls/ <question_id>[0-9]/vote [name='vote'] -
ValueError at /adm/appt/ Expected table or queryset, not str
Getting the following error when trying to use django_tables2 ValueError at /adm/appt/ Expected table or queryset, not str I have run all the updates and upgrades on the packages Error Request Method: GET Request URL: http://127.0.0.1:8000/adm/appt/ Django Version: 2.0.3 Exception Type: ValueError Exception Value: Expected table or queryset, not str Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\django_tables2\templatetags\django_tables2.py in render, line 147 Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.6.3 View: Think i'm initializing the table properly as well as sending the queryset def ApptView(request): table = AppointmentTable(Appointment.objects.all()) model = Appointment table_class = AppointmentTable filterset_class = AppointmentFilter RequestConfig(request).configure(table) return render(request,'adm/index2.html', {'table': table}) HTML {% load render_table from django_tables2 %} <body> {% render_table AppointmentTable %} </div> </body> Tables import django_tables2 as tables from .models import Appointment class AppointmentTable(tables.Table): class Meta: model = Appointment template_name = 'django_tables2/bootstrap.html' -
Get model name from instance
How can I get a model name as a "string" from a model instance. I know you can do something like type(model_instance) but this is returning the class itself as an object <Model_Name: > not as a string. -
Filter records from parent table to appear in the "Add new" page as a select list
Let's say I have two tables: customer and city. I have customer.city_id field as a foreign key that references city.id. class Customer(model.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) city_id = models.ForeignKey(City, models.DO_NOTHING, db_column='id' class Meta: managed = False db_table = 'customer' def __str__(self): return self.name class City(model.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=32) added = models.PositiveIntegerField() # value is 1 or 0 class Meta: managed = False db_table = 'city' def __str__(self): return self.name When I add a new customer, I can pull all the records (city names) and display them in the add new customer page. How can I get only the cities that their city.added value = 1 and ignore those with value 0, Preferably in the models.py file or in the admin.py file. -
How to get the slug STRING value in django models?
Basically, I have 3 classes (Vehicle, Car and Motorcycle, these 2 last extend the first one)... In the Vehicle class there's the main_image attribute which is a models.ImageField type, as you can see bellow: class Vehicle(models.Model): def __str__(self): return self.title [...] main_image = models.ImageField( upload_to = 'media/images/' + str(slug) + '/', verbose_name = 'Foto principal', null = False ) So, the str(slug) doesn't work properly, 'cause when I upload an image, it is always uploaded to /media/images/<django.db.models.fields.SlugField> when it should actually upload to /media/images/(object-slug-value)/ I've tried many different things but any of them worked the way I wanted. How can I get the string value from the slug attribute? -
Django on GAE - How to automatically 'migrate' on deploy?
Django v1.11 Postgresql v9.6 Currently, I use 2 Google CloudSQL databases, one for development and one for production. Whenever I make changes to my models, I run python manage.py migrate to update the tables in the development database. This migration does not affect the production database, however. Now, whenever I git push changes to my Django project, TravisCI automatically runs tests and deploys the code to Google App Engine. Currently, it runs on GAE flexible environment (so I can use Python 3.5) What I want to have is for Travis or GAE to automatically run python manage.py migrate on the production database before runserver. However, I can't figure out how to run custom commands during a deploy. I've tried looking around GAE and Travis documentation and adding scripts to .travis.yml and app.yaml, but to no avail. As of now, anytime there is a model change, I have to migrate the production database locally in a very hacky way. Ideally, GAE will migrate at the beginning of every deploy. -
Django 2, Celery 4.1 ModuleNotFoundError: No module named djcelery
I am running into a ModuleNotFound error using Django and Celery. I have a post endpoint using django rest framework that runs a celery task to parse and store json. I can serve pages fine, but when I do a post I get the following error: Exception Type: ModuleNotFoundError at /app/v1/results Exception Value: No module named 'djcelery' At first I thought that maybe I had a versioning issue, so I checked my packages, but I'm on the latest and don't see any outstanding conflicts. I do see the djcelery is reference in the loaders init.py of the celery projects: https://github.com/celery/celery/blob/master/celery/loaders/init.py amqp (2.2.2) billiard (3.5.0.3) celery (4.1.0) certifi (2018.1.18) Django (2.0.3) django-celery-results (1.0.1) django-filter (1.1.0) django-pyodbc-azure (2.0.3.0) djangorestframework (3.7.7) kombu (4.1.0) Markdown (2.6.11) mod-wsgi (4.6.2) pip (9.0.1) pyodbc (4.0.22) pytz (2018.3) setuptools (38.5.1) vine (1.1.4) wheel (0.30.0) My project follows the core of the Django first steps http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#django-first-steps: Proj - proj - __init__.py - celeryapp.py - settings.py - urls.py - app - models.py - tasks.py - views.py - urls.py - manage.py For all of my code I started with what was in the first steps tutorial, but have made a few changes running into issues and finding post as well as … -
Django Elasticbeanstalk Application returns 404 during autoscale
I have a django application running on elastic beanstalk. The application deploys and works fine when I deploy from the command line. However, during an autoscale, healthcheck on the new instance created always return 404 from the access_logs. "GET /health/ HTTP/1.1" 404 221 "-" "ELB-HealthChecker/1.0" Interestingly, the application eventually loads after about 20 minutes. See my wsgi.conf file below. Is there something I am doing wrong? LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On <VirtualHost *:80> Alias /static/ /opt/python/current/app/staticfiles/ <Directory /opt/python/current/app/staticfiles/> Require all granted </Directory> WSGIScriptAlias / /opt/python/current/app/myapp/wsgi.py <Directory /opt/python/current/app/> Require all granted </Directory> Header always set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE, PATCH" Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept, origin, authorization, accept, client-security-token, Authorization" WSGIDaemonProcess wsgi processes=3 threads=20 display-name=%{GROUP} \ python-path=/opt/python/current/app:/opt/python/run/venv/lib/python2.7/site-packages:/opt/python/run/venv/lib64/python2.7/site-packages user=wsgi group=wsgi \ home=/opt/python/current/app WSGIProcessGroup wsgi RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule !/api/v1.0/church/health/ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] </VirtualHost> WSGIPassAuthorization On -
Django app deployed to Digitalocean 502 Bad Gateway
I have copyed my django app (that works locally) to a droplet from Digitalocean where I have installed the django 1-click app. I get 502 Bad Gateway and can't manage to understand why. 2018/03/13 22:25:06 [error] 2104#2104: *44 upstream prematurely closed connection while reading response header from upstream, client: 139.162.251.201, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2018/03/13 22:28:19 [error] 2104#2104: *46 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:31:51 [error] 2104#2104: *49 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:32:05 [error] 2104#2104: *52 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:18 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:23 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET … -
Django - call view method when including template
Is it possible in Django to have a view method associated to template, so when I {% include %} a child template in my parent template, the child template can call it's view method and get some data? Or the only way is to have a single view method associated to url that collects data for every template? -
Spaces in url query not getting decoded in django
I have the following URL query - http://localhost:8000/api/passenger-census/?public_location_description==SW%206th%20&%20Salmon however, the spaces are not being decoded and the resulting query that django parses is GET /api/passenger-census/?public_location_description=SW%206th%20&%20Salmon which returns a null since the string to be found is "SW 6th & Salmon". Django code views.py - class PassengerCensusViewSet(viewsets.ModelViewSet): queryset = PassengerCensus.objects.all() serializer_class = PassengerCensusSerializer filter_backends = (SearchFilter,DjangoFilterBackend,OrderingFilter,) search_fields = ('route_number', 'direction','service_key','stop_seq', 'location_id','public_location_description',) filter_fields = ('summary_begin_date','route_number','direction','service_key','stop_seq','location_id', 'public_location_description','ons','offs','x_coord','y_coord','geom_2913','geom_4326',) ordering_fields = '__all__' serializer.py class PassengerCensusSerializer(serializers.ModelSerializer): class Meta: model = PassengerCensus fields = '__all__' What is the issue here? -
Django 2.0 ipn callback => Forbidden (CSRF cookie not set) despite @csrf_exempt
I use Django 2.0 and I want to accept an IPN from a remote third-party on my url http://example.com/ipn/ This is my url: urlpatterns = [ ... # url for ipn url(r'^ipn/$', views.index, name='ipn'), ... ] This is my view: # decorator from django.views.decorators.csrf import csrf_exempt @csrf_exempt def ipn(request): ''' process ipn call from merchant''' ipn = get_data_from_ipn(request) in my settings.py: ALLOWED_HOSTS = ['ipnsender.net'] ... I'd like that only the ipn view does not use csrf, but I can not understand why I do have the following error although the documentation only tells you need @csrf_exempt decorator. My log tells me every time: Forbidden (CSRF cookie not set.): /ipn/ [13/Mar/2018 22:36:50] "POST /ipn/ HTTP/1.1" 403 2868 -
Django Admin looks ugly - Impossible to load any static files
I'm working on a Django REST project and I used to send my code on Git server. Every css and static files was working fine. Now that I've fetch the project on a new pc, it's now impossible to load any css or js files either on the admin page or the home page. Whenever I load the Django admin page, I get this kind of error in the console: GET http://localhost:8080/static/admin/css/base.css net::ERR_ABORTED And the css doesn't load I also got a similar error when I load the home page: GET http://localhost:8080/static/css/main.css net::ERR_ABORTED I run my project on ubuntu 16.0.4 in a virtualenv (using vagrant) and I use Django 3.5. Here is my directory tree And here is a sample of my settings/base.py file : STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join('./', 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join('./', 'media') The images on media folder load very well. I don't know what's wrong, I've tried many workarounds on Google and many other SO related issues and nothing work. I'm lost, please help ! -
Django multiple image upload is possible?
Firstly sory for my bad english. I use python Django framework and ı am use StackedInline when uploading photos. I need to upload the images collectively, not individually. Is this possible? -
media files aren't served to template in django
I trying to serve media files to the template but make them inaccessible from url, and the opposite is happening when i do: http://localhost:8000/media/210000002A.tif I get prompted to download the files so it is being served when accessing from the address bar but in the template I have: <img src="{{ MEDIA_URL }}210000002A.tif"/> and it is not working my dir contains -project -app -media -static -template and i have this is my urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and this in my settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') -
Adding cloumns to an existing django table witha . postgreSQL db
Ive been searching around for how to do this an di think i broke my table I tried adding dealership = models.ForeignKey('Employee', null=True) To the field to the models.py, since i noticed thats where my other column fields were, and now the entire table is gone. After some more research i saw that its supposed to be added to the migrations location and then run $ python models.py migrations My question is how do i properly add the column, the db already has the information for the column data i cant imagine its that difficult to simply pull that info and how do i get my table back? The table seems to have vanished after i added to the models.py manually and when i tried undoing it just never came back. -
Save object data in list and use in parameter
I need to use the object details of obj to save in a list or some sort to use as a parameter in my send_order_verification() function. def order(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): obj = form obj.save() send_order_verification(order_details, obj.email) This is my send_order_verification() function: def send_order_verification(order_details, email): return send_mail( ('Thank you for your order #{0}', x), ('Name: {0}\nEmail: {1}\nTelephone: {2}', x, y, z), [settings.EMAIL_SEND_TO], ['{0}' % email] ) How could this be done? I tried with order_details = [obj.name, obj.email, obj.telephone] but can't access it with order_details[0] and so forth. -
Django app only works on Debug=True Heroku
I thought I had this solved but I guess not. I've got my Django app on Heroku, and it works perfectly with DEBUG = True but does not work with DEBUG = False. This tells me that I have a problem with my static files, as Django doesn't support static files during DEBUG = False. For that, I'm using Whitenoise. Would someone mind reviewing my settings files to see where I've gone wrong. First my file structure: POTRTMS | +---config | | | urls.py | views.py | wsgi.py | +---settings | | | | | base.py | | local.py | | production.py base.py import os from django.utils import timezone import dj_database_url from decouple import config from .aws.conf import * import django_heroku GOOGLE_MAPS_API_KEY = config('GOOGLE_MAPS_API_KEY') EASY_MAPS_GOOGLE_MAPS_API_KEY = config('GOOGLE_MAPS_API_KEY') BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] print(STATICFILES_DIRS) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Application definition INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn … -
using foreign key set in django models django rest framework
I am having an interesting problem. I am using the foriegn key call in the relations mananger. I.e. if I want all the objects from a related model known as hamsters the call would be hamsters_set now here is a working model attached to a serializer everything is working in this implementation. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True) class Meta: model = SearchCity fields = ('pk','city','searchneighborhood_set') read_only_fields =('pk','city', 'searchneighborhood_set') but with this new model in which I am trying to do the same thing, I am getting an attribute error class Room(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) online = models.BooleanField(default=False) description = models.CharField(max_length=1000, blank=True, null=True) privateroom = models.BooleanField(default=False) semiprivateroom = models.BooleanField(default=False) seatedcapacity = models.CharField(max_length=10, null=True, blank=True) standingcapacity = models.CharField(max_length=10, null=True, blank=True) minimumspend = models.PositiveSmallIntegerField(blank=True, null=True) surroundsoundamenity = models.BooleanField(default=False) outdoorseatingamenity = models.BooleanField(default=False) stageamenity = models.BooleanField(default=False) televisionamenity = models.BooleanField(default=False) screenprojectoramenity = models.BooleanField(default=False) naturallightamenity = models.BooleanField(default=False) wifiamenity = models.BooleanField(default=False) wheelchairaccessibleamenity = models.BooleanField(default=False) cocktailseatingseatingoption = models.BooleanField(default=False) classroomseatingoption = models.BooleanField(default=False) ushapeseatingoption = models.BooleanField(default=False) sixtyroundseatingoption = models.BooleanField(default=False) boardroomseatingoption = models.BooleanField(default=False) theaterseatingoption = models.BooleanField(default=False) hallowsquareseatingoption = models.BooleanField(default=False) class RoomImage(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) order = models.PositiveSmallIntegerField(blank=True, null=True) imageurl = … -
All urls not showing up on django.rest_framework documentation
This is my main urls.py urlpatterns = [ url(r'^', include_docs_urls(title='Foot The Ball API')), url(r'^admin/', admin.site.urls), url(r'^api/v1/aggregator/', include('aggregator.urls')), url(r'^api/v1/bouncer/', include('bouncer.urls')), ] These are the urls in bouncer.urls urlpatterns = [ url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout'), url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='register'), url(r'^location/$', LocationView.as_view(), name='location'), ] I'm using rest_framework.documentation. Strangely only login and logout view show up in the documentation home page. Can someone help as to what's going on here? -
Nginx, Django, and Gunicorn still receiving nginx default page
I am having trouble setting up my webserver to serve up my Django web application. I read this tutorial to help me get started, but alas my server only shows the default nginx "welcome page". My gunicorn_start file looks like this: source /home/ubuntu/blog/my_blog/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /home/ubuntu/blog/my_blog/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=$SOCKFILE \ --log-level=debug \ --log-file=- My nginx sites-avaliable file looks like this: upstream my_site_server{ server unix:/home/ubuntu/blog/Website/my_site/my_site.sock; } server { listen 80; server_name 13.229.113.194; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/blog/Website/my_site/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://my_site_server; break; } } } GUnicorn does create the my_site.sock file, but nginx seems to be denied when trying to read it. The error being: 2018/03/13 19:50:11 [error] 17713#0: *1 connect() to unix:/home/ubuntu/blog/Website/my_site/my_site.sock failed (111: Connection refused) while connecting to upstream, client: 74.43.49.203, server: goggleheadedhacker.com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/blog/Website/my_site/my_site.sock:/", host: "goggleheadedhacker.com" 2018/03/13 19:50:24 [error] 17713#0: *3 connect() to unix:/home/ubuntu/blog/Website/my_site/my_site.sock failed (111: Connection refused) while connecting to upstream, client: 74.43.51.94, server: goggleheadedhacker.com, …