Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement HMTX with Django Class Based Views
I am trying to understand how to utilise htmx with Django Class Based Views. To provide some context, here is a reflection of the scenario in which I want to implement django class based views and htmx together: I have an initial view, which renders the main template and initial context. As part of this initial context, I am including a date form. I want to use htmx to post the data from this form to an APIView (let’s call it APIView1). I would like APIView1 to ingest the data which is posted to it via htmx, run a function on it, and then return data back as context, while rendering a partial template (let’s call it PartialTemplate1) which utilises that context. So from what I understand, I can do this within a get() function; so it may look a little like this: views.py Class InitialView(View): template_name = “initial_template.html” form_class = date_form def get(self, request, *args, **kwargs): … date_form=self.form_class() context = { 'date_form': date_form } return render(request, template_name, context) Class APIView1(APIView): template_name = “PartialTemplate1.html” def get(self, request, *args, **kwargs): date = request.POST.get(‘date’) timeslots = function(date) context = { ‘timeslots’: timeslots } return render(request, template_name, context). initial_template.html: <form hx-post='{% url "appname:apiview1_url" … -
Warning: Received `true` for a non-boolean attribute `crossOrigin` when using NextJS/React + Django Rest Framework
I've been receiving this warning but have little idea where it may originating from or how to solve it. It appeared seemingly out of nowhere. I went back a few commits and the warning still appeared, although I'm certain it was not present when I was initially working on those commits. I have some suspicions it may be related to CORS, or to my snake_case to camelCase converting middleware. I am using a NextJS/React frontend and a Django Rest Framework backend. Error message: app-index.js:35 Warning: Received `true` for a non-boolean attribute `crossOrigin`. If you want to write it to the DOM, pass a string instead: crossOrigin="true" or crossOrigin={value.toString()}. at link at head at html at RedirectErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9) at RedirectBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:81:11) at NotFoundErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:76:9) at NotFoundBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:84:11) at DevRootNotFoundBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/dev-root-not-found-boundary.js:33:11) at ReactDevOverlay (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:84:9) at HotReload (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:307:11) at Router (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:181:11) at ErrorBoundaryHandler (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:114:9) at ErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:161:11) at AppRouter (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:536:13) at ServerRoot (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:129:11) at RSCComponent at Root (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:145:11) Django settings.py: CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:3000", "https://localhost:3000", ] INSTALLED_APPS = [ "core", "rest_framework", "corsheaders", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "compressor", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "djangorestframework_camel_case.middleware.CamelCaseMiddleWare", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] React Frontend API calls: import * as constants from '../constants/endpoints' … -
Django fields not saving
I want to receive a file from the client and perform some processing on the image in the corresponding model class before it is saved in the database. However, since the file is not saved until the end of the save() method, the directory where the file is stored is not created and I get the error FileNotFoundError: [Errno 2] No such file or directory: 'media/upload/vertical_image.jpg'. I'm actually looking for a way to do all the processing in the save method this is my Media model: title = models.CharField(max_length=255, null=True, blank=True) file = models.FileField(upload_to="upload/") filename = models.CharField(max_length=255, null=True, blank=True) mime_type = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.JSONField(null=True, blank=True) size = models.FloatField(null=True, blank=True) url = models.CharField(max_length=300, null=True, blank=True) thumbhash = models.CharField(max_length=255, blank=True, null=True) is_public = models.BooleanField(blank=True, null=True) def save(self, *args, **kwargs): sizes = [(150, 150), (256, 256)] media_path = f"media/upload/{self.filename}" image = Image.open(media_path) mime_type = image.get_format_mimetype() format = mime_type.split("/")[1] if not os.path.exists("media/cache"): os.makedirs("media/cache") thumbnail = {} for i, size in enumerate(sizes): resized_image = image.resize(size) index = "small" if i == 0 else "medium" file_path = os.path.join( "media", "cache", f"{self.id}-resized-{self.filename}-{index}.{format}", ) resized_image.save(file_path, format=format) thumbnail["*".join(str(i) for i in size)] = file_path self.mime_type = mime_type self.size = os.path.getsize(media_path) self.thumbnail = thumbnail self.url = f"http://127.0.0.1:8000/media/upload/{self.filename}" … -
How to have multiple email backends in Django?
I would like to have both SMTP backend and console backend, so that I can send an email via SMTP while also printing the generated email to console. In my settings.py I would like to have something like this: EMAIL_BACKEND = ["django.core.mail.backends.smtp.EmailBackend", "django.core.mail.backends.console.EmailBackend"] -
how to change the django connection string with postgres in each request in order to have a record of changes
Good afternoon, I have a trigger in my database that records every change, inclusion or deletion in the tables, but instead of using the user ID connected to Postgres, I would like to pass the user ID of my application, as it is an application SASS, I will have "a user" for the database, and "n" for the application. Is there any way to pass this user to my connection? where can I retrieve it in the trigger by executing select * from pg_stat_activity? I know the solution may seem inelegant, but it provides a lot of reliability when auditing data in the database I'm using: Django 4.2 DRF 3.14.0 Postgres 16.1 I tried to change the DATABASE parameters of settings.py, before the connection and I even managed to change the application_name, but when two users execute their requests "at the same time", there is a conflict and the two connections have the same value in the application_name. -
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'book.CustomUser' that has not been installed raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'book.CustomUser' that has not been installed -
Django rest social auth and simple-jwt: NoReverseMatch at /api/login/social/jwt-pair/
I was following the documentation on drf social auth https://github.com/st4lk/django-rest-social-auth/tree/master I've encountered an issue while working with Django-Rest-Social-Auth and Simple-JWT. The error message is as follows: NoReverseMatch at /api/login/social/jwt-pair/facebook/ 'http' is not a registered namespace I've registered my path in the root urls.py (located in the config folder) as follows: path("api/login/", include("rest_social_auth.urls_jwt_pair")) Despite referring to the documentation, I'm unable to resolve this error. If anyone has encountered a similar issue or has insights into what might be causing this problem. Could someone kindly assist? -
Issues with Database Router Configuration in Django for Handling Multiple Databases
I am working on a Django application that utilizes two databases: Primary Database: This is set as the default database and is primarily used for read-only operations, such as querying analytics data. It does not handle authentication or any write operations. Secondary Database (sqlserver_db): This database is used for write operations, including migrations and authentication-related tasks. I am encountering difficulties in configuring the database router in my settings.py to properly direct read and write operations to the appropriate database. Below is my current setup: I am struggling to set the database router in my settings.py file below is what I have done in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'AAAA', 'USER': 'AAAA', 'PASSWORD': 'AAAA', 'HOST': 'AAAA', 'PORT': 'AAAA', 'OPTIONS': { 'threaded': True, }, }, 'sqlserver_db': { 'ENGINE': 'mssql', 'NAME': 'AAAA', 'USER': 'AAAA', 'PASSWORD': 'AAAAA', 'HOST': 'AAAAA', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } DATABASE_ROUTERS = ['MyApp.routers.AuthRouter'] and there in routers.py : class AuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {"auth", "contenttypes"} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ … -
implement a search bar for searching company name in django
im very new to web development. Im not really familiar with django. I got alot of this code from chatgpt. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Stockipy</title> {% load static %} <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"> <script> $(document).ready(function() { // Assuming you've set an ID for the input field, replace 'id_company_name' with the actual ID $('COMPANY_NAME').select2(); }); </script> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script> </head> <body> <h1>Stock Alert</h1> <form method = "post"> {% csrf_token %} <label for="{{ form.COMPANY_NAME.id_for_label }}">Enter Company Name:</label> {{ form.COMPANY_NAME }} <br> <label for="{{ form.PERCENTAGE_DIFF.id_for_label }}">Enter Percentage Difference:</label> {{ form.PERCENTAGE_DIFF }} <br><br> <input type="submit" value="Submit"> </form> this is the html for the page def company_autocomplete(request): term = request.GET.get('term', None) if term: # Make a request to Alpha Vantage API to get matching company names params = { "function": "SYMBOL_SEARCH", "keywords": term, "apikey": ALPHAVANTAGE_API, } response = requests.get(STOCK_ENDPOINT, params=params) data = response.json().get("bestMatches", []) # Extract company names from the API response company_names = [result["2. name"] for result in data] return JsonResponse(company_names, safe=False) return JsonResponse([], safe=False) this is the function im using in view.py. i got it from chatgpt. output image when i run this website, the Company Name text field shows up small as … -
Dj rest auth and allauth returning wrong email format
I'm building an API using DJ rest auth and allauth for registration and login. I customized the email format for registration using custom adapters. Whenever I test it out in localhost it returns the desired email format which is: Dear TestUser1, Welcome to Ekopages, your gateway to sustainable education! We're thrilled to have you join our community. To get started on your journey towards a greener future, please click the link below to confirm your email address: https://ekopages.com/registration/account-confirm-email/NTE:1rUpCQ:qimz8K0QFUD5ZM8WbMlmcBqq3HSzNp0vNSziMaJRV44/ Once confirmed, you'll have full access to ekopages.com, where learning meets sustainability. Thank you for choosing Ekopages. Let's embark on this educational adventure together! Green regards, The EkoPages Team. ekopages.com after I deploy it though it just returns a format that i didnt add Hello from ! Dear testuser, Welcome to Ekopages, your gateway to sustainable education! We're thrilled to have you join our community. To get started on your journey towards a greener future, please click the link below to confirm your email address: https://ekopages.com/registration/account-confirm-email/NjI:1rWQ5A:ZKz5BArUgGzhT8tP8KKIuV62vGdVzBQ3blPHALsxWAE/ Once confirmed, you'll have full access to ekopages.com, where learning meets sustainability. Thank you for using ! I customized the registration and adapters too so I dont know where the hello from! is coming from #models.py … -
create and send a XLSX file with Django
I need to create and send an XLSX file in Django. The problem is always I'm sending the data, the file can't be opened. I tried with openpyxl and xlsxwriter and nothing... The result is the same, or a file of 0 OR 3 bytes than can't be opened...} There is a way to made it? -
Flask or Django for a python program that process and present transmitted data?
I'm currently working on a python desktop program with the purpose of extracting data from a device, particularly a sensor and hopefully wirelessly, to process and present it on the program as a tool for an investigation group. I'm considering on using CSS, HTML, and JS fro the front-end (if that's recommendable) and Python for the back-end. I'm curious to know if there any framework necessary for its development. Any advice? From what I have found, Flask and Django are good options but I'm not sure which is more applicable. They say Django is for more complex applications while Flask is for more simpler ones. My program is designed as a desktop app that can primarily work on Windows and will have a less busy UI, so I'm conflicted on which can suit better. -
I am running webODM after customizing some code that uses opencv library, however after restarting the dockerfile I get an error
I am customizing the WebODM and added my own plugin which includes opencv, matplotlib libraries. I am running the webODM as a docker file so after building the images to register the plugin I get: WARNING Failed to instantiate plugin diagnostic: No module named 'cv2' If I comment the import cv2 I in-turn get No module named 'matplotlib'. But in the environment I am running the django app, I can safely import cv2 in the python shell without issues. I suspect the issue is the dockerfile is sort of using some other python environment that causes it not to recognize cv2. How can I resolve this issue? -
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment .how to solov
when i runserver give. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? it is coming.and when i want to see the pip version #(venv) F:\pmis\pmis>pip --version Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "F:\pmis\pmis\venv\Scripts\pip.exe_main.py", line 4, in File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\main.py", line 9, in from pip._internal.cli.autocompletion import autocomplete File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\autocompletion.py", line 10, in from pip._internal.cli.main_parser import create_main_parser File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\cmdoptions.py", line 23, in from pip._internal.cli.parser import ConfigOptionParser File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\cli\parser.py", line 12, in from pip._internal.configuration import Configuration, ConfigurationError File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\configuration.py", line 20, in from pip._internal.exceptions import ( File "F:\pmis\pmis\venv\lib\site-packages\pip_internal\exceptions.py", line 13, in from pip._vendor.requests.models import Request, Response File "F:\pmis\pmis\venv\lib\site-packages\pip_vendor\requests\models.py", line 20, in from pip._vendor.urllib3.util import parse_url ImportError: cannot import name 'parse_url' from 'pip._vendor.urllib3.util' (unknown location) ## it is showing -
Make link to foreign key object in admin screen
I have class like this which has the ForeignKey class MyLog(SafeDeleteModel): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) then I is listed user of MyLog in admin page. class MyLogAdmin(admin.ModelAdmin): list_display = ["id","user"] class UserAdmin(admin.ModelAdmin): list_display = ["id","username"] Now I want to make link in user of MyLogAdmin page to UserAdmin, Is it possible? I think some framework(such as php symfony) administrator system does this automatically. However is it possible to do this by django admin? -
Django csrf verification failed despite all tokens being present
I have a django website with forms. It works fine in debug mode on localhost but when a form is posted on a real server I get an csrf verification failed error. The form contains a csrf middleware token generated by {%csrf_token%} and the csrf token from the cookie is also sent with the request. The form is sent from subdomain.example.com/path to the same address. How can I fix this error? -
Control UUID as PrimaryKey in Django
I want to see the entire history of the object in the logs (starting with the creation request). Therefore, in the middleware, I assign a UUID to each request. If this is a request to create an object, then I want the UUID of the request to become ID of the object. I'm doing something like this: # middleware.py <...> def __call__(self, request): id = uuid.uuid4() request.id = id self.log_request(request) response = self.get_response(request) self.log_response(response) return response # then I insert the UUID into the request body, but it doesn't seem to be necessary <...> # models.py class Client(models.Model): id = models.UUIDField(primary_key=True, editable=False) phone = models.CharField(max_length=11, unique=True) operator_code = models.CharField(max_length=3, db_index=True, blank=True) def save(self, *args, **kwargs): if not self.id: self.id = kwargs.get("id", uuid.uuid4()) self.operator_code = self.phone[1:4] super().save(*args, **kwargs) But it doesn't work # app.log api.middleware INFO 2024-02-07 11:34:19,641 middleware API Request: POST /api/v1/clients/, 4b3e7620-cbb8-47b6-88b5-cb8111b3536b Body: {'phone': '01234567890', 'id': '4b3e7620-cbb8-47b6-88b5-cb8111b3536b'}, Headers: {...} api.middleware INFO 2024-02-07 11:34:19,657 middleware API Response: Status Code: 201, Body: {'id': '0ecbe66a-e6f3-452c-9ce0-ecd042bbe1e3', 'phone': '01234567890', 'operator_code': '123'}, Headers: {...} You can see that UUID are different. Is there any solution to my problem? -
How can I implement DRY on my Django views that do very similar things but on different targets?
I am implementing a social network project on Django. 2 of my models, have the following fields. class Profile(models.Model): user = models.OneToOneField(User... followers = models.ManyToManyField(Profile... class Post(models.Model): owner = models.ForeignKey(Profile... content = models.CharField(... likes = models.ManyToManyField(Profile... Now I created add_likes, add_followers, and edit_post views and they are very similar to each other. Here is a rundown of what they do: add_likes Receive a JSON object with a "target_post_id" and a boolean "like_status" (for Like or Unlike) Check validity JSON object and convert it to python objects Check if target_post exits Check is user profile does not own the post Add or Remove user profile to Post.likes based on like_status Return JsonResponses based on result (success or reason for failure) add_followers Receive a JSON object with a "target_profile_id" and a boolean "follow_status" (for Follow or Unfollow) Check validity JSON object and convert it to python objects Check if target_Profile exits Check if target is not own user profile Add or Remove user profile to Profile.followers based on follow_status Return JsonResponses based on result (success or reason for failure) edit_post Receive a JSON object with "target_post_id" and "new_content" Check validity JSON object and convert it to python objects Check if target_post exits … -
CrispyError : as_crispy_field got passed an invalid or inexistent field for email field only
I can't expose Email field from User model in django, If I remove email field from register.html there is no error. Also if I use {{ form }} It does not show the email field. It shows username, password1 and password2 with no error. models.py: from django.contrib.auth.models import User class Profile(models.Model): profile_pic = models.ImageField(null=True, blank=True, default='default.jpg') # FK user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) forms.py: from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields= ['username','email', 'password1', 'password2'] views.py: from .forms import UserCreationForm def register(request): form = UserCreationForm() if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect("my-login") context = {'form': form} return render(request, "register.html", context=context) register.html {% load static %} {% load crispy_forms_tags %} . . . <form action="" method="POST" autocomplete="off"> {% csrf_token %} {{ form.username|as_crispy_field }} # error is here {{ form.email|as_crispy_field }} {{ form.password1|as_crispy_field }} {{ form.password2|as_crispy_field }} <input type="submit" value="submit" /> </form> Django 4.2.10 django-bootstrap4 24.1 django-crispy-forms 1.14.0 pillow 10.2.0 wheel 0.42.0 -
How to implement custom ordering with cursor pagination in Django Rest Framework
I am trying to use cursor pagination (because count(*) takes too long) but I already have some code that implements custom ordering. #view.py class BookViewSet(ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() pagination_class = BookCursorPagination filterset_class = BookFilterSet filter_backends = [filters.DjangoFilterBackend] #pagination.py class BookCursorPagination(CursorPagination): page_size = 10 ordering = 'id' # Specify the field by which you want to paginate ordering_param = 'ordering' # The parameter for specifying ordering in the URL def get_ordering(self, request, queryset, view): """ Return the field or fields to use for ordering the queryset. """ ordering = request.query_params.get(self.ordering_param) if ordering: return ordering.split(',') return self.ordering.split(',') #filters.py from django.db.models import F, QuerySet, Func from django_filters import rest_framework as filters from django_filters.constants import EMPTY_VALUES from poll.models import Book class BookCustomOrderingFilter(filters.OrderingFilter): def filter(self, qs: QuerySet, value): if value in EMPTY_VALUES: return qs if any(v in ['test_ordering', '-test_ordering'] for v in value): qs = qs.annotate( author_length=Func(F('author'), function='LENGTH') ) return qs.order_by("author_length", "id") return super().filter(qs, value) class BookFilterSet(filters.FilterSet): ordering = BookCustomOrderingFilter( fields=( ("test_ordering", "test_ordering") ), ) How do I use 'test_ordering' along with Cursor pagination? -
custom column type for django create DB cache table command
I’m currently working with a PostgreSQL database and I want to use a timestamp of type ‘timestamp(0)’. To achieve this, I’ve created a custom column type using the following code: class DateTimeWithoutTZField(DateTimeField): def db_type(self, connection): return 'timestamp(0)' My question is: How can I use this custom ‘timestamp(0)’ type with the DB cache table that is created by running the Django command python manage.py createcachetable -
django using oauth2.0, getting error {"error": "invalid_grant"} when trying to get access token
Following this tutorial, https://django-oauth-toolkit.readthedocs.io/en/latest/getting_started.html on step curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=${ID}" -d "client_secret=${SECRET}" -d "code=${CODE}" -d "code_verifier=${CODE_VERIFIER}" -d "redirect_uri=http://127.0.0.1:8000/noexist/callback" -d "grant_type=authorization_code" I'm getting an error: {"error": "invalid_grant"} I have checked everything twice, and even re-assembled the app from the ground up as in tutorial, it still gives the error. Please help, thank you! -
Title: Issue with Generating ID for New Address Object
I'm encountering an issue in my project where the ID for a new address object is not being generated as expected when adding a new address. Below is the relevant code snippet from my project: models.py: class Address(EmbeddedDocument): id = fields.ObjectIdField(required=True, default=fields.ObjectId) line1 = fields.StringField() line2 = fields.StringField() city = fields.StringField() state = fields.StringField() zip_code = fields.StringField() class UserExt(Document): addresses = fields.ListField(field=fields.EmbeddedDocumentField(Address)) usercontroller.py: @api_view(["POST"]) def add_address(request, userId): try: data = request.data new_address_id = user_service.add_address(data, userId) return Response({"message": "Address added successfully", "address_id": new_address_id}, status=201) except Exception as e: return Response({"message": str(e)}, status=400) services.py def add_address(data, userId): new_address = repo.add_address(data, userId) return new_address user_repository.py def add_address(data, userId): try: connection = conn_db() new_address = data.get("addresses") # Access the new address data if new_address: result = connection.get_collection("user").update_one( {"_id": ObjectId(userId)}, {"$push": {"addresses": new_address}} ) if result.modified_count > 0: return {"message": "New address added successfully"} else: raise Exception("Failed to add new address") else: raise Exception("No address data provided") except Exception as e: raise e { "id": "65c26ed05186a91e4ef3d7c6", "line1": "abc", "line2": "xyz", "city": "palanpur", "state": "Gujarat", "zip_code": "385515" } Current output: { "line1": "pqr", "line2": "lmn", "city": "gandhinagar", "state": "Gujarat", "zip_code": "382028" } -
Python Django Admin site Custom Query Set
Background I have a Usergroup model class UserGroup(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, blank=True) def __str__(self): return self.name I want to add this on Django’s admin site so that a admin can create User groups and also assign Users to Usergroups A user should only be allowed to be in one User group A user also doesn’t have to be in a group Dont want a usergroup field on my User Model Below is what I have for my admin site at the moment. class UserGroupAdmin(admin.ModelAdmin): list_display = ('name',) search_fields = ('name',) filter_horizontal = ('users',) admin.site.register(UserGroup, UserGroupAdmin) It looks like this when Creating a group adding users ect. My thought was to change the query set to only show Users who are not in a Group and the users who are currently in the group Which means. Under Available Users You will only be allowed to Add / see users who are not yet in a group. Under Chosen User View Users already in this current Group. Question Im not sure how to approach changing the Query set. The below Works great to only show Users not in a group. But now I cant see Users already in … -
Gunicorn not able to load up Global Variables
I have a Django project deployed with Gunicorn configured in the backend, the project generates several files every day for 4 different services (let's say service A, B, C, and D), and the files are named as servicename_date the date is being picked up by a global variable TODAY. from datetime import date TODAY = date.today().isoformat() def func_A(): df.to_csv(os.path.join(os.getcwd(), "data","service_A" + "_" + TODAY + ".csv"), index=False) def func_B(): df.to_csv(os.path.join(os.getcwd(), "data","service_B" + "_" + TODAY + ".csv"), index=False) def func_C(): today = date.today().isoformat() df.to_csv(os.path.join(os.getcwd(), "data","service_C" + "_" + today + ".csv"), index=False) def func_D(): today = date.today().isoformat() df.to_csv(os.path.join(os.getcwd(), "data","service_D" + "_" + today + ".csv"), index=False) and this global variable is used in different functions in the same file. The problem is the value of TODAY is not always correct on the server. Sometimes it is correct I,e Today's date sometimes it picks up previous dates. The problem only occurs with the services that use Global variables I,e Service A and B, other services that use variables initialized inside their specific function don't face this issue I,e Service C and D. I have tried to replicate this issue on my local however wasn't able to replicate the issue.