Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom user admin not reflected in admin site
I am new to django and going through legacy django project where Custom user admin is configured with following: app1/admin.py from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): """Define admin model for custom User model with no email field.""" fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email', 'first_name', 'last_name', 'phone_number', 'type_of_user', 'timezone', 'deleted', 'is_supervisor', 'supervisor', 'role')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined', 'created_date')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username', 'password1', 'password2'), }), ) list_display = ('username', 'first_name', 'last_name', 'is_staff') search_fields = ('username', 'first_name', 'last_name') ordering = ('username',) Also in app1.models.py, where CustomUser is further inherit from AbstractBaseUser. class User(CustomUser): first_name = models.CharField(max_length=1024, db_index=True) last_name = models.CharField(max_length=1024, db_index=True) phone_number = models.CharField(max_length=1024, blank=True, null=True) is_supervisor = models.BooleanField(default=False, db_index=True) license = models.CharField(max_length=1024, blank=True, null=True) type_of_user = models.IntegerField(choices=TYPE_OF_USER, default=1, db_index=True) created_date = models.DateTimeField(default=timezone.now) timezone = TimeZoneField(choices=[(tz, tz) for tz in pytz.all_timezones]) deleted = models.BooleanField(default=False, db_index=True) load_id = models.CharField(max_length=1024, null=True, blank=True) approval_status = models.IntegerField(choices=APPROVAL_STATUS, null=True, blank=True) supervisor = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) last_alert_sent_on = models.DateTimeField(null=True, blank=True, db_index=True) role = models.ForeignKey("common.Role", on_delete=models.SET_NULL, null=True, blank=True) In settings.py: AUTH_USER_MODEL = 'app1.User' There's no admin.py in main_app folder. The problem here is that the User model … -
How can I re-filter queryset without N+1 problems in Django?
I have simple N+1 problem with queryset in Django. Simple views.py code example of the problem what I'm having. a_queryset = AA.objects.filter(user=request.user).all() # some codes in here with a_queryset . . . b_queryset = a_queryset.filter(id__in=[3,4,5]) # re-filtered # some codes in here with b_queryset . . . c_queryset = a_queryset.get(id=10) # re-filtered # some codes in here with c_queryset . . . I have N+1 problem which is three SELECT queries and I already know these codes cause it. It would be very nice to call queryset at once, but I can't because there're some tasks in the middle. What should I do? -
i am facing the issue when submiting the form of second section , the returns back to the first section insted of updating the content of curent page
User this is my script for the single page with side bar in which 4 four buttonsrespectivey for page 1 page 2 page 3 page 4, these four pages are in a single template and containing the relevant content , page is containg two form, the first form showing the drop down of the loc_ids as i selects the value from the drop down and submits the form it should update the current page content as the second form from the views file rendering the same template which containing the four pages , as the view sending the value to the template, on the front as page loading completes it showing me the first page which welcome page , instead of this how can i remain on the current page(specific section of the template), this is due to as the view rendering the template and on submiting the previus form it rediret to the second form's view which is rendering the template and when loading it show the template from the start . on tis page i have a multiple forms , here i have also same forms but rendering from diffrent views. <script> window.addEventListener('load', function() { var urlPath = … -
How to add Django admin panel widgets to custom templates?
how to you use admin panel widgets on custom templates ?? like edit, add and view -
Django is mixing 2 different translation entries and creates a fuzzy entry in the PO file
I see this in the django.po file after executing python manage.py makemessages command: #: .\homepage\models.py:40 #, fuzzy #| msgid "The logo of the site as appears on the top of each page." msgid "The logo of the brand as appears on the homepage." msgstr "لوگوی سایت که بالای هر صفحه نمایش داده میشود." The problem: #| msgid "The logo of the site as appears on the top of each page." belongs to line 20 (not 40) of models.py of core app (not homepage). There's no other entry for line 20 of models.py of the core app in the file. msgid "The logo of the brand as appears on the homepage." belongs to line 40 of models.py of homepage app. Ironically, the translated text appears for the first message (which is commented out) not the second. I have no idea why this is happening and how to fix it. This is Django v5.0.3 on Windows. -
most of time flask rest api request is aborted when authentication is failed onyl sometime it raise unauthorised error
I have a Flask REST API through which I make requests with a large XML payload. In the code, I have set it up so that when authentication fails, it should raise an 'unauthorized' error. While testing the API using Postman, I've noticed that sometimes the error is raised, but most of the time, the request is aborted whenever an authentication error occurs. Additionally, when I use the Python requests library for testing this API, I encounter a 'chunked encoding' error when the request is aborted. Could you please advise me on how to solve this problem? Also, could you explain why the request is aborted sometimes and not others? I want the API to return an 'unauthorized' error when incorrect credentials are provided, rather than aborting the request, as it currently does inconsistently. Sometimes it works as intended, but other times it simply aborts the request without providing the appropriate error response. How can I ensure that the API consistently returns an 'unauthorized' error when unauthorized access is detected? -
Want to retrieve the id of the latest object created in a model
So I am creating a login page. I am trying to register a user and then login. In the registration of my user, the user is prompted to fill in details in a form, and then the next step is to create username and passoword. So the problem I am facing is that the personal information entered is a different model, and I want to retrieve the id of the latest object created so that I can link them with the username and password. Here is my code for it Models.py class UserData(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) fullName = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) aadhaarNumber = models.CharField(max_length=12, blank=True, null=True) dateOfBirth = models.DateField(null=True, blank=True) maritalStatus = models.CharField(max_length=20, blank=True, null=True) emergencyContact = models.CharField(max_length=255, blank=True, null=True) address = models.TextField(blank=True, null=True) phoneNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) emailID = models.EmailField(validators=[EmailValidator()], blank=True, null=True) emergencyContactNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) jobTitle = models.CharField(max_length=100, blank=True, null=True) departmentName = models.CharField(max_length=100, blank=True, null=True) joiningDate = models.DateField(blank=True, null=True) employmentType = models.CharField(max_length=100, blank=True, null=True) prevCompany = models.CharField(max_length=255, blank=True, null=True) prevDesignation = models.CharField(max_length=100, blank=True, null=True) relevantSkills = … -
Asynchronous scraper + Django
I'm trying to create an application that displays information to the user from an asynchronous scraper. The scraper must work independently and continuously. The user, when visiting the desired page of the site, must automatically subscribe to the flow of an independently working scraper. For example: the scraper works using while True. It collects, processes and sends processed data. The user has visited the site and should be able to see the data that the scraper gave during its last iteration. When the scraper again collected, processed and returned the data, the user’s data should be automatically updated, and so on in a circle. Unfortunately, I can’t show you the project code due to confidentiality. Next I will describe the methods that I found and tried to apply. All of them are somehow related to Django Channels and multiprocesses and threads. Which of these methods is the most correct and how to connect your scraper correctly? Maybe I missed some other method, I don't know. Multiprocessing, Pipe. It was suggested to create a separate script process (in my case, an asynchronous scraper) and use Pipe to pass this data to another script (in my case, Django View). Websockets. Create an … -
Extract data from DB or populate it with fixtures before running tests
My pytest runs do not extract the db in the real database which I believe is normal as test DB is initially empty. Part of my code requires that I fetch the id of a page in an existing model. def result_page_get_id_from_slug(slug): print(ContentPage.objects.values().last()) obj = ContentPage.objects.get(slug=slug) return obj.id There's no way I can do this in tests sice test db is empty. So I keep gettign the following error: home.models.ContentPage.DoesNotExist: ContentPage matching query does not exist. When I try to print all objects during testing I get None meaning that ContentPage model is empty during test run. print(ContentPage.objects.values().last()) How can I populate it please. Thanks -
Django is not raising validationerror
class confirm_password_form(forms.Form): password = forms.CharField(label="Password",widget = forms.PasswordInput,required=True) confirm_password = forms.CharField(label="Confirm_Password",widget = forms.PasswordInput,required=True) def clean(self): print("this is clean") cleaned_data = super().clean() password = self.cleaned_data["password"] confirm_password = self.cleaned_data["confirm_password"] print("in clean password ",password) print("in clean confirm_password",confirm_password) if password!=confirm_password: print("this is not equal condition") raise forms.ValidationError("both password should be match") "In above code django is not raising the validationerror. It is printing 'this is not equal condition' but it is not raising error. I have tried available solutions. -
Django HttpStreamingResponse Not Streaming
I have a very interesting issue with the Django HttpStreamingResponse. Our server calls OpenAI Text Completion API in streaming mode, upon receiving the chunks from OpenAI, we incrementally parse the chunks and stream complete JSON objects back to our clients. Below are some code snippets: views.py class StreamViewSet(ModelViewSet): ... def stream(self, request): ... json_stream = agent.get_json_objects() return StreamingHttpResponse(json_stream, content_type="application/json") agents.py def stream(self): yield from self.json_agent.get_json_stream() json_agent.py def get_data_stream(self): # This calls OpenAI text completion API with stream=True stream_response = self.get_text_completion(user_preference, stream=True) # Create an incremental json parser json_stream_parser = JsonStreamParser() for chunk in stream_response: if chunk.choices and chunk.choices[0].delta.content is not None: json_stream_parser.feed(chunk.choices[0].delta.content) yield from json_stream_parser.parse() json_parser.py class JsonStreamParser: """A simple JSON stream parser that can parse a stream of JSON objects. Note it only works for an array of JSON objects, which means the input must contain a valid JSON array, at any point of the stream, that starts with '[' and ends with ']'. It will parse the JSON objects in the array and ignores anything outside of the array. """ def __init__(self): self.buffer = "" self.index = 0 self.open_braces = 0 self.start_index = -1 self.array_started = False def feed(self, data): self.buffer += data def parse(self): parsed = [] … -
Custom Django admin login with django allauth package
I want a functionalities where when user login to admin page, either using username and password, or using google sso (using allauth package). they still need to go for a certain check. Now I have this views where i state my checks: views.py def custom_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): user = form.get_user() # Check if the user belongs to a specific group print(user) check_in_wd = check_user_in_wd(user) if (user.groups.exists() or user.is_staff) and check_in_wd: login(request, user) return redirect('/admin/') # Redirect to admin dashboard after successful login else: messages.error(request, 'You are not authorized to access the admin page.') else: messages.error(request, 'Invalid username or password') else: form = AuthenticationForm() return render(request, 'admin/login.html', {'form': form}) urls.py urlpatterns = [ path('grappelli/', include('grappelli.urls')), # grappelli URLS path('admin/login/', custom_login, name='custom_login'), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] login.html - just for extra refs <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>App</title> </head> <body> {% extends "admin/login.html" %} {% load static %} {% load i18n %} {% block content %} <div id="content-main"> <form id="login-form" method="post" action="{% url 'admin:login' %}" novalidate> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <label for="id_username">{{ _('Username') }}:</label> {{ form.username }} </div> <div class="form-row"> <label for="id_password">{{ _('Password') }}:</label> {{ form.password }} … -
Django queryset filter data by timestamp range at last one hour
I am trying to filter data from the Django queryset where the timestamp range has to be exactly last seven days at the last one hour. For example, I want to filter out data from today (March 31st, 2024) until March 24th, 2024 but only within the last hour (10:00 - 11:00 a.m.). What I have done so far, yet still no further improvements: qs = SuccessRateTodayData.objects.select_related('region')\ .order_by('-timestamp', 'region__region_name')\ .filter(Q(timestamp__range=(start, end))) I have tried using raw query in PostgreSQL. It's something like this: SELECT regionname, round(avg(completed)::numeric, 2) avg_completed, round(avg(failed)::numeric, 2) avg_failed FROM ( SELECT timestamp2, regionname, completed, failed, num_read, numofdata FROM "SuccessRateTodayData" WHERE timestamp2 > current_date - interval '7 days' AND (timestamp2::time BETWEEN '10:00:00' AND '11:00:00') ORDER BY regionname, timestamp2 ) t GROUP BY regionname Expected Result: Any help would be appreciated. Thank you. -
How to fix the issue with some post functions not working during autopagination?
I need help solving a problem with automatic pagination. When automatic pagination occurs from the home_list.html template to the home.html template, all functions of the template stop working, even though the template itself is paginated correctly. The functionality stops working after pagination, namely: "edit" and "delete" the published post, "Add comment", "Edit comment", "Save edited comment", "Delete comment". In the home.html template, these functions work in the {% for post in post_lists %} loop, but after automatic pagination from the home_list.html template in the {% for post in posts %} loop, these functions do not work. How can I fix this? home.html <div id="post_contenter"> {% for post in post_lists %} <div class="post_content" id="post_content"> <!-- Add identifier post_content --> <div class="post_header"> <div class="post_user_avatar"> {% if post.author.avatar %} <img style="width:50px; height: 50px;" src="{{ post.author.avatar.url }}" class="user-picture-small"> {% else %} <img style="width:50px; height: 50px;" src="{% static 'twippie/img/avatar.png' %}" class="card_user_picture_small"> {% endif %} </div> <div class="post_user_info"> <div class="post_user_fullname"><a href="{% url 'user:profile_username' post.author.username %}" class="post_user_fullname_style">{{ post.author.first_name }} {{ post.author.last_name }}</a></div> <div class="post_user_username"><a href="{{ user_profile.username }}" class="post_user_nickname_style">@{{ post.author }}</a> {% if post.author.verification %} <span class="verified_user_small"></span> {% endif %} </div> <div class="post_user_date"><a href="{{ post.get_absolute_url }}" class="post_user_date_style">{{ post.time_create }} {{ post.time_create|naturaltime }}</a></div> </div> </div> <div class="post_user_more"> <div class="dropdown … -
Django Admin Panel and Sub URLs Returning 404 Error on Deployment
have recently deployed my Django project to a server, and while the index URL (mannyebi.com) loads correctly along with static files, accessing sub URLs such as mannyebi.com/blogs or even the admin panel (mannyebi.com/admin) results in a 404 error. Locally, the project runs smoothly, indicating the issue may stem from the deployment configuration. I've ensured that all necessary URL patterns are defined in the urls.py files and that Django's admin app is properly installed and configured. However, despite these measures, I'm still encountering difficulties accessing sub URLs beyond the homepage. Is there a specific configuration step or server setting that I might be overlooking to resolve this 404 error and enable access to sub URLs on my deployment? Any insights or troubleshooting suggestions would be greatly appreciated. I deployed my Django project to a server. Upon navigating to sub URLs such as mannyebi.com/blogs or mannyebi.com/admin, I encountered a 404 error. I verified that all necessary URL patterns were defined in urls.py and that Django's admin app was properly configured. I expected these URLs to load correctly, similar to how they did on my local development environment. However, despite these efforts, the 404 errors persisted. I'm seeking guidance on resolving this issue … -
How to return HTTP Get request response from models class in Django project
I am trying to Get a response from the OpenAi assistants API using a Django project. I implement a model class inside models.py as such: from django.db import models from typing_extensions import override from openai import AssistantEventHandler from django.http import HttpResponse # Create your models here. class Eventhandler(models.Model,AssistantEventHandler): class meta: managed = False @override def on_text_created(self, text) -> None: print(f"\nassistant > ", end="", flush=True) @override def on_text_delta(self, delta, snapshot): print(delta.value, end="", flush=True) def on_tool_call_created(self, tool_call): print(f"\nassistant > {tool_call.type}\n", flush=True) def on_tool_call_delta(self, delta, snapshot): if delta.type == 'code_interpreter': if delta.code_interpreter.input: print(delta.code_interpreter.input, end="", flush=True) if delta.code_interpreter.outputs: print(f"\n\noutput >", flush=True) for output in delta.code_interpreter.outputs: if output.type == "logs": print(f"\n{output.logs}", flush=True) Now, what is important is that the Eventhandler class sends the response back to the client! I am a getting an exception of type: ValueError: The view theassistantcallerapp.views.callerview didn't return an HttpResponse object. It returned None instead. Now, callerview is the view inside views.py. It maps to the URL that will start the GET request to the OpenAi Assistants API. This implementation I am using is for streaming responses. Now, here is the view insides views.py and NOTICE HOW THE EVENTHANDLER CLASS IS USED #inside views.py # this is callerview(request, paramm): thread = … -
Issue with Quantity Increment in Django E-commerce Cart
Description: I'm encountering an unexpected behavior in my Django e-commerce website where the quantity of items in the cart increments at an exponential rate instead of a linear one. Here's a breakdown of the problem and the relevant code snippets: Problem Description: When adding an item to the cart, the quantity appears to double with each click of the "add" button. For instance, if I add an item once, it shows a quantity of 3 instead of 1. Then, upon adding it again, the quantity jumps to 6 instead of 2, and so forth. Similarly, when decreasing the quantity using the "remove" button, it doesn't decrement linearly but exhibits similar exponential behavior. Code Snippets: cart.html: This snippet shows the HTML code responsible for displaying the quantity and buttons to add or remove items from the cart. <div class="li-cartstyle cartbodyinformation-quantity"> <p class="quantity-input">{{ item.quantity }}</p> <div class="cartquantity-buttons"> <i data-product={{ item.product.id }} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i> <i data-product={{ item.product.id }} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i> </div> cart.js: This JavaScript code handles the interactions with the cart, such as adding or removing items. // var user = '{{request.user}}' var updateBtns = document.getElementsByClassName('update-cart') var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser'; for(var i=0; i … -
Can't install Pipenv on Windows
i'm building the backend of an app in python and i wanted to use Django, the problem is, i installed pipenv with pip3 the first time and it run smoothly, now if i try to install with pip only it tells me: Requirement already satisfied: pipenv in c:\users\marco\appdata\roaming\python\python39\site-packages (2023.12.1) Requirement already satisfied: virtualenv>=20.24.2 in c:\python39\lib\site-packages (from pipenv) (20.25.1) Requirement already satisfied: certifi in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (2024.2.2) Requirement already satisfied: setuptools>=67 in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (69.2.0) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (4.2.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.8) Requirement already satisfied: filelock<4,>=3.12.2 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.3) WARNING: You are using pip version 21.2.3; however, version 24.0 is available. You should consider upgrading via the 'C:\Python39\python.exe -m pip install --upgrade pip' command. but if i try to run pipenv --version powershell tells me: pipenv : Termine 'pipenv' non riconosciuto come nome di cmdlet, funzione, programma eseguibile o file script. Controllare l'ortografia del nome o verificare che il percorso sia incluso e corretto, quindi riprovare. In riga:1 car:1 + pipenv + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException (wich by the way is the "not recognized as the name of … -
use dict from python in django html template and also in js
I am having a dict statistics in my view.py and give it as param in my context to my index.html. There I want to use it in my html like {{ statistics.key1 }}. But I also want to use it in js. When using json.dumps like this in my view.py: "statistics": json.dumps(statistics, cls=DjangoJSONEncoder), I can use it like this in my js: var statistics = JSON.parse('{{ statistics | escapejs }}'); But then I can't use it as a dict anymore in my html. Makes sense, as it is now a JSON-String. But when I just pass it like a dict, I can use it in my html. but var statistics = '{{ statistics | escapejs }}' gives me a JSON with single quotes so I can't just parse it. How can I do both? Still use the dict as normal in my HTML and also parse it to use it in js? -
'pyodbc.Cursor' object has no attribute 'callproc', mssql with django
I cannot execute a procedure stored on mssql server from django. Here is the configuration for the db DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'OPTION':{ 'driver': 'ODBC Driver 17 for SQL Server', 'trusted_connection': 'yes' } } } In my view: def test(request): if request.method == "POST": with connection.cursor() as cursor: P1 = request.data["p1"] P2 = request.data["p2"] try: cursor.callproc('[dbo].[SP_TEXT]',[P1,P2]) if cursor.return_value == 1: result_set = cursor.fetchall() print(result_set) finally: cursor.close() return Response({"msg":"post"}) else: return Response({"msg": "get"}) I use sql server standard 2022 Need help please -
Django Bootstrapv5 carousel multiple item problem
I want my carousel items to contain a maximum of 5 card tags. However, when I add more cards and it exceeds five, it doesn't create another carousel item, but simply overflows into the same carousel. How i can fix this problem. This is my code: <div class="carousel-box"> <div id="carousel-1" class="carousel slide" data-bs-interval="false" data-bs-wrap="false"> <div class="carousel-inner"> {% for knowledge in knowledges %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <div class="row"> {% for photo in photo01s %} {% if photo.category01 == knowledge %} <div class="card" style="background-image: url('{{ photo.image01.url }}');"></div> {% endif %} {% endfor %} </div> </div> {% endfor %} </div> </div> I have written it like this, but it's not effective. <div class="carousel-box"> <div id="carouselExample" class="carousel slide" data-bs-interval="false" data-bs-wrap="false"> <div class="carousel-inner"> {% for knowledge in knowledges %} {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <div class="row"> {% with photo_count=0 %} {% for photo in photo01s %} {% if photo.category01 == knowledge %} {% if photo_count < 5 %} <div class="card" style="background-image: url('{{ photo.image01.url }}');"> </div> {% endif %} {% increment photo_count %} {% endif %} {% endfor %} {% endwith %} </div> </div> {% endfor %} </div> </div> -
Django socketio process
I'm dealing with a little problem that I need to solve. I have an application in Django and I need a websocket, but I don't like Django channels, so I created a socket server in Flask and I'm trying to connect Django to it, by creating middleware that when called starts a process that sends messages through the process what it has in the queue But either the shared variable doesn't work or the process itself doesn't work properly. Please if you have any advice or solution write also how to terminate the process with socket when django terminates This is my code: socket.py --- import socketio import json from project.settings import SOCKET_CONFIG, MANAGER from multiprocessing import Process sio = socketio.Client() class Socket: queue = MANAGER.list() def __init__(self, get_response): self.get_response = get_response thread = Process(target=Socket.process_loop, args=()) thread.start() def __call__(self, request): return self.get_response(request) @staticmethod def process_loop(): sio.connect('http://{}:{}'.format(SOCKET_CONFIG["host"],SOCKET_CONFIG["port"])) while True: try: import time time.sleep(1) data = Socket.queue.pop(0) sio.emit('message', data) except BaseException as e: print(e) settings.py --- import os, subprocess from multiprocessing import Process, Manager MANAGER = Manager() SOCKET_CONFIG={ "host":"localhost", "port":8001 } ... -
Unable to get Docker with React and Django to work in Ubuntu - forbidden access
I am trying to get my React and Django project that is using docker-compose to work on AWS Ubuntu. It works on my mac. However, I cant get it working on my IP. I have allowed port 80 inbound traffic. Here are the docker-compose up logs https://gist.github.com/axilaris/5844a146a08ae80256f064572a1f0ab6 One thing I noticed is nginx where it serves the React files seems to be forbidden: nginx_1 | 2024/03/31 14:57:00 [error] 29#29: *1 directory index of "/var/www/frontend/" is forbidden, client: 172.20.4.193, server: , request: "GET / HTTP/1.1", host: "172.21.4.130" nginx_1 | 172.20.4.193 - - [31/Mar/2024:14:57:00 +0000] "GET / HTTP/1.1" 403 153 "-" "ELB-HealthChecker/2.0" "-" nginx_1 | 2024/03/31 14:57:01 [error] 29#29: *2 directory index of "/var/www/frontend/" is forbidden, client: 172.20.1.172, server: , request: "GET / HTTP/1.1", host: "172.21.4.130" nginx_1 | 172.20.1.172 - - [31/Mar/2024:14:57:01 +0000] "GET / HTTP/1.1" 403 153 "-" "ELB-HealthChecker/2.0" "-" Here is my docker-compose.yaml file version: '3.7' services: # Redis redis: image: redis:alpine container_name: redis ports: - "6379:6379" backend: volumes: - .:/django - static:/static env_file: - .env build: context: ./backend ports: - "8000:8000" container_name: backend_container frontend: build: context: ./frontend volumes: - frontend:/app/build container_name: frontend_container nginx: build: context: ./nginx volumes: - static:/static - frontend:/var/www/frontend ports: - "80:80" depends_on: - redis - backend … -
Root path analogue in uWSGI as in Uvicorn
Uvicorn has the option --root-path (https://www.uvicorn.org/settings/#http) that helps a lot if the application is mounted to a specific path, distinct to /. For example, in case of a Django application I can run it with: uvicorn myproj.asgi:application --host=localhost --port=8001 --root-path="/myproj-custom-path" So if I configure the Nginx location /myproj-custom-path/ as proxy_pass http://localhost:8001/, I can access the application by http://localhost:80/myproj-custom-path with all the functionality, including the Admin panel, without the need to specify the root path anywhere else in the project. Is there a similar option or a way to do the same with uWSGI? -
Django register function accepting a new user while the login function can't find it
I'm creating a site using django, python and html. I have an app called account which I have currently written two functions for: register and login_view. My register function works properly, accepting a user unless their username is already taken or their two passwords are not a match. However, my login_view function doesn't seem to recognize the same user that has just been created in the register page, giving me this error: return render(request, 'account/login.html', {'error': 'Wrong username or password.'}) Here are the files inside my account folder I've worked on so far: views.py: from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def register(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: the_username = request.POST['username'] try: the_user = User.objects.get(username = the_username) return render(request, 'account/register.html', {'error': 'Username already taken. Please choose another one!'}) except User.DoesNotExist: new_user = User.objects.create(username = the_username, password = request.POST['password1']) return render(request, 'account/profile.html') else: return render(request, 'account/register.html', {'error': 'Passwords do not match.'}) else: return render(request, 'account/register.html') def login_view(request): if request.method == 'POST': the_user = authenticate(username = request.POST['username'], password = request.POST['password']) if the_user is not None: login(request, the_user) return render(request, 'account/profile.html') else: return render(request, 'account/login.html', {'error': 'Wrong username or password.'}) else: return render(request, …