Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to Access LMS Course in OpenEdX: Facing WebpackBundleLookupError
After clicking on the LMS course, an error occurs and the error log shows this. Error Logs: views.py:597 - Error in /courses/course-v1:RICE+1_13_2630+2021_Q1/course/: user=neerajACT, effective_user=neerajACT, course=course-v1:RICE+1_13_2630+2021_Q1Traceback (most recent call last): File "/openedx/edx-platform/./lms/djangoapps/courseware/views/views.py", line 509, in get return super().get(request, course=course, page_context=page_context, **kwargs) File "/openedx/venv/lib/python3.8/site-packages/web_fragments/views.py", line 23, in get fragment = self.render_to_fragment(request, **kwargs) File "/openedx/edx-platform/./openedx/features/course_experience/views/course_home.py", line 80, in render_to_fragment return home_fragment_view.render_to_fragment(request, course_id=course_id, **kwargs) File "/openedx/edx-platform/./openedx/features/course_experience/views/course_home.py", line 152, in render_to_fragment outline_fragment = CourseOutlineFragmentView().render_to_fragment( File "/openedx/edx-platform/./openedx/features/course_experience/views/course_outline.py", line 104, in render_to_fragment html = render_to_string('course_experience/course-outline-fragment.html', context) File "/openedx/venv/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/openedx/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/openedx/edx-platform/common/djangoapps/edxmako/template.py", line 82, in render return self.mako_template.render_unicode(**context_dictionary) File "/openedx/venv/lib/python3.8/site-packages/mako/template.py", line 444, in render_unicode return runtime._render( File "/openedx/venv/lib/python3.8/site-packages/mako/runtime.py", line 874, in _render _render_context( File "/openedx/venv/lib/python3.8/site-packages/mako/runtime.py", line 916, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/openedx/venv/lib/python3.8/site-packages/mako/runtime.py", line 943, in exec_template callable(context, *args, **kwargs) File "/tmp/mako_lms/629639353521218167/course_experience/course-outline-fragment.html.py", line 357, in render_body __M_writer(filters.html_escape(filters.decode.utf8(static.webpack(entry='CourseOutline')))) File "/tmp/mako_lms/1ff981c2157d500713c1ce6bf7fdbce2/static_content.html.py", line 282, in render_webpack __M_writer(filters.html_escape(filters.decode.utf8(HTML(render_bundle(entry, extension=None, config='DEFAULT', attrs=attrs))))) File "/openedx/venv/lib/python3.8/site-packages/webpack_loader/templatetags/webpack_loader.py", line 12, in render_bundle tags = utils.get_as_tags(bundle_name, extension=extension, config=config, attrs=attrs) File "/openedx/venv/lib/python3.8/site-packages/webpack_loader/utils.py", line 62, in get_as_tags bundle = _get_bundle(bundle_name, extension, config) File "/openedx/venv/lib/python3.8/site-packages/webpack_loader/utils.py", line 40, in _get_bundle bundle = get_loader(config).get_bundle(bundle_name) File "/openedx/venv/lib/python3.8/site-packages/webpack_loader/loader.py", line 82, in get_bundle raise WebpackBundleLookupError('Cannot resolve bundle {0}.'.format(bundle_name))webpack_loader.exceptions.WebpackBundleLookupError: Cannot resolve … -
Error: Cannot read properties of undefined (reading 'session')
I am creating a web application, and I'm using Next.js for the front-end and Django for the back-end. I am making a home page that redirects to your profile if you're logged in and displays a login dialog if you're not. I'm running into this error: Error: Cannot read properties of undefined (reading 'session') Here's the full error: src\app\layout.tsx (9:53) @ session ⨯ TypeError: Cannot read properties of undefined (reading 'session') at App (./src/app/layout.tsx:17:40) at stringify (<anonymous>) digest: "2784612708" 7 | export const theme = extendTheme({}); 8 | > 9 | export default function App({Component, pageProps: {session, ...pageProps}}: AppProps) { | ^ 10 | return ( 11 | <SessionProvider session={session}> 12 | <ChakraProvider theme={theme}> ⨯ src\app\layout.tsx (9:53) @ session ⨯ TypeError: Cannot read properties of undefined (reading 'session') at App (./src/app/layout.tsx:17:40) at stringify (<anonymous>) digest: "2784612708" 7 | export const theme = extendTheme({}); 8 | > 9 | export default function App({Component, pageProps: {session, ...pageProps}}: AppProps) { | ^ 10 | return ( 11 | <SessionProvider session={session}> 12 | <ChakraProvider theme={theme}> GET / 404 in 1684ms Here's my layout.tsx // pages/_app.tsx import type {AppProps} from "next/app"; import {SessionProvider} from "next-auth/react"; import {ChakraProvider, extendTheme} from "@chakra-ui/react"; export const theme = extendTheme({}); … -
Text won't show up in html template
When I tried to integrate a html template I found online everything worked fine but the text just doesn't show up. I was following a tutorial where they made me use a static file to load in the site. Another problem I had is that I didn't understand what what to encase in {% static 'file name here'%}. Would appreciate if you could help with that too. P.S. I used this template https://bootstrapmade.com/maxim-free-onepage-bootstrap-theme/ Down Below is a piece of the index.html from the template. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>My Portfolio</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="{% static 'assets/img/favicon.png' %}" rel="icon"> <link href="{% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="{% static 'https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i' %}" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="{% static 'assets/vendor/aos/aos.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/boxicons/css/boxicons.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/glightbox/css/glightbox.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet"> <!-- Template Main CSS File --> <link href="{% static 'assets/css/style.css' %}" rel="stylesheet"> <!-- ======================================================= * Template Name: Maxim * Template URL: https://bootstrapmade.com/maxim-free-onepage-bootstrap-theme/ * Updated: Mar 17 2024 … -
Django error while creating the blog web application
urls.py path("blogpost/int:id", views.blogpost, name="blogpost) views.py def blogpost(request, id): post = Blog1.objects.filter(post_id = id)[0] return render(request, 'blogpost.html', {'post':post}) having an error that Blog1 object is iterable. tried everything and my model has been created as well for blog1 and primary key has been issues under post_id, but I don't no why am I having this error about object is iterable, any idea ?? -
`504 Gateway Time-out` when sending emails with Djoser and Nginx in Django production
I am encountering an issue in my Django production environment when using Djoser for user registration and login management. When a user requests to create an account, the API takes about a minute and then returns a 504 Gateway Time-out error. In my local environment, the process works correctly, and the activation email is sent without issues. Here are the details of my environment and configurations: Nginx Configuration: server { listen ${LISTEN_PORT}; location /static { alias /vol/web/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; # Timeout settings uwsgi_read_timeout 120; proxy_read_timeout 300s; proxy_connect_timeout 300s; proxy_send_timeout 300s; } } Relevant Email Sending Code: class ActivationEmail(email.ActivationEmail): template_name = "user/email/activation.html" def send(self, to, *args, **kwargs): print(f"Sending activation mail to {to}") try: super().send(to, *args, **kwargs) except: print(f"Couldn't send mail to {to}") raise print(f"Activation mail sent successfully to {to}") Email Configuration: The email configuration is the same both locally and in production. However, the email does not arrive in the inbox, and the 504 error persists. What I've Tried: Increased timeout options in Nginx. Added logs in the email-sending function, and the function appears to be called correctly. Checked environment variables to ensure they are consistent between local and production environments. Question: What … -
Assistants API worker timeout with Django
I am using assitants api with django, sometimes I do requests and I get these errors. I am using a free server in Render, I don't know why, but some requests take a lot of time and my web app keep waiting each .5 seconds and I print a message 'queue - "number_of_iteration"': Code: async def send_message(thread_id:str, message:str): # Making prompt prompt = await PromptManager.read_prompt('prompt_message') prompt_result = PromptManager.fill_out_prompt(prompt, {'message':message}) # Sending prompt message await OpenAISingleton.create_message(thread_id, prompt_result) run = await OpenAISingleton.run_thread(thread_id) # Getting answer return await OpenAISingleton.retrieve_message(run, thread_id) class OpenAISingleton(): __client = None @classmethod def __get_connection(self): """ This method create our client and give us a new thread """ client = AsyncOpenAI(api_key=settings.OPENAI_API_KEY,) return client def __new__(cls, *args, **kwargs): if cls.__client==None: # making connection cls.__client = cls.__get_connection() return cls.__client @classmethod async def create_message(cls, thread_id:str, message:str): """ This method create a new message in the assistant """ message = await cls.__client.beta.threads.messages.create( thread_id=thread_id, role="user", content=message ) return message @classmethod async def run_thread(cls, thread_id:str): """ This method run our thread to process a response the answer from the assistant """ run = await cls.__client.beta.threads.runs.create( thread_id=thread_id, assistant_id=settings.ASSISTANT_ID ) i = 0 while run.status == "queued" or run.status == "in_progress": run = await cls.__client.beta.threads.runs.retrieve( thread_id=thread_id, run_id=run.id, ) … -
GEOSException in dev container for geodjango with postgis for python 3.12
I'm trying to setup a dev container to develop a geodjango application. The dev container spins up and runs but when browsing in the admin to the model overview that contains a PointField, I get the following error message: Error message: GEOSException at /admin/phyiscal_assets/plant/ Error encountered checking Geometry returned from GEOS C function "GEOSWKBReader_read_r". Request Method: GET Request URL: http://localhost:8002/admin/phyiscal_assets/plant/ Django Version: 5.0.7 Exception Type: GEOSException Exception Value: Error encountered checking Geometry returned from GEOS C function "GEOSWKBReader_read_r". Exception Location: /workspaces/django-test/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/prototypes/errcheck.py, line 33, in check_geom Raised during: django.contrib.admin.options.changelist_view Python Executable: /workspaces/django-test/.venv/bin/python Python Version: 3.12.4 Python Path: ['/workspaces/django-test/src/XXX', '/usr/local/lib/python312.zip', '/usr/local/lib/python3.12', '/usr/local/lib/python3.12/lib-dynload', '/workspaces/django-test/.venv/lib/python3.12/site-packages', '/workspaces/django-test/src'] Server time: Wed, 31 Jul 2024 15:09:24 +0000 models.py from django.contrib.gis.db import models #as gis_models class Plant(models.Model): """Model representing a plant.""" name = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=200) location = models.PointField() # lat and long point fields def __str__(self): """String for representing the Model object.""" return self.name admin.py: from django.contrib.gis import admin from .models import Plant @admin.register(Plant) class PlantAdmin(admin.ModelAdmin): list_display = ('name', 'city') The DEV Container (VS Code) is created via: devcontainer.json: { "name": "Python 3", "build": { "dockerfile": "Dockerfile", "context": "..", "args": { "NODE_VERSION": "lts/*", "POETRY_VERSION": "1.8.3", "NOX_VERSION": "2024.4.15" } }, "customizations": { "vscode": { … -
Django command doesn't apply changes when raising an exception
I created a django command to remove about 100.000 entries in our database, however we tested it and noticed that when the command is terminated or otherwise raises an exception, the .delete() is not applied. For example the command is at 100 of the 100.000 and we terminate the command, all entries are still there and the 100 that should be gone are still there. Does anybody know why this happens and if this behaviour can be disabled. I know this can be dangerous, but we need it :) I tried to look at the implementation, but I cannot figure it out. -
How to avoid IntegrityError and db collision when saving model after sanitize slug with slugify in Django?
I am currently working on a simple web project, where I have several models that make use of SlugField as URL, such as Page, Note and Tag. From the admin panel the user can edit the slug and other fields of the model. The user can modify the slug manually to make it more user friendly. The user can also enter content in uppercase, and special characters, either by mistake or by malpractice. The validation of the slug as a unique field is done correctly in the frontend if it is entered correctly, but not if uppercase characters or special characters are entered. Here is an example: User creates a new tag with slug: new-tag Hit save, and it does the work. User creates a new tag with slug new-tag Hit save, and the user get a front end validation warning, saying is not possible. Ok, as expected. User creates a new tag with slug: New-Tag(noticed the capital letters) Hit save and we got. Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: notes_tag.slug Which is expected and im trying to address it. This is my model: You can check full project here: Github repo class Tag(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, … -
i always get error on this statement even if statement is false or true if password != confirm_password: print("Password error")
if password != confirm_password: print("Password error") return redirect("user_register") else: if User.objects.filter(email=email).exists(): print("Email already exists") return redirect("user_register") else: if User.objects.filter(username=username).exists(): print("Username error") return redirect("user_register") else: user = User.objects.create_user(username=username, email=email, password=password) user.save() data = Customer(user=user, phone_field=phone) data.save() # Code for login user again our_user = authenticate(username=username, password=password) if our_user is not None: login(request, our_user) return redirect("") else: print("Authentication error") return redirect("user_register") return render(request, 'accounts/register.html') i want when my all statement got true then data save to database and redirect page to login page and after that redirect from login to home page -
Why do I need to restart docker container to update code changes
I am developing a Django-based application in a Docker container. All the volumes are set up correctly but I noticed something concerning file updates in the docker container. After some time, the docker container cannot update the file in the container despite changes in my host machine. I am forced to restart the container to make the changes reflect. What could be the cause of this issue? Why files in a docker container may be out of sync with files in the host machine yet the volumes are correctly mapped? I tried to restart the container and the changes reflected but I want to know what causes this issue? -
How to Pass Tenant ID to FastAPI Microservices for Database Operations in a Django-Tenants Setup?
I'm relatively new to Django-tenants. My goal is to develop a SaaS application that runs on Kubernetes, where each tenant has its own database. For scalability and fault tolerance, I'm considering using FastAPI as microservices to manage individual modules separately. Architecture example Would it be advisable to structure the application this way, or would it be better to stick with a monolithic Django architecture and compromise on individual scalability? If it is recommended, how should I structure FastAPI to handle tenant-specific operations, such as using an X-Tenant-ID header in AJAX requests to determine the appropriate CRUD operations? I tried to send the tenant ID via AJAX (Header: X-Teantn-ID: 1) to the FastAPI microservice, but FastAPI is unable to establish a connection to the database using the tenant ID. -
Django Nginx And Gunicorn subdomain hosting gets 400 error
Nginx and Django Setup Results in Bad Request (400) Error I'm trying to configure Nginx to serve my Django application, but I'm encountering a "Bad Request (400)" error. I've set up my Nginx server block and Django settings as follows: server { listen 80; server_name subdomain.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/diagrjxt/medinote/staticfiles/; } location /media/ { alias /home/diagrjxt/medinote/media/; } location / { proxy_set_header Host $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:/run/medinote.sock; } } DEBUG = False ALLOWED_HOSTS = ['*'] Issue: I've restarted both Gunicorn and Nginx, but I still receive a "Bad Request (400)" error when I try to access the site. There are no errors in the Nginx error log, but the access log shows the following entries: 103.121.239.95 - - [31/Jul/2024:06:22:40 +0000] "GET / HTTP/1.1" 400 154 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/5127.36" "-" 103.119.239.95 - - [31/Jul/2024:06:22:40 +0000] "GET /favicon.ico HTTP/1.1" 400 154 "http://medinote.diagnotech-ai.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" "-" -
Keycloak 25.0.2 - Django - Force Login
I need to add an external auth in my Django + Keycloak application. Unfortunally there is no native plugin for this auth (is specific for my Country) so I need to manage it with Python and then force a user login using PythonKeycloack (that use api) without knowing the user password. What I have is an admin account, and relative tokens, that may be usefull to achieve this goal. Thanks -
How to change the Display Name on sent emails with django allauth?
I'm using django allauth to sign up users and sending confirmation emails to new users and it's working fine except that it shows "support" as in "support@example.com" as my name. I'd like it to change that to "Khaled from XYZ". I tried the following but it actually crashed the smtp connection: EMAIL_HOST_USER = 'Khaled from XYZ <support@example.com>' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
db.sqlite to postgresql conversion in a django project
Error : RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres.railway.internal" to address: No such host is known. warnings.warn( No changes detected DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': '*****************', 'HOST': 'postgres.railway.internal', 'PORT': '5432', } }```` Earlier the database support was made via db.sqlite by sql is not supportd by vercel for deployment so had to convert it to postgresql but this error is showing up I do not have command over postgresql so i do not have it installed rather I have used railway.app for the purpose -
How can i manage boolean flags in Django?
Can somebody explain, which best practice should i use for managing flags in my Django Models, that will be serialize in DRF I have this model: class Project(models.Model): * Logic * is_free = models.BooleanField(default = True) is_paid = models.BooleanField(default = False) is_free_or_donate = models.BooleanField(default = False) How should i manage this flags in Django? Should I use model methods for this purpose to incapsulate logic within model? Or maybe overwrite save methods and do it there? I appreciate for having tips about best practices -
CommandError: This field cannot be blank. This field cannot be null.This field cannot be blank.; This field cannot be blank. when creating a superuser
I have seen similar concerns here but none fixes my problem. I am making my first project in Django and wagtail. I am fairly new with both of them, so please be nice :). I am using a custom user for django authentication and I keep getting the error in teh title every time I try to create a super user. The more confusing thing is, the user seems to be registered because when I try to use the email in the next creation, it says that teh email has been used but then when I try to login, it says that the user has no profile. Here is my code, any answers will be appreciated. The user model has the following code: from typing import ClassVar from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin, Group, Permission from django.db import models from django.db.models import BooleanField from django.db.models import CharField from django.db.models import EmailField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from rhs_soccer.users.enums import UserRoles from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): """ Default custom user model for RHS Boys Soccer Club. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. … -
How to create and use multiple standalone vue apps in one html page (Vue2 + Django)
Im kind off new to vue and I'm trying to implement a vue + vuetify + vuex frontend in my already half written django application, I want the vue applications to connect independently of each other in different divs of html pages At the moment, with this connection: <div class="tab-content" id="settings-tab-content"> <script type="application/json" id="initial-data"> { "is_superuser": {{ is_superuser|lower }} } </script> <div class="tab-pane fade" id="groups-tab-content" role="tabpanel" aria-labelledby="groups-tab"> <div id="userGroups"></div> </div> <div class="tab-pane fade" id="structure-tab-content" role="tabpanel" aria-labelledby="structure-tab"> <div id="app"></div> </div> </div> import Vue from 'vue' import clinicStructure from './clinicStructure.vue' import userGroups from './userGroups.vue' import router from './router' import store from './store' import vuetify from './plugins/vuetify' import '@mdi/font/css/materialdesignicons.css' import 'vuetify/dist/vuetify.min.css' Vue.config.productionTip = false new Vue({ router, store, vuetify, render: h => h(clinicStructure) }).$mount('#app') new Vue({ router, store, vuetify, render: h => h(userGroups) }).$mount('#userGroups') Components and building with this "build": "vue-cli-service build --dest=../../static/builds/prod", "dev": "vue-cli-service build --dest=../../static/builds/dev --mode=development --watch" works fine but modal windows from one element open in another (in the one that is mounted first) So, how can I make a separate vue component connect to a specific div without affecting other components p.s. I can't make one entry point for frontend and then process paths through vue router, I need … -
SSE react '406 (Not Acceptable)'
I have some problem with react and django application. I want to use SSE to let the two of them communicate, but I get 406 responses from the front end. I think I fail when I try to connect. I can't get a response from the backend. This is my django code class Test(viewsets.ViewSet): def list(self, request): def test(): i = 1 while i < 6: yield f'data: {i}\n\n' i += 1 return StreamingHttpResponse(test(), content_type='text/event-stream') And my react code import { NativeEventSource, EventSourcePolyfill } from 'event-source-polyfill'; export default function Teset() { const test = () => { const EventSource = EventSourcePolyfill; const eventSource = new EventSource( "http://localhost:30018/test/", { headers: { "Content-Type": "text/event-stream", }, withCredentials: true, } ); }; return ( <> <button onClick={test}>button</button> </> ) } If you know the answer, please leave an answer. I saw an answer on Google saying you just need to specify what type you will receive in the header, but to no avail. -
How to get Parent Thread request data to all Child threads. using DRF
How to get Parent Thread request data to all Child threads. using DRF. I store request data using middleware and i get this request in subthread i not get that values. middleware.py class GlobalHttpRequestMiddleware(MiddlewareMixin): global_request.set_request(request) global_request.py class GlobalRequest(local): """Thread local class to store Http request object""" def __init__(self): self.__request: Optional[HttpRequest] = None def get_request(self) -> Optional[HttpRequest]: """ getter() to get the request""" return self.__request def set_request(self, request: HttpRequest) -> None: """ setter() to set the request""" self.__request = request global_request = GlobalRequest() class ThreadGlobal: """Create a Custom request object for a thread""" def __init__(self, current_scheme: Optional[str], meta_data: Optional[dict]): self.current_scheme = current_scheme self.meta_data = meta_data sample.py request = global_request.get_request() thread = CustomThread(target=Trigger.samplefn, args=([a1, a2]), initialize_env=_set_custom_app_env) thread.start() thread_callback.py def _set_custom_app_env() -> Callable[[], None]: # getting the global request from current thread and storing it into the variable to pass inside child function global_request_data = global_request.get_request() currect_scheme = global_request_data._current_scheme_host meta_data = global_request_data.META request = ThreadGlobal(currect_scheme, meta_data) def _set_env() -> None: '''This inner function will be executed inside the child threads''' global_request.set_request(request) return None return _set_env in global_request.set_request(request) in side the _set_env closer funtion i get request is NONE why... Give solution -
Difference in date translation between localhost and production - django
Localhost: Production (nginx + gunicorn): Do you have any idea why this happens? And it happens only in polish. German, japanese, english and spanish work perfectly on production as well. Settings.py: LANGUAGE_CODE = "en-us" LANGUAGES = [ ("pl", "Polski"), ("en", "English"), ("es", "Español"), ("de", "Deutsch"), ("ja", "Japanese"), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) TIME_ZONE = "Europe/Warsaw" USE_I18N = True USE_L10N = True USE_TZ = True HTML: {% for concert in concerts %} <div class="detailed-page-text calendar"> <p class="concert-title">{{ concert.title }}</p> <p class="concert-date">{{ concert.date }}</p> <p class="concert-time"><bold>{{ concert.time }}</bold></p> <p class="concert-location">{{ concert.location_main_name }}</p> <p class="concert-address">{{ concert.location_address }}, {{ concert.city }}</p> {% if concert.link_to_details %} <a class="more" href="{{ concert.link_to_details }}"> {% trans "More" %}</a> {% endif %} <br> </div> {% endfor %} I tried clearing nginx cache manually - no result. restarting, reloading server. Did not help much. I have also restarted gunicorn and gunicorn.socket. No result. -
Using Django as the SSO Identity Provider?
Instead of using a 3rd-party SSO tool (Okta, Auth0, Outseta...), I want to use my Django app as it's own Identity Provider (to maintain my custom-built registration and login flows) ...BUT I can't seem to find any resources/tutorials/examples of this being done. Specifically, I want my registered users to access my BetterMode instance via their "Custom Oauth2" option (Their support says they support my use case). Question: Are there Django libraries that support Django being it's own identity provider? Is this wildly uncommon for reasons I'm not seeing? Otherwise, is the solution just custom code with the django.authlib library? (ex: client_id/secret > Auth/token/callback_Urls...) -
using variable to reference Panda Column name in python
i'm trying to write a function to simplify my code, as a result i'm passing variables containing column names. its for a Django app and the debugger is not giving any feedback on where my error is, just 'internal server error'. My code works fine written NOT as function: df_trips['trip_time_prep_starts'] = df_trips["trip_time_prep_starts"].map(str) df_trips.trip_time_prep_starts = pd.to_datetime(df_trips.trip_time_prep_starts) df_trips['trip_time_left_house'] = df_trips['trip_time_left_house'].map(str) df_trips.trip_time_left_house = pd.to_datetime(df_trips.trip_time_left_house) df_trips['stage1_duration']=(df_trips['trip_time_left_house']-df_trips['trip_time_prep_starts']).dt.total_seconds() written as a function, passing the following variables: stage_name="stage1_duration" stage_start="trip_time_prep_starts" stage_end="trip_time_left_house" my function: def calc_stage_duration(df_trips, stage_name, stage_start, stage_end): df_trips[stage_start] = df_trips[stage_start].map(str) df_trips.[stage_start] = pd.to_datetime(df_trips.[stage_start]) df_trips[stage_end] = df_trips[stage_end].map(str) df_trips.[stage_end] = pd.to_datetime(df_trips.[stage_end]) df_trips[stage_name]=(df_trips[stage_end]-df_trips[stage_start]).dt.total_seconds() I can't find my mistake and I'm not clear on the proper use of brackets and periods, for example df_trip.[stage_end] versus df_trips[stage_end] -
Django nginx 502
Looking for a solution how to fix nginx 502 Bad Gateway with Django using Elastic Beanstalk. Django application is correct, locally everything works seamlessly. Problems occurs when I am trying to deploy that application to AWS EC2. I use AWS PostgreSQL Database. All environment variables are saved in AWS environments correctly. Have traversed through all solutions but, nothing helped. Is it ever possible that some libraries create a conflict that results 502 Bad Gateway? Using Python 3.11.9 **requitements.txt** asgiref==3.8.1 boto3==1.34.141 botocore==1.34.141 certifi==2024.7.4 charset-normalizer==3.3.2 colorama==0.4.6 crispy-bootstrap5==2024.2 Django==5.0.6 django-autoslug==1.9.9 django-crispy-forms==2.2 django-environ==0.11.2 django-mathfilters==1.0.0 django-storages==1.14.4 django-utils-six==2.0 djangorestframework==3.15.2 gunicorn==20.1.0 idna==3.7 jmespath==1.0.1 packaging==24.1 phonenumbers==8.13.40 pillow==10.3.0 psycopg2-binary==2.9.9 requests==2.32.3 s3transfer==0.10.2 six==1.16.0 sqlparse==0.5.0 tzdata==2024.1 urllib3==2.2.2 Then **.ebextensions/django.config** option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ecommerce.wsgi:application Then **Procfile** web: gunicorn ecommerce.wsgi:application --bind 0.0.0.0:8000 Then **ecommerce/ecommerce/wsgi.py** import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings") application = get_wsgi_application() Then **.ebignore** requirements.dev.txt .pytest_cache/ tests/ .pytest_cache/ *.test.py test_*.py *.local .env .env.example .git/ README.md .prettierignore .vscode/ .idea/ *.pyc __pycache__/ .mypy_cache/ .nox/ .coverage .tox/ .venv/ CMD Output: >eb logs Retrieving logs... =========================== ---------------------------------------- /var/log/web.stdout.log web[2267]: File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/gunicorn/util.py", line 359, in import_app