Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it ok to have two or more Django forms in one HTML form?
I know it's possible to have more than one Django form in one HTML form, even formsets, and standard forms combined and it works perfectly fine. I want to know if it is a good practice and how this can impact security if it will at all? I couldn't find any information about those cases but in tutorials, I saw both (multiple Django forms in one HTML and every Django form in a separate HTML form) in some cases is necessary since the two forms can do different things like update and delete for example. In my case, all forms POST data to different models, and then all are combined in one model. Please take a look at the example (This is a simple example and not the actual code) below: <form action="" method="POST"> {% csrf_token %} {{ form.field1 }} {{ form.field2 }} {{ form.field3 }} {% for field in dates_form %} {{ field.Loading_date_from }}{{ field.Loading_time_from }}{{ field.Loading_date_to }}{{ field.Loading_time_to }} {% endfor %} {% for field in dates_form2 %} {{ field.Loading_date_from }}{{ field.Loading_time_from }}{{ field.Loading_date_to }}{{ field.Loading_time_to }} {% endfor %} {{ form.field4 }} {{ form.field5 }} <input type="submit"> </form> -
Why is it industry standard to run JS frameworks like Vue.js and React with conjuction of Node.js? [duplicate]
I have seen number of existing projects: where frontend is served from node.js server. backend server (non node.js) is providing some REST API. Clients communicate with this server the rest of the time. So nodejs is needed just for initial request. I see that frontend nodejs server does not much, but provides some static resources and js dependencies. Having frontend provided by django or even by nginx (if no server side rendering required) seems more simple. It feels like an overkill to have an extra nodejs server in your environment. We don't need to maintain extra node.js server. What am i missing here? What advantage gives this frontend node.js server? -
How do I override a template-tag for the "pinax" application in Django?
Unfortunately for me, the "pinax" application for Django does not seem to have stayed up with the times – in one specific way: the shorttimesince template-tag still refers to the tzinfo object which has been deprecated. The message is this: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'pinax.templatetags.templatetags.shorttimesince_tag': No module named 'django.utils.tzinfo' In my project, I have a overrides/pinax/templatetags directory which contains both __init__.py and shorttimesince_tag.py which contains the updated code. But it does not seem to be referenced. Whereas, the same project contains an overrides/pinax/notifications/backends/email.py which, so far as I know now, is being correctly referenced and which still appears to work. The 'TEMPLATES:DIRS' settings do now contain: os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', 'overrides/pinax'), ... which is what I assume causes the other override to be recognized. But apparently the "templatetag" override is not being seen. -
how to sand list of dict JSON response
i want to sand list of JSON is it possible to sand data like that or i should use serialize-rs dis = [{'name': 'iteam1', 'instock': 12}, {'name': 'iteam2', 'instock': 13}, ] # dis_s= serializers.serialize('json',dis) dis_d = dict(dis) diss = dict(name='iteam0', instock=100) if request.method == 'GET': print(type(dis_d), "successfully called GET") return JsonResponse(dis_d) -
Dynamically using select2 in django formset
I am able to add multiple forms successfully with formset. I am using select2 in the product name part of the form. But as I mentioned below, I manually enter the form ids. $(document).ready(function() { $('#id_store_house_id').select2(); $('#id_product_id').select2(); etc.. }); But it doesn't work because the form id changes dynamically every time I add a new form. I am bad at javascript. I have tried similar threads and solutions on stackoverflow but without success. my form and java script like this : form : <div class="row"> <div class="col-md-6 offset-md-3"> <h3 align="center">Add New Task</h3> <hr> <form id="form-container" method="POST"> {% csrf_token %} {{user_task_form | crispy }} {{ formset.management_form }} {% for form in formset %} <div class="tasksources-form"> {{form | crispy}} </div> {% endfor %} <button id="add-form" class="btn btn-success">+Add More Product</button> <br> <br> <button type="submit" class="btn btn-outline-info">Add New Task</button> </form> </div> </div> my js : <script> let tasksourcesForm = document.querySelectorAll(".tasksources-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = tasksourcesForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = tasksourcesForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } </script> Thanks for your help. I tried this : How do I use Django Dynamic … -
Problem in debugging django project using VS code
I have a problem while debugging a django project using VS code, the problem that nothing happened when I click to debug button, I can launch my script just by tapping in terminal python manage.py runserver. Here is my launch.json file, and note please that I tried a lot of examples, and still the same problem: { "version": "0.2.0", "configurations": [ { "name": "Django", "python": "C:/Users/msekmani/Desktop/dashboard_project/venv/Scripts/python.exe", "type": "python", "request": "launch", "program": "C:/Users/msekmani/Desktop/dashboard_project/IPv2/src/manage.py", "console": "internalConsole", "args": ["runserver"], "django": true, "justMyCode": true, }, ] } I am using python version 3.6 and for the OS is Windows. I hope that someone can help me, Thanks in advance :) -
Why when I try to search for a product, nothing comes up?
I've created an ecommerce website using Django, though the search results aren't coming up when I try to search for a product. For example, when I try to search for part of a product title, like throat spray, nothing comes up even though there is a throat spray in the database. I tried using the Post and Get methods though it didn't really make any difference between the two. I checked to make sure the url for the show_product page works and it does. I'm expecting search results for what I searched for. Though, the search page goes through, nothing comes up as the search results. Instead I get a /search/?searched=throat-spray My views.py: def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'product': products}) My search.html: <center> {% if searched %} <h1>Search Results for {{ searched }}</h1> <br> {% for product in products %} <a href="{% url 'epharmacyweb/show-product' product.title %}">{{ product }}</a> {% endfor %} </br> {% else %} <h1>You haven't searched anything yet...</h1> {% endif %} </center> My urls.py: path('search/', views.search, name='search'), path('search-error/', views.search_error, name='search_error'), path('show-product/', views.show_product, name='show-product'), My show_product.html: <div class="col"> <div class="card shadow-sm"> <img class="img-fluid" alt="Responsive image" src="{{ product.image.url … -
Django prevent duplication of two foreign keys in one model
I have two foreign key fields that point to the same model. I would like to prevent them from having the same value. Here is my code that does not work class Match(models.Model): team_a = models.ForeignKey(Team, related_name='team_a', on_delete=models.CASCADE) team_b = models.ForeignKey(Team, related_name='team_b', on_delete=models.CASCADE) match_date_time = models.DateTimeField(validators=[validate_matchdate]) winner = models.CharField(choices=CHOICES, max_length=50, blank=True, null=True) def clean(self): direct = Match.objects.filter(team_a = self.team_a, team_b=self.team_b) reverse = Match.objects.filter(team_a = self.team_b, team_b=self.team_a) if direct.exists() & reverse.exists(): raise ValidationError('A team cannot be against itself') -
How to save data to user models when using a resume parser in django
I am working on a website whereby users will be uploading resumes and a resume parser script will be run to get skills and save the skills to the profile of the user. I have managed to obtain the skills before saving the form but I cant save the extracted skills now. Anyone who can help with this issue will be highly appreciated. Here is my views file def homepage(request): if request.method == 'POST': # Resume.objects.all().delete() file_form = UploadResumeModelForm(request.POST, request.FILES, instance=request.user.profile) files = request.FILES.getlist('resume') resumes_data = [] if file_form.is_valid(): for file in files: try: # saving the file # resume = Profile(resume=file) resume = file_form.cleaned_data['resume'] # resume.save() # resume = profile_form.cleaned_data['resume'] # print(file.temporary_file_path()) # extracting resume entities # parser = ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) parser = ResumeParser(file.temporary_file_path()) # extracting resume entities # parser = ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) data = parser.get_extracted_data() resumes_data.append(data) resume.name = data.get('name') resume.email = data.get('email') resume.mobile_number = data.get('mobile_number') if data.get('degree') is not None: resume.education = ', '.join(data.get('degree')) else: resume.education = None resume.company_names = data.get('company_names') resume.college_name = data.get('college_name') resume.designation = data.get('designation') resume.total_experience = data.get('total_experience') if data.get('skills') is not None: resume.skills = ', '.join(data.get('skills')) else: resume.skills = None if data.get('experience') is not None: resume.experience = ', '.join(data.get('experience')) else: resume.experience = None # import … -
Problem loading large amount of geoJSON data to Leaflet map
I have geoJSON with more than 5000 objects containing various coordinates, but when they are displayed on the sitemap, the page either crashes or loads the objects for a very long time, but further interaction with the site is impossible. In index.html I have the following code: var mapOptions = { center: [14, 30], zoom: 7 } var map = new L.map('map', mapOptions); var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); map.addLayer(layer); var dataurl = '/locdata/'; fetch(dataurl) .then(function (resp) { return resp.json(); }) .then(function (data) { new L.GeoJSON(data, { onEachFeature: function (feature, layer) { layer.bindPopup(feature.properties.name); } }).addTo(map); The code for packing class objects into a JSON file contained in /locdata/ def loc_datasets(request): locations = serialize('geojson', Location.objects.all()) return HttpResponse(locations, content_type='json') The JSON looks like this: {"type": "GeometryCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"name": "00", "lon": 28.676971529668783, "lat": 60.02057178521224, "pk": "133811"}, "geometry": {"type": "Point", "coordinates": [28.676971529668783, 60.02057178521224]}}, {"type": "Feature", "properties": {"name": "41", "lon": 28.844832766965556, "lat": 60.02863347426495, "pk": "142975"}, "geometry": {"type": "Point", "coordinates": [28.844832766965556, 60.02863347426495]}}]} What is the reason that the coordinates cannot be displayed correctly on the Leaflet map on the user page? I'm working on Django, in which the data is displayed correctly in the admin panel. Thanks in … -
Using a React Template with Django (and React)
I am wondering how (or if it is even possible) to use a react template like this one: https://www.creative-tim.com/product/black-dashboard-react with an existing Django app. I have an app setup within a project like this ---project ---migrate.py ---project ---api (django app backend) ---models.py ---urls.py ---views.py ---..... ---frontend (react app) ---here Django a django app along with package.json, babel.config.json, webpack.config.js, and templates, static and src folders. I am wondering how I would integrate a template like the one linked above into this Django app. I am very new to React, I apologize if the question is explained poorly. I have tried replacing my folders and package.json files with the folders and files downloaded with the template. I couldn't get it to work properly. -
Start listening to kafka in a parallel stream when starting a django project
I want to run a file that listens to kafka in a parallel stream with a django project. My manage.py file import asyncio import os import sys import multiprocessing as mt from kafka.run_kafka import run_kafka def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'business_logic.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': kafka_process = mt.Process(target=asyncio.run(run_kafka())) django_process = mt.Process(target=main()) kafka_process.start() django_process.start() kafka_process.join() django_process.join() My run_kafka.py file uses Confluent Kafka Python import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'business_logic.settings') django.setup() import asyncio from business_logic.settings import KAFKA_CONF, TOPIC_PROD from kafka.kafka_consuners import KafkaConsumerBL async def run_kafka(): """ Запуск прослушивания Kafka на всех топиках на все ответы """ consumer = KafkaConsumerBL(KAFKA_CONF) consumer.indicate_topic([TOPIC_PROD]) await consumer.run_consumer(consumer) if __name__ == '__main__': asyncio.run(run_kafka()) I tried to solve the problem using the threading and multiprocessing libraries. After using any of the libraries, either the django project or kafka is launched. When using the multiprocessing library, one process is started, but not both manage.py ... if __name__ == '__main__': kafka_process = mt.Process(target=asyncio.run(run_kafka())) django_process = mt.Process(target=main()) kafka_process.start() django_process.start() kafka_process.join() django_process.join() … -
Django filter query using future date-time
How do I filter a query to contain only the objects that have a date-time field that holds a DateTime in the future? Here is my code that is not working: def matches(request): matches= Match.objects.all().filter(match_date_time > timezone.now() ) context = {'matches': matches} return render(request, 'bookie/matches.html', context) match_date_time is a model field in the Match model but I get an error that it's not defined. -
How can i import custom icons in leaflet Django webapp?
I am unable to import custom icons in my leaflet javascript file (Django webapp) var myicon=L.icon({ iconUrl:Url("icons/dead.svg"), iconSize:[30,40] }); I am trying this method but still unable to import..Any solution??? Please!!! -
Iterate a JSONfield corresponding to an object
The view receives an user request and then returns the corresponding object on the 'ControleProdutos' model db. views.py def relatorio_produtos(request): if request.method == 'POST': prod_json = ControleProduto.objects.get(pk = request.POST.get('periodo')) return render(request, 'selecao/historico-produtos.html', {'prod_json':prod_json}) else: return HttpResponseRedirect('/relatorios') model.py class ControleProduto(models.Model): periodo = models.DateTimeField(auto_now_add= True, verbose_name='Período') produtos = models.JSONField(verbose_name='Produtos') faturamento = models.FloatField(verbose_name='Faturamento') log_forma_pagamento = models.CharField(max_length=50, verbose_name='Forma de Pagamento') def __str__(self): return "{} {} {} {}".format(self.periodo, self.produtos, self.faturamento, self.log_forma_pagamento) def get_data(self): return{ 'periodo': self.periodo, 'produtos': self.produtos, 'faturamento': self.faturamento, 'log_forma_pagamento': self.log_forma_pagamento } class ListaProdutos(models.Model): nome_produto = models.CharField(max_length=50, verbose_name='Produto') quantidade_produto = models.IntegerField(verbose_name='Qntd.') vendido = models.IntegerField(verbose_name='Vendidos') data_adicao_prod= models.DateTimeField(auto_now_add= True ,verbose_name='Data de Adição') nota_produto = models.TextField(null=True, blank=True) custo = models.FloatField(verbose_name='Custo') tipo_produto = models.TextField(verbose_name='Tipo de Produto') def __str__(self): return "{} {} {} {} {} {} {} {}".format(self.nome_produto, self.quantidade_produto, self.vendido, self.data_adicao_prod, self.nota_produto, self.custo, self.tipo_produto) def get_data(self): return{ 'id': self.id, 'nome_produto': self.nome_produto, 'quantidade_produto': self.quantidade_produto, 'vendido': self.vendido, 'custo': self.custo, 'tipo_produto': self.tipo_produto, } Then, on the html file I'm using the for loop to iterate the JSONfield, but Django is indentifying the field as a string. html <p>{{ prod_json.periodo }}</p> <p>{{ prod_json.produtos }}</p> <p>{{ prod_json.faturamento }}</p> <p>{{ prod_json.log_forma_pagamento }}</p> <table> <thead> <tr> <th>ID</th> <th>Produto</th> <th>Quantidade Vendida</th> </tr> </thead> {% for prod in prod_json.produtos %} <tbody> <tr> <td>{{prod.pk}}</td> </tr> </tbody> {% endfor %} … -
read more button is not working on my blog post
enter image description here when i press read more to read full article ,is not opening. please am new to django where can i fixed the error i change my url as below from . import views from django.urls import path urlpatterns = [ path('', views.postlist.as_view(), name="home"), path('<slug:slug>/', views.postlist.as_view(), name="post_detail"), #path('<slug:slug>/', views.DetailView.as_view(), name="post_detail"), ] is not still working -
Docker image url validation for django
I want to get docker image URL from the user but URLs can't be acceptable with models.URLField() in django.For example, this URL: hub.something.com/nginx:1.21, got an error.How can fix it? -
Get hierarchical data
I have a db table id name parent id 1 A None 2 B 1 3 C 2 So there are many parents (parent id none) with arbitrary number of children and arbitrary depth. I want to write a django db query (recursive mysql db queries is not an option) so i can print the entire nested structure all the way to leaf element like so for a given id. What is the best way to achieve this? A --B ----C ----D --P ----Q Only solution i could think of is to query the db initially like so table.Object.filter(Q(id=id) | Q(parent_id=id)) to get the parent and its children. Iterate over children to go dfs and query db in the dfs method for nested children until it goes to the leaf element. I am trying to figure out if django has additional tools that could some how get the entire hierarchy with a few queries as possible (ideally one) -
Django static files not loading/working with no error signs
Unable to load static files, looked around the internet, but the solutions aren't working for me. Pls help. I tried moving around the static folder changing its place, tried playing around in settings.py, but nothing seems to fix it, i don't get 404 in the terminal but instead "GET / HTTP/1.1" 200 4441 All i am trying to do is change the backround color to confirm it if works body{ backround-color: blue; } like this i mean Any help would be greatly appreciated Here is my main.html where i load static: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Mutuals</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'styles/main.css' %}"> </head> Static folder location Settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] -
Cannot import django-smart-selects
I wanted to use the django smart select library to create related dropdowns. I did everything as indicated in the library documentation, but an error occurs: import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6] Even when I enter "import ..." the library itself already glows gray, as if it does not find it. This is what my INSTALLED_APPS in settings.py looks like: INSTALLED_APPS = [ 'routes_form.apps.RoutesFormConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'smart_selects', ] USE_DJANGO_JQUERY = True This is my urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('form/', include('routes_form.urls')), path('admin/', admin.site.urls), path(r'^chaining/', include('smart_selects.urls')), ] ...and my model.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey I tried to find a solution to the problem, looked for possible options. That is why I already changed from `JQUERY_URL = True` to `USE_DJANGO_JQUERY = True`. Errors (six) I did not take off. I have only this...: `import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6]` I would be incredibly grateful even for trying to help. -
HOW DO I MAKE A TEACHER VIEW ASSIGNMENTS OF STUDENTS BELONGING TO HIS/HER CLASS ONLY?
Hi Guys i need help im developing a django software whereby students submit assignments online on a school platform ,How do i make a teacher view assignments for his specific claass only Right now my software is submiting assignments , and viewing all the assignments even those of students not belonging to his/her class .So i expect the software to view only assignments of students belonging to the class of logged in teacher -
can't get the back end data when I run a react app from other device
I have a project with react on the front and django/python and postgres on the back Everything goes ok on the computer, but if I run it from another device, in the same network, the data can’t be loaded, it says axios network error I found my Ip with ipconfig, suppose it's 192.xxx.xxx.xxx, then I set in the mobile device http:// 192.xxx.xxx.xxx:3000, it runs the application but the data can't be found there, it says AxiosError: Network Error My computer recognizes the wifi network 2.4, then I connect the phone to the 2.4 network In the axios call, I set the address as: const response = await axios.get( `http://127.0.0.1:8000/api/v1/whole_menu/${restaurantId}` ); (I’m not using localhost) But I still get the network error in the phone, but in the computer, everything is ok What could it be? Thanks in advance Rafael -
ensure_csrf_cookie method decorator not setting CSRF token in browser cookies tab
I'm working on a project using Django as API backend (hosted on localhost:8000) and React (hosted on localhost:3000) as frontend. My plan is to host them on different servers in production as well. I'm currently trying to set the CSRF token in the browser cookies tab using the "ensure_csrf_cookie" method decorator. While the javascript API call seems to work and returns the response, no cookie is set in my cookie tab (tested in different browsers). However, the weird thing is that when I type in the CSRF token URL directly in the browser, the cookie is set. This leads me to believe it's not working due to some cross-origin issues. So I've tried many different settings in my settings.py file without success. Django View: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response ({ "success": "CSRF cookie set"}) React: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } async function … -
DRF tries to create User object when used in nested serializer
DRF docs says that "By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be save."<< In general this is true except for one case. When User class is a nested object in serializer. Use case is to add existing user to newly created organization. Consider my simple example where I noticed that issue: views.py class UserOrganizationViewSet(viewsets.ModelViewSet): # authentication_classes = (JwtAuthentication, SessionAuthentication) # permission_classes = (permissions.JWT_RESTRICTED_APPLICATION_OR_USER_ACCESS,) serializer_class = UserOrganizationSerializer queryset = UserOrganization.objects.all() models.py: class UserOrganization(models.Model): name = models.CharField(max_length=256) users = models.ManyToManyField(User, blank=True, related_name="user_organizations", through='OrganizationMember') def __str__(self): return self.name class OrganizationMember(models.Model): organization = models.ForeignKey(UserOrganization, on_delete=CASCADE) user = models.ForeignKey(User, on_delete=CASCADE) joined = AutoCreatedField(_('joined')) serializers.py: First version - User class has its own simple serializer and it is used as nested serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ['username'] class UserOrganizationSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, required=False) class Meta: model = UserOrganization fields = ['id', 'name', 'users'] read_only_fields = ['id'] Is this case I am able to fetch data via GET method (Organization created through admin panel): But when I am trying to create organization I am … -
i can't add domain name to server
i create Django one click drophlet on Digitalocean. i configure my website and i want add domain name. i configure my nginx and i add to server domain name . i also add nameservers on my domain registrant and configure domain name on digitalocean but still didn't work. here is my configuration. upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name recourse.ge www.recourse.ge; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0;} } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } I add nameservers to my domain registrant. i add also A record to my digitalocean domain name. i configure nginx and add my domain name to nginx configuration and i add in settings.py Allowed host my domain name.