Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing JS in Django templates
I have a list of ingredients, for every ingredient, I would like to give the option to delete the current ingredient via using a popup that asks the user "are you sure they want to delete this?" If confirmed, I want that ingredient to be deleted. Currently, no matter which ingredient I choose to delete, it always the deletes the first ingredient in the list. For example, if the list of ingredients is ['cheese', 'lettuce'], I click remove ingredient under lettuce, and it will still delete cheese. I've never used javascript in Django templates before, I think I need to pass the ingredient into the openPopup function, but I'm not sure how to do it, any help would be appreciated! I've looked at the Django docs for using JS in templates but it's not crystal clear to me. How do I go about doing this? <div class="ingredient-container"> {% for ingredient in ingredients %} <div class="ingredient"> <b>{{ ingredient|title }}</b><br> <small><a href="{% url 'core:edit_ingredient' ingredient.id %}">Edit Ingredient</a></small> {% empty %} {% endfor %} <!-- This button opens the popup up to confirm deletion of the ingredient--> <button class="remove" type="submit" onclick="openPopup()">Remove Ingredient</button> <div class="popup" id="popup"> <h2>Delete Confirmation</h2> <p>Are you sure you want to … -
Django multiple models that have a foreign key to another model
Example: A system that processes different types of csv files. The different types of csv files have different content inside. So the current way im thinking about modeling this is: File model that stores some generic info about each file processed, like the name, date etc. class File(models.Model): name = models.CharField() Then models that stores the content for each type of file and these models link back to the File model: class Example1File(models.Model): file = models.ForeignKey(File, related_name=example_file_1_content) ... (all columns for this file) class Example2File(models.Model): file = models.ForeignKey(File, related_name=example_file_2_content) ... (all columns for this file) Is there an easy way for example to loop through the files table and get the content for each file and django would just know in which table to go look? for file in File.objects.all(): file.??? Or would I only be able to do this by storing a type field on the file and then getting the content with the reverse relationship like this. for file in File.objects.all(): if file.type == FileTypes.ExampleFile1: file.example_file_1_content But what if there are a lot of different file types? Im still in the process of learning about how django handles relationships/reverse relationships so I might just not be there yet … -
django issue : i get erro 404 page note found
I try to write a django code fo a registration page the error snip and code: enter image description here """ """ -
Django configuration in PyCharm
After few years using Mac and Linux for my dev I have to pass on windows now. I have a project which run on docker-compose and that works very well on Mac and Linux but on windows I have some configuration problems with PyCharm. If I run the docker compose by hand: works well If I run the project threw the "run" or "debug" in pycharm: works well But when I try to run the "manage.py command" threw pycharm I got this traceback: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. That would be just a small problem but it seems that Pycharm does not recognize django in the docker interpreter because all the django specific code is highlighted and the autocompletion doen't work anymore. Basic example: if I use {% load ... %}, the load tag is not recognized. It is definitly a problem in the configuration of pycharm but I can not find where it is. Any idea? -
How can I retrieve my post request using JavaScript
I have two projects, the first one is Node.JS. jsonobj = JSON.stringify(generateMockData) xhrToSoftware.send(jsonobj); xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true); xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhrToAPI.send(jsonobj); It's sending data to the second project Django Python. I can receive the data using my views.py. post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible? for example: <script> //get the data that posted by the node.js </script> UPDATE: I tried using the answers below like this one: fetch('http://127.0.0.1:8000/path/') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => console.error(error)); but I'm having an error it says that: SyntaxError: Unexpected token '<', "<!-- <d"... is not valid JSON I think that's because I'm returning an html file in my views.py: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return render(request, 'waterplant/iot/data.html') so, I change it to jsonresponse like this: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return JsonResponse({"msg": value}, status=200) After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. … -
Example of jqgrid with python
So I've cloned this https://bitbucket.org/romildo/django-jqgrid-demo.git as I am looking for a working example of jqgrid with django. I've been updating the code (as this seems like it was written for a version 2 of django and I'm workng on 4.1) I'm completely stumped by the lines from jqgrid import JqGrid giving me this error ModuleNotFoundError: No module named 'jqgrid' I cannot find a reference to jqgrid within pip and I cannot install one (jqgrid is not a python package) I understand that jqgrid is a javascript component around jquery but how do I get that to work in Python I have google for django-jqgrid and on youtube. None of the answers provide enough information to get a simple working example up. There seems to be an assumption that everything is installed and I'd like to understand what is required where and how to reference What am I missing? -
Convert SQL Query into Django Query ORM
I have this sql query, I need to use Django ORM format delete from foodies_orderstall as os where os.order = <order-id> and not exists ( select * from foodies_ordermenu as om where om.order_stall = os.id ); -
Converting a complex dictionary list to a dictionary
I would like to convert this dictionary list below into a dictionary data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } ] And I would like to have this result, just the starting brackets that we change to {..} data={ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } } -
ImageField storage options based on settings
I am using django-storages with the Azure backend. I would like to use the local provided Django solution when running locally and the Azure storage when running in production. How would I change this based on the settings? Do I just use an IF statement below these? # local image = models.ImageField(upload_to="profile_pics", blank=True, null=True) # production image = models.ImageField(upload_to="profile_pics", blank=True, null=True, storage=AzureMediaStorage()) -
What's the diffrence bettwen timezone.now and auto_now_add parameters in DateTimeField field in Django models?
I'm writing my first Django app - blog. When creating Post model I'm asked to create publish and created fields with timezone import. publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) It's explained that "By using auto_now_add, the date will be saved automatically when creating an object" and "timezone.now returns the current datetime in a timezone-aware format". So it seems to me that they both same job. Why not use default=timezone.now in both fields? What's the difference? It's my first question so sorry in advance if I made some mistakes. -
PgAdmin Queries fast Django orm very slow
When I write a query via pgAdmin, I get very fast results, but the queries made with Django orm are very heavy, what could be the reason? database connection as below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user', 'USER': 'users', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'data': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'data', 'USER': 'datas', 'PASSWORD': 'toor', 'HOST': '192.168.1.1', 'PORT': '5432', }, } The query I sent with pgAdmin PgAdmin 97 msec SELECT COUNT(id) as noti FROM notification WHERE created_at BETWEEN '2022-11-15 00:00:00' AND '2022-11-15 23:59:59' The query I sent with django Django 20.44 s from django.utils.timezone import get_current_timezone from datetime import datetime get_today = datetime.now(tz=get_current_timezone()) Notification.objects.using('data').filter(created_at__year=get_today.year, created_at__month=get_today.month, created_at__day=get_today.day).count() I'm making multiple database connections with Django the second database is running very heavy query how can I fix this -
solr search returning 3 result but when i it try to iterate object is not working
I have implement solr search and try to run this in a shell when i fetch all record it gave count 3 it's correct but when i try to display title and body it's gave me an error please let me help this solr-9.0 python3 and django 4 for solr > post_text.txt templates/search/indexes/blog/post_text.txt {{ object.title }} {{ object.tags.all|join:", " }} {{ object.body }} in search_indexes.py from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish') def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().published.all() Now in shell from haystack.query import SearchQuerySet from blog.models import Post sqs = SearchQuerySet().models(Post).all() sqs.count() # return 3 but when i run this loop then geting error for x in sqs: x.object Traceback (most recent call last): File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2018, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 2, in <module> File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/haystack/models.py", line 81, in _get_object self._object = self.searchindex.read_queryset().get(pk=self.pk) File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/query.py", line 636, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/query.py", line … -
How to fix IntegrityError 1048 in django
So, i just made a upload feature to insert data into databases. Data inserted successfully into the database but show an error messages Before, i tried to change the column name on my excel .. i thought it was the problem, but after i undo the changes to default .. error still happened. Here's my view code Views.py if 'uploaddatasiswa' in request.POST: dataset = Dataset() new_siswa = request.FILES['uploadSiswa'] if not new_siswa.name.endswith('xlsx'): messages.info(request, 'Format tidak valid!') else: imported_data = dataset.load(new_siswa.read(),format='xlsx') for data in imported_data: tambah_siswa = modelUser( username = data[0], namadepan = data[1], namabelakang = data[2], password = data[3], email = data[4], jeniskelamin = data[5], tanggallahir = data[6], agama = data[7], alamat = data[8], telepon = data[9], role = "siswa" ) tambah_siswa.save() return HttpResponseRedirect("/admin/daftarsiswa") return render(request,'tambahsiswa.html') Models.py class modelUser(models.Model): namadepan = models.CharField(max_length=200, null=False, blank=False) namabelakang = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) password = models.CharField(max_length=200, null=False, blank=False) email = models.CharField(max_length=200, null=False, blank=False) jeniskelamin = models.CharField(max_length=200, null=False, blank=False) tanggallahir = models.DateField() agama = models.CharField(max_length=200, null=False, blank=False) alamat = models.CharField(max_length=200, null=False, blank=False) telepon = models.CharField(max_length=200, null=False, blank=False) jumlahkelas = models.CharField(max_length=200, null=True, blank=True, default=0) role = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.username Tables -
How can I get value from one function in another function in Django, views()
Hello I am new to Django I want to get latitude and longitude from myview1 function to myview function so that I can Post that values and put into the relevant code. PLease Can anyone guide me regarding this? def my_view1(request): latitude='latitude' longitude='longitude' context = {'latitude':latitude, 'longitude':longitude} my_view(context) return (context) @csrf_exempt @require_http_methods(["POST"]) def my_view(request,context): if request.method == "POST": # value_data=(my_view1(data=request.POST)) value_data=my_view1().objects.all() latitude = request.POST.get(value_data['latitude']) longitude = request.POST.get(value_data['longitude']) # In this example I am reading a file with (time, x, y) as dimensions xarr = xr.open_rasterio('/home/shaheer07/New Rasters/image_factors.tif') # Slice one of the bands img = xarr[0, :, :] #Use the .sel() method to retrieve the value of the nearest cell close to your POI pixel_value = img.sel(x=latitude, y=longitude, method="nearest") image = '/home/shaheer07/New Rasters/image_factors.tif' with rasterio.open(image) as f: # Load metadata meta = f.meta # Use the transform in the metadata and your coordinates rowcol = rasterio.transform.rowcol(meta['transform'], xs=latitude, ys=longitude, zs=None) y = rowcol[0] x = rowcol[1] # Load specific pixel only using a window window = Window(x,y,1,1) raster_values = f.read(window=window) return JsonResponse(pixel_value,raster_values, status=status.HTTP_201_CREATED) else: return JsonResponse('Nothing') -
Django CSRF Protection GraphQL API
I do have a graphqlAPI which I use for CRUD Operations to my database. The authentication is tokenbased. So if an user wants to make cruds (mutations) to my database, it needs a valid token in order to do that. What I dont know is if my graphql API is also protected against CSRF attacks as I exempt this protection with csrf_exempt without csrf_exempt it needs a csrf token. Is there a way to ask for a valid csrf token without sending it over the frontend ? The graphql api is only used for the backend for inserting data into the database in which I cant get the csrf token over the frontend. Backend/Frontend: Django Database: Mongo Thanks -
How to include staticfiles in wsgi django project?
Today I ran into a problem connecting static files to my project. If I run django app with command: python manage.py runserver <ip>:<port>then static files are found. If I run the django app as a wsgi service (systemctl start myapp), I get an error that no static files were found. My project in /home/alevt/health_check. I have next structure of project: ---- client -------- manage.py -------- my.ini -------- app ------------ urls.py ------------ settings.py ------------ wsgi.py -------- health_app ------------ urls.py ------------ static --------------- scripts ----------------- myscript.js ------------ templates --------------- index.html settings.py INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'health_app', ...] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') index.html <script src="{% static 'scripts/myscript.js' %}"></script> ERROR Not Found: /static/scripts/create-table.js my.ini [uwsgi] http = 10.107.14.161:8000 module=app.wsgi:application chdir = /home/alevt/health_check/client/ wsgi-file = /home/alevt/health_check/client/app/wsgi.py virtualenv=/home/alevt/health_check/env single-interpreter = true enable-threads = true master = true And my file of service Description=uWSGI instance to serve myproject [Service] ExecStart=/usr/bin/bash -c 'uwsgi --ini /home/alevt/health_check/client/my.ini' KillSignal=SIGQUIT Type=notify [Install] WantedBy=multi-user.target``` -
Multiple CN LDAP integration in Django project
I want to use multiple CN names in LDAP configurations. I tried to use AUTH_LDAP_REQUIRE_GROUP = "CN=GROUP_NAME1,OU=MSG Distribution Groups,DC=XXX,DC=XXX,DC=XXX" How can I allow multiple groups in CN? Thanks in advance. -
it safe to request url in django? [closed]
I need to check if user submitted url really exists. but I found in some sources that it is not safe to send request from django to the site for this. do you have any suggestions django used to have validation for this but then removed it for security reasons I found code samples: but verify_exists is deprecated for security reasons and has been removed in Django 1.5 -
Cannot connect to redis while using Sentinels in django-redis
Currently I am trying to integrate redis into my django project which is docker based. I was able to integrate redis using the DefaultClient but it doesn't work for SentinelClient My settings.py looks like this: DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' SENTINELS = [ ('redis://9b39d2b0eb5d', 26379), ] # 9b39d2b0eb5d is the ip of redis sentinel container CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis-queue-1:6379', 'OPTIONS': { 'SENTINELS': SENTINELS, # django_redis.client.SentinelClient 'CLIENT_CLASS': 'django_redis.client.SentinelClient', 'CONNECTION_POOL_CLASS': 'redis.sentinel.SentinelConnectionPool', }, } } It doesn't throw any exception, django just gets stuck on loading -
Django rest framework updating a OneToOne field
I have a User model that inherits from AbstractUser which has an email field. And a profile model that has an OneToOne relation with the User model class User(AbstractUser): email = models.EmailField(unique=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(max_length=13, validators=[phone_regex], unique=True, null=True, blank=True) birth_date = models.DateField(blank=True, null=True) about = models.TextField(max_length=2000, blank=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}" view.py class ProfileViewSet(ModelViewSet): .... @action(detail=False, methods=["GET", "PUT"], permission_classes=[IsAuthenticated]) def me(self, request, *args, **kwargs): profile = Profile.objects.get(user_id=request.user.id) if request.method == "GET": serializer = ProfileSerializer(profile) return Response(serializer.data) elif request.method == "PUT": serializer = ProfileSerializer(profile, request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): user = CurrentUserSerializer() def update(self, instance, validated_data): user_data = validated_data.pop('user') user_ser = CurrentUserSerializer(instance=instance.user, data=user_data) if user_ser.is_valid(): user_ser.save() instance.phone = validated_data.get('phone', instance.phone) instance.birth_date = validated_data.get('birth_date', instance.birth_date) instance.about = validated_data.get('about', instance.about) instance.save() return instance class Meta: model = Profile fields = [ 'id', 'user', 'phone', 'birth_date', 'about', ] Now when I try to update a user profile I get status: 400 Bad Request error { "user": { "email": [ "user with this email already exists." ] } } using patch instead of put or partial=True doesn't change anything I still get this error. What can I do here? -
Django: Async POST Request
I am trying to make an async post request using the following approach: First of all, I have defined a fixture to return the client: @pytest.fixture(scope="session") async def async_app_client(): async with AsyncClient() as client: yield client Then i use the client to execute the post request. @pytest.mark.asyncio @pytest.mark.django_db() async def test_single_statistic_task_monitoring( async_app_client, statistic_object_univariate ): print(reverse("statistics-list")) response_post = await async_app_client.post( reverse("statistics-list"), statistic_object_univariate, format="json", ) The error i am getting is: AttributeError: 'async_generator' object has no attribute 'post' However, for examples online many use httpx AsyncClient to make the post request. What is the problem here? -
Cannot create a db from scratch after messing with squashmigrations command in django
I tried to run the squashmigrations command in django and after a while I needed to delete the db and start from scratch (the problem also applies when downloading the repository from GitHub and trying to recreate the project). I get the following error when running python manage.py makemigrations or python manage.py migrate error: (venv) meal_plan main python manage.py makemigrations Traceback (most recent call last): File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: meal_plan_recipe The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 22, in <module> main() File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 443, in execute self.check() File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = … -
Django - Using Case to update datefield but no effect?
I am trying to update two fields: # This works, changes the correct field. DModel.objects.filter(ticker=i['tic']).filter(trail=True).update( last_high_price=Case( When( LessThan(F('last_high_price'), i['high_price']), then=Value(i['last_high_price'])), default=F('last_high_price') ) ) # Using the same condition to change another field in same row. Does not work? DModel.objects.filter(ticker=i['tic']).filter(trail=True).update( date_high_price=Case( When( LessThan(F('last_high_price'), i['high_price']), then=Value(i['last_date_time'])), output_field=DateField(), default=F('date_high_price') ) ) The field date_high_price will not update, I am getting a 200 response. But the field remains null. If I remove output_field then I get >FieldError. -
I have a two Model related to each other and I want to automatically create the data on ModelB upon creating the data in ModelA
I have this User Model Which came from the User of Django Admin class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] def __str__(self): return str(self.id) + " " + self.email And I have another model related to this User model called Promoter model class Promoter(models.Model): user = models.ForeignKey( NewUser, on_delete=models.CASCADE, ) def __str__(self): return str(self.user.id) + " " + self.user.email def email(self): return self.user.email And every time I added a data into User I want to Automatically add also a data into the Promoter model with a link to newly created User This is my code in added/registering a new User class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): newuser = serializer.save() if newuser: return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I try to manually add the newly created User into the front end by having a two different API call both for adding User and adding promoter but I'm getting an error in adding a Promoter data manually (1048, "Column 'user_id' cannot be null") I also try … -
Best way to config gunicorn and nginx with django?
I am trying to deploy django with gunicorn and nginx on heroku, and i'm kinda confused with the way to config gunicorn and nginx, when i searched through internet, they usually create gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target but when i go to gunicorn docs : https://docs.gunicorn.org/en/stable/deploy.html. nginx has a config file like this worker_processes 1; user nobody nogroup; # 'user nobody nobody;' for systems with 'nobody' as a group instead error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # set to 'on' if nginx worker_processes > 1 # 'use epoll;' to enable for Linux 2.6+ # 'use kqueue;' to enable for FreeBSD, OSX } http { include mime.types; # fallback in case we can't determine a type default_type application/octet-stream; access_log /var/log/nginx/access.log combined; sendfile on; upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/tmp/gunicorn.sock fail_timeout=0; # for a TCP configuration # …