Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bug that requires a lot of "Djongo migrate"
I'm using djongo. I don't know what the cause is, but a message asking me to run python manage migrate appears from time to time. Does anyone know the cause? please. requirement.txt django==4.1.13 django-cors-headers django-mongoengine pytz beautifulsoup4 lxml requests selenium djongo==1.3.6 mongoengine==0.27.0 graphene-django graphene_mongo pymongo==3.12.3 pytesseract pyftpdlib openai==0.28 Nothing in particular was done. -
Stop isort reordering specific imports
When I run isort on this init.py file it reorders the imports alphabetically, moving instruments into the correct alphabetical position. from .administration_model import Administration # noqa from .administration_model import AdministrationSummary, administration_data # noqa from .instrument_model import Instrument # noqa from .benchmark import Benchmark # noqa from .demographic import Demographic # noqa from .instrument_family import InstrumentFamily # noqa from .instrument_score import InstrumentScore # noqa from .ip_address import ip_address # noqa from .measure import Measure # noqa from .payment_code import PaymentCode # noqa from .researcher_model import Researcher # noqa from .study_model import Study # noqa from .summary_data import SummaryData # noqa But Benchmark.py is dependent upon it and needs importing first. How do I prevent the reordering in this file only? -
Data Is not being sent to the django endpoint
I am trying to send data to my django endpoint. Which will then be used to compare against the entries made in the database. The data is not being sent to the endpoint, therefore I am getting a Invalid request error on my browser console when calling the api/login endpoint.Here is my frontend code import React, { useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import '../css/login.css'; import axios from 'axios'; function Login() { const [formData, setFormData] = useState({ username: '', password: '' }); const navigate = useNavigate(); const handleChange = (e) => { const { name, value } = e.target; setFormData(prevState => ({ ...prevState, [name]: value })); }; const handleSubmit = async (event) => { event.preventDefault(); try { const response = await axios.post('http://127.0.0.1:8000/api/login/', formData); if (response.data.message) { switch (response.data.role) { case 'Business Development Partner': navigate('/bdpdashboard'); break; case 'Recruiter': navigate('/employeedashboard'); break; case 'Manager': navigate('/managerdashboard'); break; case 'Business Development Partner Manager': navigate('/bdpmdashboard'); break; case 'Account Manager': navigate('/amanagerdashboard'); break; default: console.error('Invalid role:', response.data.role); } } else { console.error('Login failed:', response.data.error); } } catch (error) { console.error('Login failed:', error); } }; return ( <div className="login-container"> <h2>Login</h2> <form onSubmit={handleSubmit}> <div className="input-group"> <label htmlFor="username">Username</label> <input type="text" id="username" name="username" value={formData.username} onChange={handleChange} required /> … -
Model.objects.get not returning anything
So I am trying to retrieve data from the database so that I can compare those values with the values entered by the user and show then the appropriate page I have made sure that the database table linked to the view has data. Here is the view @csrf_exempt def verify_login(request): if request.method == 'POST': data = request.POST user = data.get('username') # Retrieve stored login details stored_login = LoginDetails.objects.get(username__iexact=user) print(stored_login.username) if stored_login: # Compare the passwords directly if data.get('password') == stored_login.password: # Authentication successful user_role = stored_login.user_data.role if stored_login.user_data and stored_login.user_data.role else None print(user_role) return JsonResponse({'message': 'Login successful', 'role': user_role}) else: # Password does not match return JsonResponse({'error': 'Invalid password'}, status=401) else: # Username not found return JsonResponse({'error': 'Invalid username'}, status=401) return JsonResponse({'error': 'Invalid request method'}, status=405) And printing the stored_login print None on the python terminal running the django server. I get the following error on the console <h1>DoesNotExist at /api/login/</h1> <pre class="exception_value">LoginDetails matching query does not exist.</pre> To check whether the data exists in the LoginDetails model, I ran the following commands python3 manage.py shell from backend_app.models import LoginDetails LoginDetails.objects.all() I get the following output <QuerySet [<LoginDetails: qwerty>]> I am also posting the frontend page which gets the … -
how to load image from user side
I am working on real estate website. so, user can upload their property. i can upload from admin side. But when user try to upload it is not working. below is my code. My settings.py: import os MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My urls.py: from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My models.py: media = models.ImageField(upload_to='images') my rent.html: <a href=""><img class="img-fluid" src="{{i.image.url}}" alt=""></a> -
Seeking Recommendations for Email and WhatsApp Integration in Django Project
I'm currently developing a Django-based project with a couple of key features focused on user engagement and reminders. Here's an overview: Email Confirmation & Reminder System: Upon completion of specific surveys by users, the system should automatically send confirmation emails. It should also be capable of scheduling and sending reminder emails to users on predetermined dates. The expected volume of emails is around 50,000 per month. WhatsApp Messaging Integration: Similar to the email system, I aim to implement automated WhatsApp messages that will be sent to users who interact with our platform in a specific manner. Given the outlined requirements, I have a few questions: For Email Automation: Are there any free services available that can handle the email volume mentioned above? If free options are limited or unavailable, could you suggest any cost-effective, reliable API providers for this purpose? For WhatsApp Integration: What are the typical costs associated with integrating WhatsApp messaging in such a manner? Are there any free or low-cost services available for automating WhatsApp messages? I'm looking for recommendations on tools or services that integrate well with Django and can efficiently manage the described functionality. Cost-effectiveness and reliability are my primary considerations. Thank you in advance … -
how to sort django query result on a string field including software version x.y.z
I am write a web site using Django framework. I have a model that stores software and its version number in the format "x.y.z" (or "x", "x.y"), where x, y, and z are integer numbers. How can I sort the query results by the version number in ascending order? The default sorting behavior is based on string alphabet order, but not what I want. Thank you! -
Websocket jwt authentification keeps handshaking and disconnecting
I have this custom jwt auth-middleware in django: class JWTAuthMiddleware: def __init__(self, inner): self.inner = inner async def __call__(self, scope, receive, send): print(": Middleware called") headers = dict(scope['headers']) if b'authorization' in headers: print(": Authorization header found") try: token_name, token_key = headers[b'authorization'].split() if token_name == b'Bearer': print(": Bearer token found") user = await self.authenticate(token_key.decode()) if user is not None: print(": User authenticated") scope['user'] = user except InvalidTokenError: print(": Invalid token") await self.inner(dict(scope, user=None), receive, send) return except KeyError: print(": Invalid token format") await self.send_error(send, "Invalid token format") return else: print(": No authorization header found") await self.inner(dict(scope, user=None), receive, send) async def authenticate(self, token_key): print(": Authenticating user") try: secret_key = settings.SECRET_KEY decoded_token = decode(token_key, secret_key, algorithms=['HS256']) user_id = decoded_token['user_id'] user = await self.get_user(user_id) if user is not None and user.is_authenticated: print(": User authenticated successfully") return user except (InvalidTokenError, KeyError): print(": Authentication failed") pass return None @database_sync_to_async def get_user(self, user_id): print(": Retrieving user from database") try: return User.objects.get(user_id=user_id) except User.DoesNotExist: print(": User not found") return None When i make a request through postman or flutter,after a user logs in and selects a group to access its chat_screen : void _initializeWebSocket() async { print("_initializeWebSocket called"); SharedPreferences prefs = await SharedPreferences.getInstance(); String? accessToken = prefs.getString('accessToken'); … -
Model Form Data is not Visible When i try to update the model in django
so this is the view : def update_ticket(response,ticket_title): ticket = get_object_or_404(TicketsModel, title=ticket_title) ticket_form = AddTicketsForm(response.POST or None,instance=ticket,assigned_by=response.user) if 'return' in response.POST: return redirect('home', type_user=response.session.get('type_user')) if ticket_form.is_valid(): ticket.ticket_creation_date = datetime.now() ticket_form.save() return redirect('home', type_user=response.session.get('type_user')) return render(response, "template/testapp/update_ticket.html", {'ticket_title': ticket.title, 'ticket_form': ticket_form}) the problem is , when i render the form , i dont see the data inside of the inputs , but if i delete the 'response.POST' in the AddTicketsForm() , i can see the data but i cant update nothing here is the html content <h2>Update Ticket</h2> <form action="{% url 'update_ticket' ticket_title=ticket_title %}" method="post"> {% csrf_token %} {{ ticket_form.as_p }} <button type="submit" name="save" id="regDirect" >Save</button> <button type="submit" name="return">Return</button> <form/> -
Can't get id_token with Auth0 backend
I'm currently implementing the Auth0 OAuth2 backend in python-social-auth and social-app-django. At the start of the social-core pipeline, after I log into Auth0, I get an error during Auth0OAuth2.get_user_details() at jwt.decode(): DecodeError at /complete/auth0/: Invalid token type. Token must be a <class 'bytes'>. I've pasted that code below: def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get("id_token") jwks = self.get_json(self.api_path(".well-known/jwks.json")) issuer = self.api_path() audience = self.setting("KEY") # CLIENT_ID ... signature_error = None for key in keys: try: payload = jwt.decode( id_token, key.key, algorithms=["RS256"], audience=audience, issuer=issuer, ) I assume the error is because response.get("id_token") is always None; the response argument only has keys for access_token, expires_at, and token_type. I must be missing something in my setup, but there's no documentation for the Auth0 backend in python-social-auth, so I'm not sure what could be wrong. I have the following environment vars set: SOCIAL_AUTH_AUTH0_KEY SOCIAL_AUTH_AUTH0_SECRET SOCIAL_AUTH_AUTH0_DOMAIN My Auth0 app is a Regular Web App on a developer account, and changing the app's grant types and authentication method hasn't fixed the error. -
How to create Gravis visualization in webpages using Django?
I want to display an interactive network graph on my webpage (similar to the ones shown here), and I am using Networkx, Gravis, and Django. The image does not show up, and neither does it thow any errors. I would like suggestions or corrections to my code (given below) so that I can get the thing working... Suggestions for using alternative packages are also welcome, as long as the packages are easy to work with from within a Django project/app. My end goal is to make the nodes in the interactive plot clickable, so that I can get the names of the nodes the user clicks...but I guess that comes later. First I need to get the basic network graph to at least show up on the webpage. Here are my codes: views.py from django.shortcuts import render import pandas as pd import networkx as nx import gravis as gv from django.http import HttpResponse def merge(list1, list2): merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))] return merged_list def plot_netx_gravis(topic_string,request): nx_csv=pd.read_csv('NetworkXNodes/'+topic_string+'_NetworkX_Edgelist.csv', index_col=None) connection_tuples=merge(nx_csv['Child'].to_list(),nx_csv['Parent'].to_list()) G1=nx.DiGraph() G1.add_edges_from(connection_tuples) image=gv.d3(G1) template = 'topics4node_2.html' return render(request, template, {'image':image.to_html()}) topics4node_2.html {% extends 'base.html'%} {% block title %}Gravis Graph{% endblock %} {% load crispy_forms_tags %} {% block content … -
database and django merging problem data is not showing in my html pages
i made database and insert data through pop sql and now i want to display inserted data in my html in django project what steps should i follow???..and the data is not shown in the html pages after doing so many things in setting i changes the database name but it is not working. i write py manage.py migrate but the data in my database is not showing -
matplotlib savefig() in django works in local server but not in docker
So when I try to savefig it works on django running on localserver but does not work on docker. Below is the example code for save fig df_2["vendor"].value_counts().plot(kind="barh") plt.title("Custom HTML Tags by Vendor") path = folder + "/" + timestamp_o + f"vendors for custom html temp.png" plt.savefig(path) img_sheet.insert_image("E" + str(cell_number), path) plt.savefig(path, bbox_inches="tight") Below are the images- in local server in docker -
Unable to do migrations in django
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency userauths.0001_initial on database 'default'. 1)I have tried commenting "django.contrib.admin", and path("admin/", admin.site.urls), 2)I have tried python manage.py migrate userauths zero and then deleting all migration file except init file then python manage.py makemigrations userauths then after that i used python manage.py migrate still facing the same issue -
Python Django ModelViewSet implementation with SAML ACS
In the current system with the legacy IAM, we have implemented a class inherited from ModelViewSet with login and logout functions. In the legacy IAM, it is not compulsory to obtain name_id and session_index to logout. Therefore, we can bypass acs (a.k.a. assertion_consumer_service) to obtain these information and go straight to the logout. Now, a new IAM system is deployed and we need to extend the current implementation to support both login and logout (along with acs). name_id and session_index shall be provided in LogoutRequest. Given we have different set of URLs for login/logout: https://example.com/saml2/account/[login|logout] acs: https://example.com/saml2/sso/acs How can we update the following code to support the callback from acs so that we can save the name_id and session_index? urls.py router = DefaultRouter() router.register("saml2/account", Saml2AccountView, basename="account") urlpatterns = [ url("", include(router.urls)), ] views.py class Saml2AccountView(viewsets.ModelViewSet): @action(detail=False, methods=['get']) def login(self, request, *args, **kwargs): # implement the login function @action(detail=False, methods=['get']) def logout(self, request, *args, **kwargs): # implement the logout function -
error in the application's ajax request in an azure app
I have an app in python-django and on localhost everything works normally. I make ajax requests to Python correctly, however it doesn't work in the Azure application, follow the example code of how I make a request: $.ajax({ url: '/PlanEx/DCC/GerarTabelaAnova', data: formData, type: 'POST', Furthermore, my gateway app constantly times out -
Django: first data record not being saved when field = zero
I am new to Django and I am currently struggling to find out the reason the first data record from a formset is not saved (included) into database when the numeric field poQtyof the ProductOrder model is equal to zero. QueryDict seems to be okay with 4 records in this example, but the first record is not included in the database when productorder_set-0-poQty is zero: <QueryDict: {'csrfmiddlewaretoken': ['6b85qEA4LMz7f3lcUvlpAi74BATLiouApAE1AKLMQhz0I7Gohvmw8jhAHnMf82LT'], 'orderOpen': ['on'], 'orderTable': ['02'], 'menuQuery': ['1'], 'productorder_set-TOTAL_FORMS': ['4'], 'productorder_set-INITIAL_FORMS': ['0'], 'productorder_set-MIN_NUM_FORMS': ['0'], 'productorder_set-MAX_NUM_FORMS': ['1000'], 'productorder_set-0-prodQuery': ['1'], 'productorder_set-0-poQty': ['0'], 'productorder_set-0-poOrder': [''], 'productorder_set-0-id': [''], 'productorder_set-1-prodQuery': ['2'], 'productorder_set-1-poQty': ['0'], 'productorder_set-1-poOrder': [''], 'productorder_set-1-id': [''], 'productorder_set-2-prodQuery': ['4'], 'productorder_set-2-poQty': ['0'], 'productorder_set-2-poOrder': [''], 'productorder_set-2-id': [''], 'productorder_set-3-prodQuery': ['3'], 'productorder_set-3-poQty': ['0'], 'productorder_set-3-poOrder': [''], 'productorder_set-3-id': ['']}> I would appreciate some help on that... thanks! Here are further details: models.py class ProductClass(models.Model): classDescription = models.CharField(max_length=255, verbose_name='Type', unique=True, null=True) classPrint = models.BooleanField(default=True, verbose_name='Print?') class Meta: verbose_name_plural = 'Product Classes' def __str__(self): return self.classDescription class Product(models.Model): prodclassQuery = models.ForeignKey(ProductClass, on_delete=models.PROTECT, verbose_name='Product Class', default=1) prodDescription = models.CharField(max_length=255, verbose_name='Product') prodPrice = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='Price') class Meta: ordering = ['prodclassQuery', 'prodDescription'] def __str__(self): return self.prodDescription class Menu(models.Model): menuActive = models.BooleanField(verbose_name='Active?', default=False) menuDescription = models.CharField(max_length=255, verbose_name='Menu') prodQuery = models.ManyToManyField(Product, verbose_name='Product') class Meta: ordering = ['menuDescription', ] def __str__(self): return … -
Use Multiple analyzer in elastic search.(Autocomplete and phonetic)
The analysis algorithm is performing well on autocomplete with fuzzy matching but the fuzzy matching is not soo good so i wanted to add phonetic analyzer to same firstname index. i ran through many documentation and didnot find good one on how to use 2 analyzer. "settings": { "analysis": { "analyzer": { "autocomplete_analyzer": { "type": "custom", "tokenizer": "autocomplete_tokenizer", "filter": [ "lowercase" ] }, "phonetic_analyzer": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "phonetic" ] } }, "tokenizer": { "autocomplete_tokenizer": { "type": "edge_ngram", "min_gram": 2, "max_gram": 10, "token_chars": ["letter", "digit"] } } } }, "mappings": { "properties": { "full_name": { "type": "text", "analyzer": "autocomplete_analyzer" }, "relation_name": { "type": "text", }, "address": { "type": "text" } } } } -
How does Django Implicitly Set Data Types for CharField or Any Other?
from django.db import models class Post(models.Model): title = models.CharField(max_length=100, null=True) When I define a field named title = models.CharField(max_length=100, null=True) in a Django model, how does Django implicitly set the data type for this field? Django automatically recognised title as CharField[str | None]. If i set null = False then type become CharField[str]. I want to know how can i implement this in my class. Thank You! Python version: 3.11.6 Using Pylance -
How to change the default directories of your project
So, i'm developing this app in python and when i try to show some html in the browser i get this error: TemplateDoesNotExist at /xPharma/hello/ hello.html Request Method: GET Request URL: http://127.0.0.1:8000/xPharma/hello/ Django Version: 4.2.11 Exception Type: TemplateDoesNotExist Exception Value: hello.html Exception Location: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: xPharma.views.say_hello Python Executable: C: \Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\Marco\\Desktop\\Desktop\\progetto X pharme\\XpharmBackend', 'C:\\Python39\\python39.zip', 'C:\\Python39\\DLLs', 'C:\\Python39\\lib', 'C:\\Python39', 'C:\\Users\\Marco\\.virtualenvs\\XpharmBackend-9gJJ8jLG', 'C:\\Users\\Marco\\.virtualenvs\\XpharmBackend-9gJJ8jLG\\lib\\site-packages'] Server time: Mon, 01 Apr 2024 15:44:22 +0000 but i find out that i get this error because python is searching for a file in the wrong directory... Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\contrib\admin\templates\hello.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\contrib\auth\templates\hello.html (Source does not exist) Is there a way to change this directories and redirect python to where i saved my file? -
IntegrityError: insert or update on table
I am currently working on a web application that uses Django as a backend, Django Rest Framework as an API, React as a frontend, and PostgreSQL as a database. For user authentication, I utilized SimpleJWT. However, I encountered an issue where I am able to create a user account through the frontend, but I cannot log in with the newly created account. There's an error message appearing in the console, the user information is present in the database. However, I can still log in with a couple of accounts that were created a while ago(all accounts from the same database table), both through the front end and Django Rest Framework. I keep getting this error on Django: the parenthesis for (user_id) can be different every time in the error IntegrityError at /api/token/ insert or update on table "token_blacklist_outstandingtoken" violates foreign key constraint "token_blacklist_outs_user_id_83bc629a_fk_auth_user" DETAIL: Key (user_id)=(4) is not present in table "auth_user". Here's my database table, this first 3 accounts I can successfully log in through frontend and Rest framework settings.py (only the simpleJWT part): SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=90), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": True, # FOR SECURITY REASON (ABOVE) "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": … -
Django + React Session Based Auth 'AnonymousUser' object has no attribute '_meta'
I am learning Django & React. I created a little session-based auth app that worked fine for an attempt and then I broke it by pressiong 'logout'. Now it is impossible to log in. It always return the following error: AttributeError: 'AnonymousUser' object has no attribute '_meta'. "POST /api/login/ HTTP/1.1" 500 75814 Here is my api/views.py code: from django.shortcuts import render # Create your views here. import json from django.contrib.auth import authenticate, login, logout from django.http import JsonResponse from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_POST @require_POST def login_view(request): data = json.loads(request.body) username = data.get("username") password = data.get("password") if username is None or password is None: return JsonResponse({"details": "Please provide both username and password"}) user = authenticate(request, username=username, password=password) if user is not None: return JsonResponse({"details": "invalid username and password"}, status=400) login(request, user) return JsonResponse({"details": "login successful"}) def logout_view(request): if not request.user.is_authenticated: return JsonResponse({"details": "you are not logged in"}, status=400) logout(request) request = JsonResponse({"details": "logout successful"}) @ensure_csrf_cookie def session_view(request): if not request.user.is_authenticated: return JsonResponse({"isauthenticated": False}) return JsonResponse({"isauthenticated": True}) def whoami_view(request): if not request.user.is_authenticated: return JsonResponse({"isauthenticated": False}) return JsonResponse({"username": request.user.username}) Thanks a lot for your help ! I tryed to: create another user on the admin pannel. restart server edit views.py … -
Cannot use Model in deployment, despite being created
I have a Django app with several apps within. I have App_A with the settings.py and then App_B where I have created the following models: from django.db import models from decimal import Decimal import re class Webshop(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) compare_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) webshop = models.ForeignKey(Webshop, on_delete=models.CASCADE, related_name='products') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name @staticmethod def parse_price(price_str): # Remove currency and convert to a format suitable for Decimal price_str = re.sub(r'[^\d,]', '', price_str).replace(',', '.') return Decimal(price_str) if price_str else None Locally, I am able to get all the products, but once I deploy the app, I cannot get any items. I use the following view to show the products, and locally this is fine, but deployed, it gives me an error, see below. from django.shortcuts import render from .models import Webshop, Product def webshop_dashboard_view(request): # get all products products = Product.objects.all() print(products) return render(request, 'webshop_dashboard.html') And the error I get is: Exception Type: ProgrammingError at /webshop-dashboard/webshop_dashboard/ Exception Value: relation "WebshopDashboard_product" does not exist LINE 1: ...id", "WebshopDashboard_product"."date_added" FROM "WebshopDa. I have tried to re-create the database and migrations, but I cannot seem … -
drf_yasg openapi swagger keeps on showing Django Login link
settings.py INSTALLED_APPS = [ .. 'drf_yasg', .. ] views.py class myapi(APIView): permission_classes = (permissions.AllowAny,) authentication_classes = () @swagger_auto_schema(operation_description="A custom description", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'token': openapi.Schema(type=openapi.TYPE_STRING, description='token'), }, required=['token'], )) urls.py from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="MY API", default_version='v1', ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('user_api.urls')), re_path(r'^apidoc/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] https://gist.github.com/axilaris/2e15f9c0cc8aff2727c39917123d25f4 nginx configuration server { listen 80; server_name 182.20.4.110 mydomain.io; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproj_app/static/; } location / { alias /home/ubuntu/myproj_app/frontend/build/; } location /apidoc { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } sudo tail -f /var/log/nginx/error.log 2024/04/01 12:37:01 [error] 3618#3618: *128 open() "/home/ubuntu/myproj_app/static/static/drf-yasg/insQ.min.js" failed (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET /static/drf-yasg/insQ.min.js HTTP/1.1", host: "mydomain.io", referrer: "https://mydomain.io/apidoc/" 2024/04/01 12:37:01 [error] 3618#3618: *129 open() "/home/ubuntu/myproj_app/static/static/drf-yasg/immutable.min.js" failed (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET /static/drf-yasg/immutable.min.js HTTP/1.1", host: "mydomain.io", referrer: "https://mydomain.io/apidoc/" 2024/04/01 12:37:01 [error] 3618#3618: *128 open() "/home/ubuntu/myproj_app/static/static/drf-yasg/swagger-ui-dist/favicon-32x32.png" failed (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET /static/drf-yasg/swagger-ui-dist/favicon-32x32.png HTTP/1.1", host: "mydomain.io", referrer: "https://mydomain.io/apidoc/" However, I keep getting this is I go into https://mydomain.io/apidoc/. It should the swagger api page. I got it working on my … -
nginx cannot serve React due to permission denied. www-data cant access frontend/build/
I'm trying to configure nginx so that it can serve both React and Django. Here is my configuration: server { listen 80; server_name 182.20.4.110 mydomain.io; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproj_app/static/; } location / { alias /home/ubuntu/myproj_app/frontend/build/; } location /apidoc { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } https://gist.github.com/axilaris/2329d3ff73034b51483366772c7cef9c However, I keep getting 403 Forbidden And based on the nginx error logs, it keeps getting permission denied in the React build directory sudo tail -f /var/log/nginx/error.log 2024/04/01 12:23:57 [error] 3616#3616: *68 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.4.193, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:23:58 [error] 3616#3616: *69 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:24:21 [error] 3616#3616: *67 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "mydomain.io" 2024/04/01 12:24:27 [error] 3616#3616: *70 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.4.193, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:24:28 [error] 3616#3616: *71 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:24:30 [error] 3616#3616: *67 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: …