Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can not see my image during server side rendering in django, any help would be appreciated
i can not see my image during server side rendering in django, any help would be appreciated. i can not see my image during server side rendering in django, any help would be appreciated. {% if object_list %} {% for post in object_list %} <div id="colorlib-main"> <section class="ftco-section ftco-no-pt ftco-no-pb"> <div class="container"> <div class="row d-flex"> <div class="col-xl-8 py-5 px-md-5"> <div class="row pt-md-4"> <div class="col-md-12"> <div class="d-md-flex"> <a href="single.html" class="img img-2" style="background-image: url({{post.image.url}});"></a> <div class="text text-2 pl-md-4"> <h3 class="mb-2"><a href="single.html">{{post.title}}</a></h3> <div class="meta-wrap"> <p class="meta"> <span><i class="icon-calendar mr-2"></i>June 28, 2019</span> <span><a href="single.html"><i class="icon-folder-o mr-2"></i>Travel</a></span> <span><i class="icon-comment2 mr-2"></i>5 Comment</span> </p> </div> <p class="mb-4">A small river named Duden flows by their place and supplies it with the necessary regelialia.</p> <p><a href="#" class="btn-custom">Read More <span class="ion-ios-arrow-forward"></span></a></p> </div> </div> </div> </div><!-- END--> {% endfor %} {% else %} <p>No post yet!!</p> {% endif %} -
TypeError at / - Django Blog Application
I'm following along with a Django tutorial (https://djangocentral.com/building-a-blog-application-with-django/) however when I try running the code I get this message: TypeError at / expected str, bytes or os.PathLike object, not tuple my blog urls.py is from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] and my projects urls.py are: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] Does anyone know why this is happening? -
permission denied : while installing django in windows
permission denied I was trying to install Django using 'pip3 install django==2.0.2' on windows. But I am getting "permission denied " error message. But "pip3 install django==2.0.2 --user" is working, but "Django-admin" command is not being recognized. Please help me out. C:\Users\Hima>pip3 install django==2.0.2 fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\program files (x86)\python38-32\Lib\site-packages\accesstest_deleteme_fishfingers_custard_gijd2m' -
Implementing user type restrictions in my Django application
I've been going back and forward between two tutorials on creating custom user models: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html and https://wsvincent.com/django-tips-custom-user-model/ So far here is my code: Model: class CustomUser(AbstractUser): is_admin = models.BooleanField('admin status', default=False) is_areamanager = models.BooleanField('areamanager status', default=False) is_sitemanager = models.BooleanField('sitemanager status', default=False) Form: class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = CustomUser Admin: class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] admin.site.register(CustomUser, CustomUserAdmin) I have hit a bit of a wall at this point. I'm not sure what direction to go in with restricting content to users. My general idea is I want admins to access everything, area managers to have the next level of access, site manager after that, then regular users (false on all boolean checks) to have base privileges. Is this the best route to go for this kind of implementation? Where should I go from here and why? -
ManyToMany field returns None in unit test
As I'm staging my test with some models that contain a ManyToMany field, I'm checking to see if related model instances are being added to the field. However, upon accessing the ManyToMany field for each model I'm getting the following... menu.Item.None menu.Ingredient.None What is causing None to be returned and what can be done to see the related objects for each respective ManyToMany field? tests.py class TestForm(TestCase): @classmethod def setUpTestData(cls): test_chef = User.objects.create_user("test_chef") eggs = Ingredient.objects.create(name="Eggs") flour = Ingredient.objects.create(name="Flour") milk = Ingredient.objects.create(name="Milk") butter = Ingredient.objects.create(name="Butter") vanilla_extract = Ingredient.objects.create(name="Vanilla Extract") sugar = Ingredient.objects.create(name="Sugar") cls.item = Item.objects.create( name="Crepe", description="A thin pancake orginiating from France", chef=test_chef, created_date=timezone.now(), standard=True ) cls.item.ingredients.add(eggs, flour, milk, butter, vanilla_extract, sugar,) cls.menu = Menu.objects.create( season="Fall" ) cls.test_menu.items.add(cls.item) def test_form(self): print(self.menu.items) print(self.item.ingredients) models.py class Menu(models.Model): season = models.CharField( max_length=20, unique=True ) items = models.ManyToManyField('Item', related_name='items') created_date = models.DateTimeField( default=timezone.now) expiration_date = models.DateTimeField( blank=True, null=True) def __str__(self): return self.season class Item(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField() chef = models.ForeignKey('auth.User', on_delete=models.CASCADE) created_date = models.DateTimeField( default=timezone.now) standard = models.BooleanField(default=False) ingredients = models.ManyToManyField('Ingredient') def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name -
How to troubleshoot corrupted BytesIO return in django?
I've got a strange issue going on in django, and am not sure how to even start troubleshooting it. I am using xlsxwriter to generate an Excel report from some data. I then want to pass the generated file back to the user. My view code looks like: today = datetime.datetime.now() document = gen_excel(today) filename = 'export_{}.xlsx'.format(today.strftime('%Y-%m-%d')) response = HttpResponse( document.read(), content_type='application/ms-excel' ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response and the function gen_excel looks like: def gen_excel(start_date): output = io.BytesIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) create_sheets(start_date, workbook) # Creates and fills worksheets with data workbook.close() output.seek(0) return output So from gen_excel, I am returning the bytesIO stream which was filled by xlsxwriter. My issue is that (using the built-in dev server) the first time I call the view, I get a perfectly readable xlsx file. All subsequent calls, return a corrupted xlsx file, that can be sort of repaired by excel (though it kills all the formatting, etc..). If I looks the file sizes, the first output is 40655 bytes, whereas the subsequent downloads are slightly smaller at 40336 bytes. The kicker is, once I restart the server, the first output is once again perfect. So it isn't … -
django-rest-auth password change responds with ErrorDetails object
I am using django-rest-auth for authentication using APIs. I am writing tests for checking whether my application works accordingly when password1 and password2 are not same. I am recieveing an ErrorDetail object instead of string in resposnse. Response : {'new_password2': [ErrorDetail(string='The two password fields didn’t match.', code='invalid')]} Expected response : {'new_password2': 'The two password fields didn’t match.'} -
Special Char Error. python pandas and win32com
i hope you are having a good night/day. Im actually developing a module with django that extract a xlsx file with datas from my server and it worked for a few files. for the process, i request data from my server filtered by my need and put them into a pandas dataframe then i insert it in a xlsx template by using Win32com and export it on a local driver, when i tried yesterday, it worked!!!. But when i tried to do an extract from my webapp today. i had an unexpected surprise, an Exception Error: com_error at /extract/extract_files (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None) so i did research on this error and on my database to see what is the problem between the files created last day and this one. actually it seems like the new one have a LOT of text with special character, but it's not like it's a few char that causing the problem.(the data for this file his more than 8000 rows). this is how put data into my template. df2 = pd.DataFrame(dict_datas_c2) df1 = pd.DataFrame(dict_datas_c1) df3 = pd.DataFrame(dict_datas_c3) # convertion de l'objet en date df1['Task End Date'] = pd.to_datetime(df1['Task End … -
Django : Redirect after post doesn't work
After Create moneylog, I want to got back to moneybook_detail, so I made a moneylog/View.py: class moneylog_create(CreateView): form_class = forms.CreateMoneylogForm template_name = "moneylogs/create.html" def form_valid(self, form): moneylog = form.save() moneybook = moneybook_models.Moneybook.objects.get( pk=self.kwargs["pk"]) form.instance.moneybook = moneybook moneylog.save() form.save_m2m() return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk})) and this is Moneybook/urls.py app_name = "moneybooks" urlpatterns = [ path("create/", views.moneybook_create.as_view(), name="create"), path("update/<int:pk>/", views.moneybook_update.as_view(), name="update"), path("<int:pk>/", views.moneybook_detail, name="detail") ] here is my detail.html <a style="display:scroll;position:fixed;bottom:50px;right:30px;" href="{% url 'moneylogs:create' pk %}"> <div class="rounded-full h-16 w-16 flex items-center justify-center bg-red-400 text-bold font-bold text-white">+</div> </a> there is no page redirect. no move, it print just log "POST /moneylogs/create/1/ HTTP/1.1" 200 5275 How can I return to moneybook_detail after create moneylog?? why my redirect doesn't work? -
Sending messages to the other user using django_private_chat?
I had integrated the django_private_chat in my application by installing and followed every step from django private chat documentation for integrating it in my application finally I got the front end which is shown in this link but when I click the send button the message is not been sended to the user but in the documentation it is not written anything about it please help me out The link which contains code and screen shot Posting the message to the user using django_private_chat integrated in django project? -
Django: how to format time (hh:mm:ss) when display in JSON?
I save time in a models name Heures and display it using WebDataRocks library that accept JSON Doing that, data are display with this format: 08:20:34.234617 How could I display it 08:20:34? views.py def index(request): data = json.dumps(list(Heures.objects.values('heu_ide','heu_dat','heu_cod','date_id__jou_dat','heu_com','user_id__user__username')), indent=4, sort_keys=True, default=str) print(data) return render(request, 'export/index.html', {'data':data})``` **models.py** ```class Heures(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE heu_ide = models.AutoField(primary_key=True) date = models.ForeignKey(Jours, on_delete = models.CASCADE, null=True) user = models.ForeignKey(Profile, on_delete = models.CASCADE, null=True) heu_dat = models.TimeField("Heure du pointage", null=True, blank=True,auto_now_add=True) heu_cod = models.IntegerField("Code employé", null=True, blank=True) heu_com = models.CharField("Commentaires", max_length = 150, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'crf_heu' verbose_name_plural = 'Heures' ordering = ['heu_ide'] def __str__(self): return f"{self.heu_dat}"``` -
Django: Table template
I have this table in my template <tr> <th>SCHEDULE OF FEES</th> <th colspan="2">SCHEDULE OF PAYMENT</th> </tr> {% for FeesType in SchoolFeesType %} <tr> <td>{{FeesType.School_Fees_Type}}: &nbsp;&nbsp;&nbsp;&nbsp;&#8369; {{FeesType.Amount}}</td> </tr> {% endfor %} {% for Fees in scheduleofpayment %} <tr> <td >{{Fees.Remark}}</td> </tr> {% endfor %} as you can see in my code I have two loop with different models, the SCHEDULE OF FEES and SCHEDULE OF PAYMENT as you can see in the picture I just want to move the result of scheduleofpayment to SCHEDULE OF PAYMENT but I don't know how, can ypu please guys help me? -
Listing a dictionary in Python
I ran the below line of code in Python but got an error titled "TypeError: unhashable type: 'set' ". I want to turn that key to a list. How can I solve this error? dictionary = { 'a' : [[1,2,3],[4,5,6],[7,8,9]], 'b' : 2, {100} : 3 } print(dictionary['a'][1][2]) ''' -
why my django form save several image when i uploade some image?
i have a django form but when i want upload one image and save it to media_root . i see several same image in media_root , and this is so bad because my data base will be filled soon . this in my from.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('image',) and my this is my views.py: class PostCreateView(LoginRequiredMixin,TemplateView): template_name= 'send_form2pltest.html' login_url = '/login/' def get(self,request): form = PostForm() posts = Post.objects.all() return render(request, self.template_name,{'form':form}) def post(self, request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() form = PostForm() return HttpResponseRedirect('/after-send/') args = {'form':form,'messages':messages} does anyone have a solution ? -
i try store user id in django admin panel like laravel
Im a beginner in Django framework I used Laravel before and in Laravel i can store user login info or user_id with this codes: auth()->user() auth()->user()->id in Django framework is any similar code for taking user_id? i try request.user and self.request.user in my model but not work -
Django admin Add form - Limit number of displayed Model by foreign key when date is within range
Consider I have the below simple model: class Dimdate(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. date = models.DateField(db_column='date') # Field name made lowercase. This table is used by many others models (so Dimdate.id is the FK) as below: class MyModel(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. dateid = models.ForeignKey(Dimdate, models.DO_NOTHING, db_column='DateId', blank=True, null=True) # Field name made lowercase. # ... My problem is that DimDate table contains too many records. When using Django admin UI to add a new MyModel instance, the dropdown menu is showing all of my DimDate which makes it not user friendly. I did a quick google search but found nothing to restrict the number of DimDate elements retrieved and displayed in the dropdown menu (when adding a MyModel instance). Can I filter my dimdate to include only the dates from 1 month in the past to 1 month in the future? Eg: If we are the 27th of Jan 2020. Dates range is: [27/12/2019, 27/02/2020] I am currently using the admin "classic" approach of django (no custom form): @admin.register(models.MyModel) class MyModelAdmin(admin.ModelAdmin): I suspect I will need to override the MyModel form. But even by doing it. How can I … -
Unable to run django wsgi with virtual environment
I'm trying to run my django app with apache2 by using wsgi but seem to fail setting up the use of the virtual environment. To install mod_wsgi I followed Serve Python 3.7 with mod_wsgi on Ubuntu 16 as I'm using python3.7. I created a virtual environment with virtualenv -p python3.7 venv Using the virtual environment manually with python manage.py runserver works and starts the server as expected. To start it with apache2 I configured the my-app.conf with: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName example.com ServerAlias www.example.com ServerAdmin webmaster@example.com ProxyPass / http://0.0.0.0:8000/ ProxyPassReverse / http://127.0.0.1:8000/ <Directory /home/path/to/project/static> Require all granted </Directory> <Directory /home/path/to/venv/> Require all granted </Directory> <Directory /home/path/to/project/server> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess project \ python-home=/home/path/to/venv/ \ python-path=/home/path/to/project/server/ WSGIProcessGroup project WSGIScriptAlias /project /home/path/to/project/server/wsgi.py \ process-group=example.com \ application-group=%{GLOBAL} Alias /static/ /home/path/to/project/static/ ErrorLog /var/log/apache2/mysite-error.log LogLevel warn CustomLog /var/log/apache2/mysite-access.log combined SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem </VirtualHost> and the my-app-ssl.conf with: <IfModule mod_ssl.c> <VirtualHost *:80> ServerName example.com ServerAlias www.example.com Redirect permanent / https://example.com/ </VirtualHost> </IfModule> I'm ending up getting the error: ImportError: No module named 'django' which is based on the venv not set correctly. I added some code to the wsgi.py: for k in sorted(os.environ.keys()): v = os.environ[k] print ('%-30s %s' % … -
Why can't I pass the location of a static image file from my Django view to my html file using jinja templating?
I'm trying to add an image to an HTML page by passing the name of the .jpg file to an html jinja template from a view. The image is located in a static folder, and will appear as desired if the file name is coded directly, but not when I try to pass it in through Jinja. Django view code: def page(request): location = '''src="{% static 'image.jpg' %}"''' return(render(request, 'page.html', {'location':location}) Code on HTML page: {% load static %} <img {{location}} alt="image"> The image file is located in a static folder at the root of the Django project I've also tried other combinations of string to be passed in and HTML including: location = '''"{% static 'image.jpg' %}"''' <img src={{location}} alt="image"> location = "'image.jpg'" <img src= "{% static {{location}} %}" alt="image"> When I code the file name in directly as follows: <img src= "{% static "image.jpg" %}" alt="image"> the image is presented as desired. I feel like there is something I'm misunderstanding, but I'm not sure what. I couldn't find another question asking how to do this when I searched, so please forgive me if you know of an answer I didn't find! -
Django - Get Variable in Junction Table - ManyToManyField
I use Django with a MySQL database and create my models with python manage.py inspectdb...but a well known problem is to manage junction table (n-n). Django propose ManyToManyField object but i stuck specific problem... Models class A(models.Model): id_A = models.AutoField(db_column='idA', primary_key=True) to_B = models.ManyToManyField( 'B', through='A_has_B', ) class B(models.Model): id_B = models.AutoField(db_column='idB', primary_key=True) to_A = models.ManyToManyField( A, through='A_has_B', ) class A_has_B(models.Model): A_id_A = models.ForeignKey(A, models.DO_NOTHING, db_column='A_idA') B_id_B = models.ForeignKey(B, models.DO_NOTHING, db_column='B_idB') variable_i_want = models.CharField(db_column='variable_i_want', max_length=45) Example case I loop my A object model like this : for a in A.objects.all(): # Here i want to get the variable : variable_i_want variable_i_want = ????????? -
DJANGO : Can't list the content of a folder located in static directory in my django project
In my project I have a folder datasets in the static folder that content 2 others folders. I want to list the content of each of thosefolders and return it in HttpResponse. I define a utility function list_dir_content in utils/data.py where I use glob.glob() function by passing it paths of those folders but I recieve an empty result. Here are the structure of my project and files views.py, models.py You can also see the code which call the utility function list_dir_content #in views.py def server_uts_datasets(request): if request.method == 'GET': uts_datasets = Dataset.get_uts_datasets() uts_datasets_serializer = DatasetSerializer(uts_datasets, many=True) print(uts_datasets) return JsonResponse(uts_datasets_serializer.data, safe=False) #in models.py @classmethod def get_mts_datasets(cls): mts_datasets_files = data.list_dir_content(settings.DATASETS_DIR) mts_datasets = [] for mts_datasets_file in mts_datasets_files: dataset_type = 'mts' dataset_path = mts_datasets_file dataset_name = data.get_dataset_name(mts_datasets_file) dataset_nb_instances = data.get_nb_instances(mts_datasets_file) mts_dataset = Dataset(dataset_path = dataset_path, dataset_name = dataset_name, dataset_nb_instances = dataset_nb_instances, dataset_type = dataset_type) mts_datasets.append(mts_dataset) return mts_datasets #in data.py import glob import os import pandas as pd import numpy as np import matplotlib.pyplot as plt def list_dir_content(dir_path, file_extension=''): files_pattern = dir_path + '/*.' + file_extension print("files_pattern : ", files_pattern) #files_results_paths = glob.glob(files_pattern) files_results_paths = glob.glob('../tsanalysisapp/static/tsanalysisapp/datasets/uts/*.') print("files_results_paths : ", files_results_paths) return files_results_paths #in settings.py MTS_DATASETS_DIR = os.path.join(BASE_DIR, 'tsanalysisapp/static/tsanalysisapp/datasets/mts') # paths to datasets in tne … -
Is there a limitation to the naming convention base.html for Django templates?
I have encountered the TemplateDoesNotExist error when using {% extends %} in another .html file to bring in a base.html file named base-not-needed.html. What is the issue here? I remove the ending '-not-needed' from the .html file and it works. -
update_or_create - cleanest way to specify the identifier and defaults from request.data
I was wondering, what is the cleanest way to utilise the update_or_create method with request.data. I was thinking: obj, created = Object.objects.update_or_create( uuid=request.data.pop('uuid'), defaults=**request.data ) Should be sufficient? ... the request.data will always have a uuid (generated from another system). The data is in the format of the following: { "uuid": "d89b312b-c755-451f-b7d6-49d0e4a8e7e9", "firstName": "John", "lastName": "Smith", "isActive": true } -
Running python manage.py runserver gives me the following error-
while working on django framework on pycharm when I tried to run the project at localhost and run the following command in pycharm terminal: python manage.py runserver It gives me the following error and I dont know what to do: Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\aggarwal\anaconda3\Lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\aggarwal\anaconda3\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Aggarwal\Envs\test\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Aggarwal\Envs\test\lib\site-packages\django\db\models\base.py", line 121, … -
Attribute Error: 'QueryDict' object has no attribute 'iterlists'
context = { 'form': form, 'adv_form': adv_form, 'shown': shown, 'models': models_filter, 'types': types_filter, 'devices': dev_dict, 'username': request.user.username, 'request': dict(request.GET.iterlists()), 'page': page_results, 'paginator': paginator, 'page_range': page_range, 'query': query, 'status':status, 'suggestion': None, 'myartifacts': myartifacts, } I am getting that crash, once I moved my application from python 2.7 to python 3.6. ('request': dict(request.GET.iterlists())) Can anyone help me with solution? -
Redirect Django site request on multiple ports with nginx
I have a domain say 'mydjango.com' . When its called i want to handle the request on multiple ports on the same IP. 122.34.55.1:8000 , 122.34.55.1:8001, 122.34.55.1:8002 This is expected for load balancing. I am using wsgi, dgango and ngix. My nginx config file /etc/nginx/sites-available/djwsgi is - server { listen 80; listen 8001; listen 8002; listen 8003; location = /favicon.ico { access_log off; log_not_found off; } root /home/raka/djwsgi; server_name mydjango.com; location /static/ { root /home/raka/djwsgi; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/djwsgi.sock; } } But by default mydjango.com is mapped with port 80 only. Other ports are being called when i am mentioning port number like mydjango.com:8002 What i need is - when i call mydjango.com nginx should call next port every time. Like 80 then 8001 then 8002, 8003, then 80, 8001, . Please any body suggest any idea ! Thanks