Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Debug django apps using vim + vimspector
I'am trying run debugging of django, but breakpoints doesn't working. For Example: I created configuration for vimspector enter image description here Add new def() to manage.py enter image description here Run the command: python manage.py runserver Start debugging from vimspector. It attached was successfully, but when I reload web-page it's give to me error "This site can't be reached". I matched it's for piece of code "debugpy.wait_for_client" and trying comment this. In this case web-page reload without error, but breakpoints doesn't work. Ex. information: After running server and debug I see two processes, may be debugpy want attach to process run sever. enter image description here -
Using few specific fields from another
So I was trying to use this fields on my Insuree model which originally came from Policy model policy_category = models.ForeignKey('Policy', on_delete=models.CASCADE, blank=True,null=True,default="Life") policy_length = models.ForeignKey('Policy', on_delete=models.CASCADE, blank=True, null=True, default="") coverage_amount = models.ForeignKey('Policy', on_delete=models.CASCADE) However, I was encountering these errors: Now, I'm not sure if its possible the thing I was trying to do. Any possible approach? -
Django For Beginers - Joinpath error when running manage.py runserver
I am learning Djnago and I am facing an issue I have looked around but can't maange to solve it. So basically on page 45 of Django For Beginners the author says : " Next we need to update config/settings.py to tell Django the location of our new templates directory. This is a one-line change to the setting 'DIRS' under TEMPLATES." Code config/settings.py TEMPLATES = [ { ... 'DIRS': [str (BASE_DIR. joinpath('templates '))], # new ... }, ] So in my settings.py file I have this : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [str(BASE_DIR.joinpath('templates'))], # new 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Unfortunatelly, when I run the manage.py runserver I then get this message : File "C:\Users\User\Desktop\pages\manage.py", line 22, in <module> main() File "C:\Users\User\Desktop\pages\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\user\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in … -
how to get only the 'title' attribute value from following data in django
This is the views.py I want to get 'title' attribute from the serialize data views.py class CalculatView(views.APIView): query = CartProduct.objects.latest('id') serializer = CartProductSerializer(query) choose_product = serializer.data.get('product') [sell_id] = choose_product querye = Product.objects.filter(id = sell_id) serializere = ProductSerializers(querye, many=True) choosee = serializere.data print(choosee) output : [OrderedDict([('id', 2), ('title', 'Frock'), ('date', '2021-04-22'), ('image', '/media/products/kids2.jpg'), ('marcket_price', 1.2), ('selling_price', 1.2), ('description', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), ('category', OrderedDict([('id', 2), ('title', 'Fashion'), ('date', '2021-04-22')])), ('seller', OrderedDict([('id', 2), ('seller_name', 'CIB - Piliyandala'), ('lat', 6.8018), ('lng', 79.9227), ('date', '2021-04-22')]))])] -
how to set timezone for strawberry on django
I am using django==3.1.7 with strawberry-graphql==0.57.2 create GraphQL APIs. I want the datetime fields that is rendered to the output get affected by django TIME_ZONE, But when I change time zone in settings.py it has no effect. I am thinking of overriding process_result of GraphQLView and check for every field type that is datetime and add time zone to it, but I feel that it's wrong. -
How to increase request timeout error for larger requests in ngnix
I have trained the machine for a few specific tasks. Deploy it into Django with Nginx and Gunicorn on AWS EC2. Whenever I generate a request based on a small input, it works fine. In the case of large input, it takes so much time. I needed that time. Eventually, the "502 Bad Gateway" error message appears. How I can prevent this error. I thought it was nginx request timeout error. So I increased using http{ ... proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; ... } So, is there a solution? I'm new to StackOverflow, so please bear with me. -
I am not getting the data I want when I call the post request, the response is empty
def spotify_callback(request, format = None): code = request.GET.get('code') error = request.GET.get('error') response = post('http://accounts.spotify.com/api/token', data = { 'grant-type' :'authorization_code', 'code' : code, 'redirect_uri': REDIRECT_URI , 'client_id' : CLIENT_ID, 'client_secret': CLIENT_SECRET }).json() access_token = response.get('access_token') token_type = response.get('token_type') refresh_token = response.get('refresh_token') expires_in = response.get('expires_in') error = response.get('error') if not request.session.exists(request.session.session_key): request.session.create() update_create_tokens( request.session.session_key, access_token, token_type, expires_in, refresh_token) return redirect('frontend:') I am trying to work with Spotify's API but when I sent a request for post with the data shown below it's saying 405: method not allowed -
Is there another issue that can cause css files not been found on django project?
I am sorry to ask very repeated question. However, I have tried my best for many days yet cannot figure it out. Could anyone guide me what I have done wrong? I tried to create a library program by django. This is my files' directory: prophado_lib |_prophado_lib |_ __pycache__ |_ __init__.py |_ settings.py |_ urls.py |_ wsgi.py |_book_management |_ __pycache__ |_ migrations |_ static |_ css |_ style.css |_ Templates |_ index.html |_ __init__.py |_ admin.py |_ apps.py |_ models.py |_ tests.py |_ views.py |_dbsqlite3 |_manage.py Then my code in each file are as follows: index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> <h1>{{var1}}</h1> Welcome to Propado School Library! settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' urls.py from django.conf.urls import url from django.contrib import admin from book_management import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^my_index/', views.index), ] urlpatterns += staticfiles_urlpatterns() fyi, I have already tried other ways with STATIC_ROOT and python manage.py collectstatic , even though I have known that it's for when I would like to make it in to production. -
Django multithreading to run render() as well as store data in a file
I am currently working on a Django application which searches for input words in a database and returns 'True' if words are found. I would like to store the undetected words in a file with the help of a function call during the time 'render()' is called to return the status of input words. How is it possible through multi-threading? Below I have shown my function names: I am currently working on a Django application which searches for input words in a database and returns 'True' if words are found. I would like to store the undetected words in a file with the help of a function call during the time 'render()' is called to return the status of input words. How is it possible through multi-threading? Below I have shown my function names: def store_undetected(): # function to store undetected words return 0 def sentence(request): # function to analyse words from input return render(....) Within 'sentence(request)', I would like to use one thread to call store_undetected() and the other to return render(). -
Reverse for 'password_reset_complete' not found
I am Using PasswordResetView for reset password, but when I Enter new Password and submit the button. Django redirect to this ulrs.py from django.urls import path from Authentication import views from django.contrib.auth import views as auth_view from .forms import * app_name = 'Authentication' urlpatterns = [ path('', views.loginpage, name='loginpage'), path('login', views.handlelogin, name='login'), path('logout', views.handlelogout, name='logout'), path('password_reset', views.password_reset, name='password_reset'), path('password_reset/done/', auth_view.PasswordResetDoneView.as_view(template_name='Authentication_template/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(template_name='Authentication_template/password_reset.html', form_class=SetPasswordForm), name='password_reset_confirm'), path('password_reset_complete/', auth_view.PasswordResetCompleteView.as_view( template_name='Authentication_template/password_reset_complete.html'), name='password_reset_complete') ] here I use custom view for sending email to user. -
KeyError Django rest framework
I am receiving KeyError from the application. I have field patientName in my model, however, the problem raised was patientName. Can anyone please help with this, has been struggling with this for few days. i am not very sure if i make any misstake here. I wanted to use filter here, to receive only the patientNmae, patienNRIC, and patientAddress, however, it fails. view.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import PatientDetail from .serializer import PatientSerializer import sqlite3 # Create your views here. @api_view(['Get', 'POST']) # @csrf_exempt def patient_list(request): if request.method == 'GET': data = request.data patientname = data['patientName'] # patientnric = data['patientNRIC'] patientdetails = PatientDetail.objects.filter(patientName = patientname ) # patientdetails = PatientDetail.objects.all() # serialization serializer = PatientSerializer(patientdetails, many=True) # return Json return Response(serializer.data) elif request.method == 'POST': #data = JSONParser().parse(request) serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['Get', 'PUT','DELETE']) @csrf_exempt def patient_detail(request,patientNRIC): try: patientdetails = PatientDetail.objects.get(patientNRIC = patientNRIC) except PatientDetail.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": # serialization, getting one data only serializer = PatientSerializer(patientdetails) # return Json return JsonResponse(serializer.data) elif request.method == "PUT": … -
list of download file without models in django
Can we create a list of download file by specifying to folder path and their is no model related to filefield to handle uploaded pdf file. Saving the uploaded file to specific folder using filehandling method. -
Handle AJAX POST request to render a template in django
I have a problem when making a site with django, I hope you guys can give me a help. After using an AJAX POST, I will get that data to a function in view.py and do my stuff. It works nice, but when I need to render a template with data of my stuff, the browser does not direct me to that template. Can anyone tell me what should I do to handle the AJAX POST request. Thanks a lot and have a nice day. view.py: def get_id_from_ajax(request): print(request) if request.method == 'POST' and request.is_ajax(): print(type(request.POST)) QueryID = request.POST['key'] print('data recieved: '+ QueryID) if type(int(QueryID)) == int: Query_user = allusers.objects.get(id = QueryID) Query_username = Query_user.username Query_teamID = Query_user.teamid Query_rank = Query_user.rank Query_status = Query_user.is_deleted #return HttpResponseRedirect(json.dumps({'username': Query_username})) #return edit_user(request) #return JsonResponse(json.dumps({'username': Query_username}), safe=False) return render(request, 'edit_user.html',{"username": Query_username, "teamid": Query_teamID, "rank": Query_rank, "status": Query_status}) #return redirect('edit_user.html') return render(request, 'edit_user.html') ajax post: btn[i].addEventListener('click', function(e){ var testID = this.id; var getID = testID.match(/\d/g); getID = getID.join(""); console.log(getID); e.preventDefault(); $.post('/testdb/get_id_from_ajax', { key: getID, csrfmiddlewaretoken: csrftoken }); I just need to render a new template with data I got in my view.py. Thank you guys for any help. -
How to authenticate using external endpoint in django
I’m building a webapp with drf which does the authentication by calling an external api. Token received from front end is sent as request parameter. Response contains the Token status (Expired or Active). My app doesn’t have a user model. So all the views should be displayed based on the status of the external api call. To accomplish this, i have added a middleware. If the token status is expired i need to respond with 401 unauthorized json response. I found out drf has HttpResponseForbidden but it returns 403 and http response. which exception or response can i use here? Is it possible to do this in drf authentication classes instead of using middleware? or is there any other way to do this? Below is my middleware code : from rest_framework.exceptions import AuthenticationFailed from django.http import HttpResponseForbidden class AuthMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: # Post call to external api # if Token valid, do nothing # else return Invalid token with 401 code return HttpResponseForbidden("Invalid Token") # currently returns 403 code except Exception as e: print(e) response = self.get_response(request) return response -
how to add a file and integer value to a File field and Integer field respectively
I'm currently trying to make a form that adds the value to the "SampleField" model that I created but it seems to not go through. I made a form that should allow the user to put any integer value and a file it should add to the model. Can anyone point me to the right direction on what to do? Any help is appreciated. Here is my forms.py class SampleForm(forms.ModelForm): timefile = forms.FileField(widget=forms.FileInput) sample_fre = forms.IntegerField(widget=forms.NumberInput) class Meta: model = SampleField fields = ('timefile',) Model.py class SampleField(models.Model): timefile = models.FileField(upload_to="media/") sampling_frequency = models.IntegerField(default=0, null=False) views.py def sample(request): if request.method == 'POST': form = SampleForm(request.POST, request.FILES) if form.is_valid(): file_uploaded = form.save(commit=False) file_uploaded.SampleField += form.sample_fre form.save() return redirect("<h1>Data saved Successfully<h1>") elif request.method == 'GET': form = SampleForm() return render (request, 'visual/value.html', {'form' : form}) -
Best way to use ProxyPass to replace certain pages of static site
I have a legacy static site that I host on apache. Over time I have needed to add dynamic features to that site so I installed Django and configured it via WSGIDaemonProcess but my understanding was that it would need to be in a subfolder (ie. /django-stuff/*). But now there are some legacy pages (ie. /legacy-important-page.html) that were in the root folder that I would like to replace with a dynamic route. I know that I can use ProxyPass to reroute a single url (ie. ProxyPass "/legacy-important-page.html" "https://www.example.com/django-stuff/legacy-important-page") or use a redirect. But is there a way to have Apache configured to check if a static file exists, otherwise use a dynamic route? Or another way to accomplish what I'm looking for? If there is another web server that accomplishes it I would be open to that as well. -
How to set StaticLiveServerTestCase to work with websockets
I am currently creating a test using behave and StaticLiveServerTestCase to spin up a runserver, and for some reason I can't connect to my websocket url I am not sure if channels are supported in StaticLiveServerTestCase and if there is a manual way to do this. This is my current codebase: import os import django from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.shortcuts import resolve_url from django.test.runner import DiscoverRunner os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings_test" django.setup() def before_all(context): context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() context.test = StaticLiveServerTestCase context.test.setUpClass() context.base_url = context.test.live_server_url def after_all(context): context.test.tearDownClass() del context.test context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() -
How to create a table from json data?
I have a json format data and I want to create a table from that. I can take values and display them correctly. But when I create a table it is not working as what I want. My data returns as rows but I want to every array should be column. It is my table: And this is like what I want: Here are my codes: views.py def test_fin(request): data_test = json.loads(json_bss_test) test_data = [] test_1 = data_test['Assets'] test_2 = data_test['Unnamed: 1'] test_3 = data_test['Unnamed: 2'] test_4 = data_test['Unnamed: 3'] test_5 = data_test['Unnamed: 4'] test_6 = data_test['Unnamed: 5'] test_data.append(test_1) test_data.append(test_2) test_data.append(test_3) test_data.append(test_4) test_data.append(test_5) test_data.append(test_6) table_headers = [] column_1_bss_header = data_bss_header["Unnamed: 1"] column_2_bss_header = data_bss_header["Unnamed: 2"] column_3_bss_header = data_bss_header["Unnamed: 3"] column_4_bss_header = data_bss_header["Unnamed: 4"] column_5_bss_header = data_bss_header["Unnamed: 5"] for i in range(0, 1): table_headers = [column_1_bss_header, column_2_bss_header, column_3_bss_header, column_4_bss_header, column_5_bss_header] context = { 'test_data': test_data, 'table_headers': table_headers, } return render(request, 'fin_test.html', context) fin_test.html <table id="basic-datatables" class="display table table-bordered"> <thead style="background-color: #d9f6ef"> <th>in Millions USD</th> {% for data in table_headers %} {% for x,y in data.items %} <th>{{ y }}</th> {% endfor %} {% endfor %} </thead> <tbody> {% for data in test_data %} <tr> {% for k,v in data.items %} <td>{{ … -
django raw sql in optimization?
I think my code is not very pythonnic ,How to optimize? code lamp_keys=["ids"] if len(lamp_keys) == 1: rsql = f""" SELECT * from brelation where source_key = '{lamp_keys[0]}' and target_concept='aaa' """ else: rsql = f""" SELECT * from brelation where source_key in {tuple(lamp_keys)} and target_concept='aa' """ robjs = RelationModel.objects.raw(rsql) if lame_keys length is 1,if use in must be error,for example: SELECT * from `brelation` WHERE source_key in ('xx',) and target_concept='aa' -
Why some data are missing in postgres database while working with django?
In views.py of django_project I've defined the following, def register(request): uname = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] user = User.objects.create_user(username=uname, first_name=fname, last_name=lname, email=email, password=pass1) user.save() And the template goes as, <form method="POST"> <div> <input type="text" name="username" id="username" required=""/> </div> <div> <input type="text" name="fname" id="fname" required=""/> </div> <div> <input type="text" name="lname" id="lname" required=""/> </div> <div> <input type="text" name="email" id="email" required=""/> </div> <div> <input type="password" name="pass1" id="password" required=""/> </div> <div> <input type="submit" formaction="register" value="Register" /> <a href="/login/">Back to Login Page</a> </div> </form> This only saves username, password and first_name in the database, the rest (last_name,email) are ignored. How to store all the data in the postgres database. -
How to call function in another python project from django views?
I have a python project which will open connection, and will update database forever until connection is closed (will run in infinite loop as long as connection is alive). Now this has to be initialized from django views once the user lets say clicks start in the UI. It works perfect if I just import those functions in the views. But the problem is if django is stopped it destroys all the objects as well meaning it stops background database update work as well. How make the background work independent of django but the initialization should happen from UI ? Flow is like this : Start the Django Server Ask User to Initiate by clicking start button Call the function which will run forever to update database (independent of django server) Even django is closed background update should happen Help me to solve the above problem. Thanks -
django.template.library.InvalidTemplateLibrary: Invalid template library specified in Django3.2
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django.contrib.admin.templatetags.admin_static': cannot import name 'RemovedInDjango30Warning' from 'django.utils.deprecation' (C:\Users\Gokul\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\deprecation.py) I'm getting this error, after i update django to 3.2! Any possible solutions would be helpful. Thanks in advance! -
Django related model not updating on form submission
How do I update a non existing related object through Django model forms ? I have two objects: Participant and Emergency. Emergency is a child of participant like if run the query: participant = ParticipantInfo.objects.get(pk = prk) I can access emergency = participant.emergency. I cannot update emergency with data from a form using a POST request. Can anyone help me please. Thanks Here's my models.py for clarity. models.py class EmergencyInfo(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=50) email = models.EmailField(max_length=100, blank=True, verbose_name="Emergency Contact Email") relationship = models.CharField(max_length=100) class ParticipantInfo(models.Model): first_name = models.CharField(max_length=100) middle_initial = models.CharField(max_length=1, blank=True) emergency = models.ForeignKey(EmergencyInfo, on_delete = models.CASCADE, editable= False, null=True, blank=True) views.py def update_participant(request, pk): # this function comes after update_specific if request.method == "GET": forms = get_participant_form_data(pk) context = {'forms': forms, 'pk': pk} return render(request, 'core/participantinfo_update_form.html', context) if request.method == "POST": return update_specific_form(request, pk) def update_specific_form(request, pk): participant = ParticipantInfo.objects.get(pk = pk) # if the object didn't exist create it like normal if participant.emergency is None: emergencyform =EmergencyForm(request.POST) if (emergencyform.is_valid): emergencyform.save() messages.success(request, 'saved') return redirect(request.path_info) # if the object exists, update it if participant.emergency is not None: emergencyform = EmergencyForm(request.POST, instance = participant.emergency) if (emergencyform.is_valid): emergencyform.save() messages.success(request, 'saved') return redirect(request.path_info) -
Why "pipenv install requests" command on windows powershell is showing error?
I have already installed python's latest version and pipenv on Windows Powershell. When I try to install requests it is showing this error: FileNotFoundError: [WinError 2] The system cannot find the file specified ValueError: Not a valid python path: 'C:/ProgramData/Anaconda3/python.exe' Full error code: Traceback (most recent call last): File "C:\Python39\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 618, in parse_executable result_version = get_python_version(path) File "C:\Python39\Lib\site-packages\pipenv\vendor\pythonfinder\utils.py", line 105, in get_python_version c = subprocess.Popen(version_cmd, **subprocess_kwargs) File "c:\python39\lib\subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "c:\python39\lib\subprocess.py", line 1420, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python39\Scripts\pipenv.exe\__main__.py", line 7, in <module> File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 829, in __call__ return self.main(*args, **kwargs) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 782, in main rv = self.invoke(ctx) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 610, in invoke return callback(*args, **kwargs) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\decorators.py", line 73, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 610, in invoke return … -
Nginx Bad Request (400) only with domain name not with IP (gunicorn and django)
I know many others have asked the same question, but I haven't found any answers that are relevant or work for me. If you do know of a duplication, feel free to direct me to it.. I'm getting lost in the maze of nginx threads! I am new to this and used the following tutorials to set up my django site with gunicorn and nginx: https://vahiwe.medium.com/deploy-django-and-flask-applications-in-the-cloud-using-nginx-gunicorn-and-systemd-centos-7-4b6aef3a8578 https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 My website works if I access it via the IP address but I get a Bad Request error when I try by the domain name. In nginx.conf my server block looks like: server { listen 80; server_name 123.456.78.910 mywebsite.com www.mywebsite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/userf/website; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/var/www/userf/website/website.sock; } } My gunicorn.service file is: [Unit] Description=gunicorn daemon After=network.target [Service] User=ssej91D Group=nginx WorkingDirectory=/var/www/ssej91D/pwebsite ExecStart=/var/www/userf/website/env/bin/gunicorn --workers 3 --error-logfile - --bind unix:/var/www/userf/website/website.sock website.wsgi:application EnvironmentFile=/var/www/userf/website/.env [Install] WantedBy=multi-user.target And my ALLOWED_HOSTS in django's settings.py: ALLOWED_HOSTS = ["mywebsite.com", "www.mywebsite.com", "123.456.78.910"] I have not added any SSL related settings to the Django settings file yet. To test the domain name, I've tried making a test index.html …