Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Final year topic [closed]
I am thinking about to create one web application using pythno and django name is Project match maker. It will help students to find the perfect group partner for their project according their requirements and skill set. I have tried to take some advise my tutors but they all are saying this is not that complicate and I have tried to advise them because this is similar like tinder and other dating application. What are your views Any suggestion -
Can non-displayed fields of a Django model be altered during custom form validation but before committing model's data?
for the last few weeks I've been working on my first Django project: a database to register all incoming orders from Customers for a generic enterprise. Let's assume that each one of the sale reps could be assigned to a specific Customer for a whole natural year and assignments may vary from one year to another (i.e. agent A assigned to customer A in 2024, whereas in 2025, agent B might be in charge of customer A). As a start, I decided to use a FK inside Orders model to refer to the associated Product and Customer. At the same time, the Assignments model would also keep a couple of FK to the Customer and Agent tables, so everything could be connected, accessible and data loops were avoided in my relational diagram. Still, this solution was really painful to get some data, specially when I needed to retrieve filtered data for the final templates... so I decided to turn everything upside down and take a different approach: class Order (models.Model): assignment = models.ForeignKey("Assignment", on_delete=models.RESTRICT) product = models.ForeignKey("Producto", on_delete=models.RESTRICT) quantity = models.PositiveIntegerField(default=1) order_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) class Assignment (models.Model): assignment_year = models.PositiveSmallIntegerField() customer = models.ForeignKey("Customer", on_delete=models.CASCADE) agent = … -
Django `Not Found: /payment_getway/` Error - URL Path Not Resolving
I’m encountering a Not Found: /payment_getway/ error in my Django application. Despite setting up the URL path and view function, Django cannot find the specified URL. I’ve provided all relevant code snippets and configurations below. I’m not sure what might be causing this issue. Here’s a brief overview of what I’ve done: URL Configuration: In my app's urls.py, I have defined the path for the payment_getway view function: urlpatterns = [ path('payment_getway/', payment_getway, name='payment_getway'), path('order-confirmation/', order_confirmation, name='order_confirmation'), ] View Function: The view function payment_getway is defined as follows: from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from .models import CartOrder, Address def payment_getway(request): if request.method == "POST": user = request.user address_id = request.POST.get('address_id') # Ensure this ID is passed in your form # Retrieve the address instance address_instance = get_object_or_404(Address, id=address_id, user=user) # Create a new CartOrder instance order = CartOrder( user=user, full_name=address_instance.name, email=address_instance.email, mobile=address_instance.mobile, address=address_instance, # Assign the Address instance here landmark=address_instance.landmark, city=address_instance.region, state=address_instance.region, # Update as per your address model postalCode=address_instance.pin, item="Your Item", # Update this as necessary price=100.00, # Example price, adjust accordingly saved=0.00, # Example saved amount, adjust accordingly shipping_method="Standard", # Update this as necessary tracking_id="Tracking ID", # Example tracking ID tracking_website="Tracking Website", # … -
Django query to sum the n largest related values
I have a db that tracks players' scores over a number of games. I want to create a leaderboard using each player's 4 highest scoring games. Here are my models: class Event(models.Model): name = models.CharField(max_length=120) class Player(models.Model): name = models.CharField(max_length=45) class Game(models.Model): name = models.CharField(max_length=15) class Score(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) score = models.IntegerField() class Meta: unique_together = ["player", "event", "game"] I've tried using a subquery, but it seems like my slice is being ignored and the sum returned is all of the player's scores, not just their top 4 scores: scores = Score.objects.filter(player=OuterRef('pk'), event=myEvent).order_by('-score')[:4] scores = scores.annotate(total=Func(F("score"), function="SUM")).values('total') leaders = Players.objects.annotate(total=Subquery(scores)).order_by('-total') Any ideas on how to get the subquery working? Or a better way to approach the problem? -
Conditional Rendering in Svelte Based on Server's Response
I am building a web application with Django as the server and Sveltekit on the client. During the registration process, a link with a token is sent from the server to the user's provided email, when they visit their mailbox and click on the link they are redirected to the SvelteKit's domain. Now, here is the problem - the client sends the token to the server for validation, and on the server I have a view that validates the token to see if it is valid or expired and sends the appropriate response to the client. Now, depending on the response received, I want to conditionally render out the right block of code to the user. If the server says the token is valid, they can finish their registration, otherwise, they need to resubmit their email for another token to be sent. The issue I have seems to be with my SvelteKit and not my server. This is my views.py - @method_decorator(csrf_exempt, name='dispatch') class ValidateTokenView(View): def get(self, request, token, *args, **kwargs): try: # Check if the token exists in the database token_instance = EmailConfirmationToken.objects.filter(token=token).first() print(f"Token received: {token}") print(f"Token instance retrieved: {token_instance}") if token_instance: print(f"Token created at: {token_instance.created_at}") is_expired = token_instance.is_expired() … -
Djoser Create User keeps returning field required and is not creating users
I ran into a problem in postman that was not there until yesterday when I was working with it and it was working fine, but now it is not working anymore. I'm trying to create a user using djoser default path, but whenever I send request, I face required field for username and password while both exist, I also send email field which is required by django, but no help. I tried some hints over internet but no luck. In setting, the code is like this for djoser: # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # djoser 'djoser', # djoser 'main', ) # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] REST_FRAMEWORK = { # 002 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # 012 Session --> Tokan #djoser 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_PAGINATION_CLASS': # 011 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1, 'DEFAULT_THOTTLE_CLASSES': ( # 014 'rest_framework.throttling.AnonRareThrottle', 'rest_framework.throttling.UserRareThrottle', ), 'DEFAULT_THROTTLE_RATES': { # 014 'anon': '5/minute', 'user': '10/minute', }, } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, # djoser } DJOSER = { 'SERIALIZERS': { 'user_create': … -
Multi Tenancy in django with user custom domains
I have a project that is currently running with an app called knowledgebase. In Knowledgebase, users can log in and see the articles created by other users in their company. There are 2 types of articles, public and private articles. Public articles can be accessed by anyone, whether logged in or not. All public articles are currently found in a public knowledgebase which is basically a page on a route like /articles/public/company-1 which shows all public articles by company 1 and we may have another like /articles/public/company-2 which shows public articles by company 2 and so on. We are currently thinkin of adding custom user domains to the project such that company 1 can add a domain like company1.com which will basically return similar view as /articles/public/company-1. Company 2 can also add company2.com and return their public articles too. How can we achieve this? Additional info: The frontend is on react and the backend running on django-rest-framework. The apsp are hosted separately in heroku and domains are from cloudflare. NOTE: we are open to any solutions, even if making the public articles a separate project. I have tried checking out projects like django-tenants but still not sure of how the … -
How to Host a Django Project with PostgreSQL and Celery on a Platform with Fixed Yearly Pricing?
I am a freelancer with a full-time job, and I am looking for a hosting solution for my Django project that requires minimal oversight and provides a fixed yearly price. Here are my specific requirements: Ease of Use: I prefer a user-friendly interface as I don’t have much time to manage and monitor the hosting environment. Managed Services: I need a hosting provider that handles most of the backend tasks such as security updates, backups, and scaling automatically. PostgreSQL Support: My Django project uses PostgreSQL, so the hosting solution should support this database. Celery Integration: My project also uses Celery for background tasks, so the hosting solution should support easy integration and management of Celery and a message broker like Redis or RabbitMQ. Fixed Yearly Pricing: I would like to have a predictable cost to effectively charge my clients, ideally with a fixed yearly pricing plan. Stability and Reliability: The hosting should be stable and reliable with good performance. Minimal Work: As I am balancing multiple responsibilities, the hosting solution should require minimal work from my end after the initial setup. I have considered using Hostinger for hosting my Django project because it offers a user-friendly interface and affordable plans. … -
how to fetch data from wordpress
how to intagrate wordpress. and how to fetch the blog post content from the wpordpress site? this is my get request url: https://wp.com/oauth/authorize?client_id=JFfZZ6rA41FU0MAWI1nKzGGX8ZrcCtEFpPMiun5q&response_type=code&redirect_uri=http://localhost&scope=basic it show this response: Forbidden You don't have permission to access this resource. Apache/2.4.41 (Ubuntu) Server at wp.ailaysa.com Port 443 how to get authorization code and then access code? -
ValueError at/account/logout
i have these codes in my django 5.0.7 and got this error which says: The view accounts.views.logout_view didn't return an HttpResponse object. It returned None instead. it seems like[text] but i have tried these: from django.urls import path from. import views from django.contrib.auth import views as auth_views urlpatterns = [ path('',views.home), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', views.logout_view, name='logout'),] forms.py: class LogoutForm(forms.Form): confirm_logout = forms.BooleanField(label='Confirm Logout') views.py: def logout_view(request): if request.method == 'POST': form = LogoutForm(request.POST) if form.is_valid(): form.save() return redirect('home') # Replace 'home' with your desired redirect URL else: form = LogoutForm() # Create an empty form for GET requests return render(request, 'logout.html', {'form': form}) -
Order of filters affect the query result in Djongo
I use Djongo package to connect to MongoDB from my Django app. However, there is inconsistency in the query results, even though not expected. Here is my model: class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField() date = models.DateTimeField(db_index=True) port_inventory_id = models.IntegerField(db_index=True) This query first filters by port_inventory_id, then date__range and returns the correct result items = Item.objects.filter(port_inventory_id=999999).filter(date__range=(date_from, date_to)) However, this query first filters by date__range, then port_inventory_id and returns the same number of items without the filter(port_inventory_id=999999) items = Item.objects.filter(date__range=(date_from, date_to)).filter(port_inventory_id=999999) I also tried making one filter call with two filters items = Item.objects.filter(date__range=(date_from, date_to), port_inventory_id=999999) And also reverse items = Item.objects.filter(port_inventory_id=999999, date__range=(date_from, date_to)) The only it works is this: items = Item.objects.filter(port_inventory_id=999999).filter(date__range=(date_from, date_to)) I did not expect the result to change this way. Any help is much appeciated... -
How to add authentication to a Django custom admin view?
I created a custom admin view in django for one of the models. But the url is available to anyone who is not logged it. from django.contrib import admin from django.urls import path from django.shortcuts import render, redirect from .models import Question from django.contrib.admin.views.decorators import staff_member_required class QuestionAdmin(admin.ModelAdmin): list_display = ('question_text', 'pub_date') # Your model fields def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/',self.upload_csv),] return new_urls + urls @staff_member_required def upload_csv(self,request): return render(request,"admin/csv_upload.html") admin.site.register(Question,QuestionAdmin) I tried adding the staff_member_required decorator but there is an error message saying 'QuestionAdmin' object has no attribute 'user' -
How does Django know that it needs to slugify title field?
@admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title', 'slug', 'author', 'publish', 'status'] list_filter = ['status', 'created', 'publish', 'author'] search_fields = ['title', 'body'] prepopulated_fields = {'slug': ('title',)} raw_id_fields = ['author'] date_hierarchy = 'publish' ordering = ['status', 'publish'] I know that prepopulated_fields doesn't only slufigy fields. How does Django know that slug field should be populated with a slug of the title? -
I get an error: "AttributeError: type object 'UserList' has no attribute 'as_view'", like, it doesn't see "as_view()" [closed]
I get an error: "AttributeError: type object 'UserList' has no attribute 'as_view'", like, it doesn't see "as_view()" My urls.py in Userapp from django.urls import path from .views import * urlpatterns = [ path('list', UserList.as_view(), name = 'user-view') ] views.py: from django.shortcuts import render from rest_framework.views import APIView from django.contrib.auth.models import User from .serializer import UserSerializer from rest_framework import response class UserList(): def get(self, request, *args, **kwargs): user_list = User.objects.all() serializer = UserSerializer(instance = user_list, many = True) return response(data = serializer.data) serializers.py: from rest_framework.serializers import ModelSerializer from django.contrib.auth.models import User class UserSerializer(ModelSerializer): class Meta: model = User fields = ['username', 'email', 'first_name',] -
Django can't find urls
Page not found in django. I already built startapp named posts already update the settings.py - apps - posts and put include in urls.py. still doesn't work, before posts, I have sample html file since I'm just learning, they both worked, posts doesn't. I did try rework or rewrite it, but still same error. YT don't have errors but I have -
problems with django logout Url
I have a problem with logout, which is when I define the logout path in urls.py: path ('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), I get HTTP error 405, which says: this page isn't working right now but when i change the path to: path ('logout/', auth_views.LoginView.as_view(template_name='accounts/logout.html'), name='logout'), it displays logout page, even though, technically, the user is still logged in and the profile is displayed while it should be anonymous! settings.py LOGIN_URL = '/account/login/' LOGOUT_URL = '/account/logout' urls.py from django.urls import path from. import views from django.contrib.auth import views as auth_views urlpatterns = [ path ('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LoginView.as_view(template_name='accounts/logout.html'), name='logout'), -
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, …