Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to track the reason for the error djongo.sql2mongo.MigrationError
I was executing an api (using GET method) of mine that has been created using Django rest framework. http://127.0.0.1:8000/api/v1/savedata Previously it was returning JSON records.When I'm executing this api end point its throwing error => djongo.sql2mongo.MigrationError: tweet_location. Note that tweet_location is a field that I have defined later in my model. Also note that I'm using MongoDB and Djongo connector to connect MongoDb from Django rest framework. /*** view code **/ class TwitterdashappViewSet(viewsets.ModelViewSet): #queryset = TwitterMaster.objects.all() permission_classes = [permissions.AllowAny] serializer_class = TwitterdashappSerializer def get_queryset(self): queryset = TwitterMaster.objects.all() tt = self.request.query_params.get('tt') if tt: condition = Q(tweet_text__contains=tt)&Q(tweet_favorite_count=13) queryset = queryset.filter(condition) return queryset def create(self, request, *args, **kwargs): serializer = TwitterdashappSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) /**** Model File ***/ class TwitterMaster(models.Model): tweet_text = models.TextField(blank=True, null=True) tweet_favorite_count = models.CharField(blank=True, null=True) tweet_location = models.TextField(blank=True, null=True) class Meta: db_table = "twitterdashapp_twittermaster" /** Serializer code */ class TwitterdashappSerializer(serializers.Serializer): tweet_text = serializers.JSONField() tweet_favorite_count = serializers.JSONField() tweet_location = serializers.JSONField() def create(self, validated_data): instance = TwitterMaster.objects.create(**validated_data) return instance -
Elasticsearch faceting for array of dictionaries with elasticsearch-dsl Python
I'm using elasticsearch-dsl to add search functionality to my Python/Django app. I'm pretty new to Elasticsearch and still learning as I go, but I have the base search functionality working. I'm now trying to implement some type of faceting. The model I'm indexing has a field called data, which consists of an array of dictionaries, kind of like tags. They are added by the user when creating a new model instance, so cannot be predefined fields. They will vary from instance to instance, and provide some random supplementary details about the model instance. For example: {'color': 'red', 'size'; 'M'} or {'condition': 'new', 'manufacturer': 'Testco'} class MyIndex(Document): category = Text() title = Text() description = Text() data = Object() class Index: name = 'my-index' Is there a way that I can set up faceting for the data field? Ideally I would like to be able to perform a search, then have filters for color, manufacturer, size and any other keys present in the data lists. So far I've tried this, which (expectedly), returns nothing when I execute the search and check response.facets.data: class ModelSearch(FacetedSearch): doc_types = [MyIndex] fields = ['title^3', 'category'] facets = { 'data': TermsFacet(field='data') } def search(self): return super().search() … -
How to recreate this view as a django model
I have the following models in my application class Semester(models.Model): name = models.CharField(max_length=100, unique=True) start_date = models.DateTimeField() end_date = models.DateTimeField() class Classroom(models.Model): semesters = models.ManyToManyField(to=Semester) name = models.CharField(max_length=100, unique=True) class AvailabilityWindow(models.Model): semester = models.ForeignKey(to=Semester, on_delete=models.CASCADE) start_date_time = models.DateTimeField() end_date_time = models.DateTimeField() optional = models.BooleanField(default=False) label = models.CharField(max_length=100) What i want to achieve is a new model called ClassroomAvailabilityWindow and i want to effectively be like the following view select * from avail_classroom c join avail_classroom_semester cs on c.id = cs.classroom_id join avail_availabilitywindow aw on aw.semester_id = cs.semester_id So that's one record, per classroom, per availability window, but only when that classroom and that semester have are joined by their many-to-many I know that i could use the view as model with managed=False but i want the users to be able to update these records. is there some way to achieve this result in django, possibly using the through option with a ManyToManyField? It's throwing me off because of the extra complexity of Classroom and Semester also being a many to many. Currently I have the model defined as below but with lots of signals set to create and destroy records when other records are created or updated and I am … -
Please enter the correct phone and password for a staff account | Django | Custom User model Authentication fails
I made a custom user model and then created a user using python manage.py createsuperuser and the same user can log in to the admin site. I then used the same model to registered another user using a register HTML page and the user object is being created in the db with the user as staff and active = True which works as expected, still while logging into through both admin login and the custom login page, it returns user object = None and shows the below error. Please enter the correct phone and password for a staff account. Note that both fields may be case-sensitive. Note: django forms isn't used. models.py ''' from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, phone, password=None, is_active=True, is_staff=True, is_admin=False): if not phone: raise ValueError("Users must have a valid phone number") if not password: raise ValueError("Users must have a password") user = self.model(phone=phone) user.set_password(password) user.active = is_active user.staff = is_staff user.admin = is_admin user.save(using=self._db) return user def create_staffuser(self, phone, password=None): user = self.create_user( phone, password=password, is_staff=True ) return user def create_superuser(self, phone, password=None): user = self.create_user( phone, password=password, is_staff=True, is_admin=True ) return user class MyUser(AbstractBaseUser, PermissionsMixin): phone = … -
Using empty related_name to access foreign object fields directly
I have three models that are very similar to eachother, and all have a foreign key to a parent model. Let's call them Applet1, Applet2 and Applet3 and all of them point to AppletGroup. Applet1 and Applet2 has a fields applet_group that is a ForeignKey, ,but Applet3 is not managed by my project, so it's fields are kept the same as fields that managing project for this model has. So I have created additional model Applet3AppletGroup class Applet3AppletGroup(models.Model): applet_group = models.ForeignKey(AppletGroup, on_delete=models.CASCADE, related_name="applet_3") applet_3 = models.OneToOneField(Applet3, on_delete=models.CASCADE, related_name="applet_group_fk") class Meta: indexes = [models.Index(fields=["applet_group", "applet_3"])] And it was working like this for quite some time. But I find it not consistent as right now to access applet_group from Applet1 and Applet2 you simply access .applet_group, but to access it from Applet3 I have to use applet_group_fk__applet_group. I started wondering if it is safe to use related_name="" in OneToOneField? -
php or python. which sould i learn php or python for web development. thank you
I'm a web designer. NOw I want to learn web development, so which one is better for me either php or python. thank you -
django bash script pass requirements as bash arguments
i have created this bash script to create django projects #!/bin/bash PROJECT_NAME=$1 ENV_NAME=$2 PROJECT_DIR="$HOME/$PROJECT_NAME" echo $PROJECT_NAME; echo $ENV_NAME; mkdir -p "$PROJECT_NAME" cd "$PROJECT_DIR" python3 -m venv "$ENV_NAME" . "$PROJECT_DIR/$ENV_NAME/bin/activate" pip install django django-extensions django-debug-toolbar python-memcached djangorestframework pip freeze > "$PROJECT_DIR/requirements.txt" django-admin startproject "$PROJECT_NAME" mkdir -p public cd "$PROJECT_DIR/$PROJECT_NAME" pwd mkdir -p templates mkdir -p static cd templates touch index.html base.html cd .. pwd cd "$PROJECT_NAME" mv settings.py settings_base.py touch settings.py settings_local.py settings_local_sample.py ls when i run source file.sh project_name env it creates the project, i want to pass the requirements of the project as array argument in the bash , how i can do it -
Django Rest Framework Permission class OR Django Middleware - Which is the best option to perform validations?
In my REST application (built in Django REST framework) containing hundreds of APIs, few of those APIs will need to have access token validated before starting its business logic, few of those APIs will need to have a key validated before its business logic. Likewise, there are different levels of validations to be performed on different group of APIs. I came to know that both permission classes and middleware can be used for validation purposes. I would like to know which of these two will be best choice for my requirement. Any related suggestion will help us to choose the effective option. Thanks in advance. -
Is it possible to (how) to lock a domain server behind a password?
I've been working on a django Web app to manage some data for tenants. Things like their personal contact information, government ID, tenancy agreements etc (in other words, very gdpr sensitive info) as well as personally private information such as expense reports. All of this is displayed on the front end of the app as intended seeing as it's supposed to be a private tool for internal company use. At the moment I run it at home on a local machine server so there is little risk involved however for my convenience I'd like to take the Web app live so I can access it while I'm out and about. The issue I'm having is that there really is no reason for anyone other than myself or business associates to use this app and therefore no reason for anyone else to connect to the domain. I've considered making the landing page of the website a login page and locking all other views behind this with CSRF protection but even that is too close for comfort in my opinion as it would mean allowing external entities tor connect to the app. I'd much rather have a server which refuses any connection … -
How to use username as a string in model in django?
I want to use the username of the account in which my django is running as a string to load the model fields specific to that username. I have created a file 'survey.py' which returns a dictionary and I want the keys as the fields. How can I get the username as string? from django.db import models from django.contrib.auth.models import User from multiselectfield import MultiSelectField from survey_a0_duplicate import details, analysis import ast class HomeForm1(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE,) details.loadData(survey_name = user)#<=====This loads the data for specific user<====== global f1 f1=analysis.getQuestion(in_json=False)#<====We get the dictionary here<======== d=list(f1.keys()) ###################assign the filters####################################################### for k in d: q=list(f1[k].keys()) q.sort() choices=tuple(map(lambda f: (f,f),q)) locals()[k]=MultiSelectField(max_length=1000,choices=choices,blank=True) def save(self, *args, **kwargs): if self.pk is None: self.user= self.user.username super(HomeForm1,self).save(*args,**kwargs) def __str__(self): return self.title -
How to open detail view in editable format as shown in admin page?
I'm trying to show the user the details they entered in an editable format as we can see in ./admin/AppName/model_name/id/change I am using Model Forms. view.py @login_required def view_phone_book(request): all_phone_books = PhoneBook.objects.filter(user=request.user) context = { 'all_phone_books': all_phone_books } return render(request, "CallCenter/view_phone_book.html", context) @login_required def detailed_view_phone_book(request, phone_book_id): try: all_contacts = Contact.objects.filter(phone_book__id=phone_book_id) context = { 'all_contacts': all_contacts } return render(request, "CallCenter/detailed_view_phone_book.html", context) except Contact.DoesNotExist: raise Http404("PhoneBook Does Not Exist!") templates ### detailed_view_phone_book.html {% extends 'CallCenter/base.html' %} {% block title %} Detailed Phone Book View {% endblock %} {% block content %} {% if all_contacts %} {% for contact in all_contacts %} <ul> <li><strong>First Name: </strong> {{ contact.first_name }}</li> <li><strong>Last Name: </strong> {{ contact.last_name }}</li> <li><strong>Phone Number: </strong> {{ contact.phone_number }}</li> </ul> {% endfor %} {% endif %} <a href="{% url 'index' %}">Back To Home</a> {% endblock %} I want to show the user the detail view in an editable way so that the changes he makes in detail view is reflected back. I have no idea on how to proceed. -
Access Reverse Relation in django
Models.py class MaterialRequest(models.Model): owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales') flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='flow') kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit') quantity = models.IntegerField(default=0) is_allocated = models.BooleanField(default=False) class AllotmentDocket(models.Model): transaction_date = models.DateField(default=datetime.now) dispatch_date = models.DateField(default=datetime.now) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE, related_name='allotment_sales') parent_company = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_parent') plastic_pallet = models.IntegerField(default=0) side_wall = models.IntegerField(default=0) top_lid = models.IntegerField(default=0) insert = models.IntegerField(default=0) separator_sheet = models.IntegerField(default=0) I wan to access all the material request as well as the ones which have allotment docket to create a table. For e.g I have 5 Material Request and 3 Allotment dockets, i want a table in which there are 5 rows showing all the details of material request's objects and the respective allotment objects Something like this: owner flow kit quantity platic_pallet side_wall top_lid Insert 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 - - - - 5 5 5 5 - - - - -
My djnago applicaion is on nginx. want to install wordpress on /blog
My application is running on ubuntu/nginx. I want to install wordpress on /blog url using nginx. Please let me know the best way. -
'QueryDict' object has no attribute 'first_name'
Have AttributeError 'QueryDict' object has no attribute 'first_name' Get examples from here. I'm don't understand what is the problem models.py class Employee(models.Model): first_name = models.CharField(max_length=30) second_name = models.CharField(max_length=30) patronymic = models.CharField(max_length=30) birth_date = models.DateField() views.py def edit_employee_action(request, employee_id): if request.method == "POST": form = AddEmployeeForm(request.POST) if form.is_valid(): edited = Employee.objects.filter(pk=employee_id) edited.update( first_name = request.POST.first_name, second_name = request.POST.second_name, patronymic = request.POST.patronymic, birth_date = request.POST.birth_date ) else: form = AddEmployeeForm() form = AddEmployeeForm() return render( request, 'edit_employee.html', context={'form': form} ) The parameter employee_id is correct (debugged). -
User Account activation email using Django
I am trying to create User Registration form . User account will be activated by activation email. Following error is coming:- Exception Type: NoReverseMatch at /register/ Exception Value: Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name. I followed following links : https://studygyaan.com/django/how-to-signup-user-and-send-confirmation-email-in-django https://blog.hlab.tech/part-ii-how-to-sign-up-user-and-send-confirmation-email-in-django-2-1-and-python-3-6/ https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef def register(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('website/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user=user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: for msg in form.error_messages: print(form.error_messages[msg]) else: print('in else') form = NewUserForm() return render(request=request, template_name='website/register.html', context={'form': form}) def activate_account(request, uidb64, token): try: uid = force_bytes(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Your account has been activate successfully') else: return HttpResponse('Activation link is invalid!') My html file code {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' … -
Python unittest mysteriously fails because of a second test
I wrote the following unit test, which succeeds when I run it: api\test\test_views.py: class ProductListViewTest(APITestCase): def test_get_products(self): mock_products = MockSet() mock_products.add(MockModel(mock_name='e1', prod_id='1') client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get(reverse('product-list')) serialized = ProductSerializer([{'prod_id': '1'}], many=True) self.assertEqual(response.data, serialized.data) The rest of the code: # api\views.py: from api.models import Product class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer # api\urls.py: ... path('product/', views.ProductListView.as_view(), name='product'), ... However, as soon as I add a second test to the same TestCase, which uses the APIClient, the first test fails (the response.data contains an empty array)!!! def test_second_test(self): client = APIClient() response = client.get('/') self.assertEqual(True, True) if I remove the client.get() call, which doens't even make sense, the first test passes again! -
urllib.error.HTTPError: HTTP Error 403: Forbidden while executing url in python 3.x
I am trying to execute url http://domain/logout with python package urllib, getting urllib.error.HTTPError: HTTP Error 404: Not Found. But when i execute this from browser its working and logging out. urllib.request.urlopen("http://domain/logout") -
Convert fob to tiff in python3
I need to convert the fob file to tiff file in python. I tried with the following code. But it is not working. Could you please anyone guide me to do this task in python. from PIL import Image img = Image.open('/Users/administrator/Desktop/367069291_1.FOB').convert('RGB') img.save('sample.tiff', format='TIFF', compression='tiff_lzw') I am getting this error: raise IOError("cannot identify image file %r" % (filename if filename else fp)) OSError: cannot identify image file '/Users/administrator/Desktop/367069291_1.FOB' -
Django bulk creation: too many terms in compound SELECT
So I am trying to generate a lot of data to test my database and I am using the following statement to generate ItemLists: for __ in range(0, 1000): list_cache = [] for __ in range(0, 10000): list_cache.append(ItemList()) ItemList.objects.bulk_create(list_cache, ignore_conflicts=True) When I try to execute the code the error django.db.utils.OperationalError: too many terms in compound SELECT shows up. It originates from the last line of the code sample. I found that when I move the list_cache outside of both for loops and only call the bulk_create once, it works fine. But as a one million line statement isn't optimal, I tried to split it into smaller batches, as you can see. -
Django - Stuck On Creating a Pricing System
I am making a "booking airbnb" website. On my apartment detail page I have a JQuery UI Date Picker calendar which the user uses to put in start and end dates of the reservation. Once that is done and the user submits the form I want to refresh the site, and when refreshed display the dates the user picked, as long with price per day and total price. In my models I have created: models.py: class Apartment(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) apartment_price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) size = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class ApartmentImages(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="image") image = models.ImageField("image") def __str__(self): return self.image.url class ApartmentPrices(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price") price_start_date = models.DateField(blank=True, null=True) price_end_date = models.DateField(blank=True, null=True) price = models.IntegerField() def __str__(self): return self.apartment.title class Reservation(models.Model): apartment = models.ForeignKey(Apartment, related_name='reservations', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) name = models.CharField(default="", max_length=200) def __str__(self): return self.name this is what I have in my view so far. I have tried many different things, but … -
how to fix the 'django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library'
I am trying to store location of stores in my django database, i tried installing geodjango for the purpose which gives me the above error. i have installed python postgresql osgeow psycopg2 also modified the envirenment variables as per geodjango documentation i tried installing gdal manually using -http://www.gisinternals.com/query.html?content=filelist&file=release-1911-x64-gdal-2-2-3-mapserver-7-0-7.zip the generic core components my settings.py file- import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] INSTALLED_APPS = [ ... 'django.contrib.gis', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'services', 'USER': '*******', 'HOST': 'localhost', 'PASSWORD': '******', 'PORT': '5434', } when i run python manage.py check it gives me the error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. i have already set the gdal ibrary path to gdal data directory, it still isn't working. Please help with whatever's wrong above. Also suggest if there is any other way to store locations in django database? -
How to wait for the twilio callback until it changes from TBD to the actual price?
I am trying to wait for the callback after the price is generated because it comes back as None and my model is Float field, so it throws a value error(ValueError: could not convert string to float: 'one'). To counter this, I thought of using the sleep function. Unfortunately, it did not work when I asked the callback to sleep for 10 sec, so to be safe I asked the callback to sleep for 80 sec. Doing this I realised that Twilio has a timeout of 10 sec, so I got an error(11205 HTTP connection failure) How do I fix this? views.py @login_required def start_campaign(request, campaign_id): # send_campaign.apply_async(args[]) try: campaign = Campaign.objects.get(pk=campaign_id) campaign.status = 'started' campaign.save() account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) phone_numbers = Contact.objects.filter(phone_book=campaign.phone_book) xml_url = 'http://XXX.ngrok.io/call-center/assets/' + str(campaign_id) callback_url = 'http://XXX.ngrok.io/call-center/events/' + str(campaign_id) for phone_number in phone_numbers: call = client.calls.create( method='GET', status_callback=str(callback_url), status_callback_event='completed', status_callback_method='GET', url=xml_url, to=str(phone_number), from_='+1XXX' ) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'all_campaigns': campaign } return render(request, "CallCenter/start_campaign.html", context) def events(request, campaign_id): time.sleep(80) campaign = Campaign.objects.get(pk=campaign_id) campaign.status = 'completed' campaign.save() account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) sid = request.GET.get('CallSid', default=None) detail = client.calls(sid).fetch() check … -
Incorporating Recaptcha Email Form Into Existing Django Project
I would like to incorporate an email form with Google Recaptcha similar or identical to this: https://github.com/maru/django-contact-form-recaptcha Into this existing django github project: https://github.com/justdjango/video-membership Where a website visitor could send emails to a Gmail account that I own directly from the form. I edited the code from the video membership github project to include a contact page for this purpose. How can this be accomplished? video-membership-master/courses/urls.py: from django.urls import path from .views import ContactPageView app_name = 'courses' urlpatterns = [ path('contact/', ContactPageView.as_view(), name='contact') ] video-membership-master/courses/views.py from django.views.generic import TemplateView class ContactPageView(TemplateView): template_name = 'contact.html' video-membership-master/courses/templates/contact.html: {% extends 'courses/base.html' %} {% block content %} <h1>Contact</h1> {% endblock %} -
Is there a way to add class in my html element in Django using forms?
I want to add a class attribute in my template but my code doesn't work. I have already tried the other answers from Stackoverflow but none of these worked for me. class LoginForm(forms.ModelForm): class Meta: model = User fields = ['username','password'] def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={ 'id': 'id_username', 'class': 'input', 'placeholder': 'Enter username'}) The output have no changes at all. -
Nginx can access static folder but not other folders inside it. Throws sub-folder/index.html is not found
I am trying to deploy my django app on google cloud platform. I am using nginx and gunicorn. I am following this guide - https://medium.com/@_christopher/deploying-my-django-app-to-a-real-server-part-ii-f0c277c338f4. I have created a file - le_website - under the folder sites-available. This is the code - ''' server { listen 80; server_name 10.xxx.x.x; location = /favicon.ico {access_log off;log_not_found off;} location = /static/ { root /home/jainpriyanshu1991/learnEarn/le-webiste; } location = / { include proxy_params; proxy_pass http://unix:/home/jainpriyanshu1991/learnEarn/le-webiste/le_website.sock; } } When I try the url myIPaddress/static/ , it works and shows the folders inside it. But it does not work for any subfolder within static. It gives "/usr/share/nginx/html/static/img/index.html" is not found for img folder inside static. Similarly, when I try the url myIPaddress/ it opens the homepage of website but again, it does not work for any other link and gives error. For about page it gives error "/usr/share/nginx/html/about" failed (2: No such file or directory).