Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to use COALESCE on related fields on django model
I have model structure as below. from django.db import models class Switch(models.Model): fqdn = models.CharField(unique=True) class Meta: db_table = 'Switch' class Colo(models.Model): name = models.CharField() class Meta: db_table = 'Colo' class Clstr(models.Model): colo = models.ForeignKey('Colo', db_column='colo', related_name='clstrs') name = models.CharField() class Meta: db_table = 'Clstr' class ESwtch(models.Model): switch = models.OneToOneField(Switch, db_column='switch', primary_key=True, related_name='e_swtch') clstr = models.ForeignKey('Clstr', db_column='Clstr', related_name="e_swtches") class Meta: db_table = 'ESwtch' class BSwtch(models.Model): switch = models.OneToOneField(Switch, db_column='switch', primary_key=True, related_name='b_swtch') clstr = models.ForeignKey('Clstr', db_column='clstr', related_name='b_swtches') class Meta: db_table = 'BSwtch' class VChas(models.Model): clstr = models.ForeignKey('Clstr', db_column='clstr', related_name='v_chas') vc_num = models.IntegerField() class Meta: db_table = 'VChas' class VSwtch(models.Model): switch = models.OneToOneField(Switch, db_column='switch', primary_key=True, related_name='v_swtch') v_chas = models.ForeignKey(VChas, db_column='v_chas', related_name='v_switches') role = models.CharField() class Meta: db_table = 'VSwtch' class CTrig(models.Model): switch = models.ForeignKey(Switch, db_column='switch', related_name='c_trig') config_trigger = models.CharField() class Meta: db_table = 'CTrig' I want to get the CTrig based on Colo.name. I ran raw query as below. SELECT `CTrig`.`switch`, `CTrig`.`config_trigger`, `Switch`.`fqdn` FROM `CTrig` LEFT OUTER JOIN `Switch` ON (`CTrig`.`switch` = `Switch`.`id`) LEFT OUTER JOIN `BSwtch` ON (`Switch`.`id` = `BSwtch`.`switch`) LEFT OUTER JOIN `ESwtch` ON (`Switch`.`id` = `ESwtch`.`switch`) LEFT OUTER JOIN `VSwtch` ON (`Switch`.`id` = `VSwtch`.`switch`) LEFT OUTER JOIN `VChas` ON (`VSwtch`.`v_chas` = `VChas`.`id`) LEFT OUTER JOIN `Cluster` ON (COALESCE(`BSwtch`.`clstr`, `VChas`.`clstr`, … -
Django and react webrtc remote isn't being added
I am making a chat app with django for backend and react for frontend. I use django channels. consumers.py def receive(self, text_data): text_data_json = json.loads(text_data) if 'message' in text_data_json: # Handle chat message message = text_data_json["message"] user = text_data_json["user"] print(message) # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat.message", "message": message, 'user': user} ) elif 'webrtc' in text_data_json: # Handle WebRTC signaling signal_data = text_data_json['webrtc'] user = text_data_json['user'] # Relay WebRTC signaling data to the group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type": "webrtc.signal", "webrtc": signal_data, "user": user } ) def chat_message(self, event): message = event["message"] user = event["user"] # Send message to WebSocket self.send(text_data=json.dumps({"message": message, 'user': user})) def webrtc_signal(self, event): signal_data = event["webrtc"] user = event["user"] # Send WebRTC signaling data to WebSocket self.send(text_data=json.dumps({ "webrtc": signal_data, "user": user })) **VideoChat.js ** const [socket, setSocket] = useState(null); const localAudioRef = useRef(null); const remoteAudioRef = useRef(null); const peerConnectionRef = useRef(null); const [localStream, setLocalStream] = useState(null); useEffect(() => { const initializeSocket = () => { const newSocket = new WebSocket(`ws://${window.location.host}/ws/chat/1/`); setSocket(newSocket); newSocket.onopen = () => { console.log('WebSocket connected'); }; newSocket.onmessage = async (event) => { const data = JSON.parse(event.data); console.log('Message received:', data); const messageType = data.webrtc?.type; if (messageType === 'offer') { await handleOffer(data.webrtc); } … -
reset_password function causing Internal Server Error
i work in django project and i have this function : def reset_password(request): if request.method == 'POST': email = request.POST['email'] try: # Check if the user exists user = RestPassword.objects.get(email=email) # Generate a unique reset token reset_token = str(uuid.uuid4()) user.reset_token = reset_token user.save() # Send the reset password email subject = 'Password Reset' message = f'Please click the following link to reset your password: {settings.SITE_URL}/authentication/reset/{reset_token}/' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [email] send_mail(subject, message, from_email, recipient_list) success_message = 'A password reset link has been sent to your email.' return render(request, "authentication/login.html", {'success_message': success_message}) except RestPassword.DoesNotExist: error_message = 'No account found with the provided email.' return render(request, "authentication/reset_password.html", {'error_message': error_message}) return render(request, "authentication/reset_password.html")``` and this the HTML fil <!DOCTYPE html> <html lang="en"> <head> <title>Password Reset</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <style> body { background-color: #f8f9fa; } .container { max-width: 400px; margin: 100px auto; padding: 30px; border: 1px solid #ced4da; border-radius: 5px; background-color: #fff; } .btn-reset { width: 100%; } </style> </head> <body> <div class="container"> <h2>Password Reset</h2> <form id="resetPasswordForm" action="{% url 'reset_password' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" name="email" required> </div> <button type="submit" class="btn btn-primary btn-reset" onclick="return verificate_email()">Reset Password</button> </form> </div> <script> function verificate_email() { const email = … -
CSRF token not generated in django backend
I have a web application that I built using a Vuejs for the frontend and django for the backend. When I was developing the application, I did not have issues in regards to csrf token generation. I have only begin encountering this issue 2 months after development. I am not sure why this issue is happening, or what was the behaviour for setting the csrf token when I was developing it. As far as I understand, an initial get request to the backend sets the csrf token in the browser, and can then be used by all other subsequent requests. But I do not see any csrf cookie in the applications tab. I have this method for setting the csrf cookie in the backend: def get_csrf_token(request): return JsonResponse({"detail": "CSRF cookie set"}) and this is where I call the method in my frontend: onMounted( async()=>{ const response = await fetch('http://127.0.0.1:8000/get-csrf-token', { method: 'GET', credentials: 'include' // This ensures cookies are sent with the request }); console.log if (response.ok) { console.log("CSRF token set successfully."); } else { console.log("Failed to set CSRF token."); } }) this is my setting.py file if its needed: """ Django settings for api project. Generated by 'django-admin startproject' … -
Add pyproject.toml to Django apps that are part of a source tree
I have a Django application which consists of two Django 'apps' - the term used in the Django world for (potentially) reusable packages. My whole application lives in one git repository. I would like to use one of the apps in another Python application. Specifically, I want to use the Django ORM and need to use the models definied in that app. Currently I put the parent directory of the app onto my sys.path and it works fine. But I would like to be able to pip install that app. My directory layout looks like this: website/ website/ <- main Django app settings.py urls.py ... crawls/ <- app I want to share views.py urls.py pyproject.toml <- this is new ... other_app/ <- application where I want to use `crawls` What I tried now is to place a pyproject.toml into crawls. However, both hatchling and flit seem to insist on an additional subdirectory. For example, the following results in ValueError: No file/folder found for module gen_crawler_crawls: [build-system] requires = ["flit_core >=3.2,<4"] build-backend = "flit_core.buildapi" [project] name = "gen-crawler-crawls" dependencies = [ "Django>=5.0.6", ] requires-python = ">=3.12" authors = [ {name = "Homer Simpson", email = "homer.simpson@example.com"}, ] dynamic = ["version", "description"] … -
Godaddy Professional Mail Connecting with django to send mails through django api
Im trying to send emails through my django api by connecting the Godady Professional email This is my settings.py config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'Password' EMAIL_PORT = 587 Postman api it shows email sent sucessfully but i didnt recieve any email utils.py from django.core.mail import EmailMessage from django.conf import settings from django.core.exceptions import ImproperlyConfigured class Util: @staticmethod def send_email(data): try: email = EmailMessage( subject=data['email_subject'], body=data['email_body'], to=[data['to_email']], from_email=settings.DEFAULT_FROM_EMAIL ) email.send(fail_silently=False) # logger.info(f"Email sent successfully to {data['to_email']}") except Exception as e: print(f"Failed to send email to : {e}") Views.py class SendEmailView(viewsets.ViewSet): def list(self, request): serialized_items = [] # Append serialized item data to the list serialized_items.append({ 'url': "", }) # Return the list of items as a JSON response # return Response(serialized_items) try: email_body = "Hello, This is a test email sent from our API." email_data = { 'email_body': email_body, 'to_email': "email@gmail.com", 'email_subject': 'Test Email from API' } # Send the email using the Util.send_email function Util.send_email(email_data) return Response({"message": "Email sent successfully!"}, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response({"error": "User with this email does not exist."}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) it shows the email sent sucessfully while i use the api through … -
How to annotate after group by and order_by in django?
I have a DB table which has a field "created_at". This is a auto_now_add=True field. This table is inserted data once everyday. What I want to do is filter data that corresponds to the last day of each month of each year. I have a query as follows: qs = ( self.model.objects().with_months() .with_years() .values('year', 'month') .annotate(last_day=Max('created_at')) .order_by('year', 'month') ) with_months() and with_years() methods are queryset methods that annotate year and month. What I want to do is to annotate other fields of this model in this queryset; however, since values() returns a list of dictionaries, I am not able to do that. I cannot add other fields inside values() as they won't be grouped. How can I achieve this? Best -
Remove products from the cart [closed]
The button to remove the product from the cart don`t work. when user add first product to the cart he can not remove that product from cart. But this problem is only for the product that was initially added to the cart I have no problem when I use the method GET, but when I use the method POST, this is the error my cart: Cart_Session_Id = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(Cart_Session_Id) if not cart: cart = self.session[Cart_Session_Id] = {} self.cart = cart def __iter__(self): cart = self.cart.copy() for item in cart.values(): product = Product.objects.get(id=int(item['id'])) item['product'] = product item['total'] = int(item['quantity']) * int(item['price']) item['unique_id'] = self.unique_id_generator(product.id, item['color'], item['size']) yield item def unique_id_generator(self, id, color, size): color_encoded = quote(str(color)) # کدگذاری رنگ size_encoded = quote(str(size)) # کدگذاری سایز result = f'{id}-{color_encoded}-{size_encoded}' return result def remove_cart(self): del self.session[Cart_Session_Id] self.save() def add(self, product, quantity, color, size): unique = self.unique_id_generator(product.id, color, size) if unique not in self.cart: self.cart[unique] = { 'quantity': int(quantity), 'price': str(product.Price), 'size': size, 'id': str(product.id), 'color': color } else: self.cart[unique]['quantity'] += int(quantity) self.save() def total_price(self): cart = self.cart.values() total_price = sum(int(item['price']) * int(item['quantity']) for item in cart) return total_price def delete(self, unique_id): if unique_id … -
Celery/Redis trigger send_email task twice per task
I have a Celery task to send an email, but since some time ago this email arrives 2 times with the same subject and body. I consider important to mention, for sending emails I use SendGrid. Attached is a fragment of the code used to run the task app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_transport_options = {'visibility_timeout': 43200} "send_sales_ga_rental":{ "task": "core.tasks.send_sales_ga_rental", 'schedule': crontab(0, hour=12, day_of_week='1') } app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Finally, I consider important to mention that this application runs on a Heroku server. [![enter image description here][1]][1] [1]: https://i.sstatic.net/K6cAoCGy.png -
how to send data returned from a function to client in django in real time without the client need to refresh
I am writing a program to retrieve data and display it in a Django template. I have a function called match_algo() that takes a long time to run. I want to initially show 'Loading...........' on the page, and once the function completes and returns the result, I want to display the retrieved content on the page. This is the view I tried first : def redirected_page(request): data = match_algo() context = { 'data' : json.dumps(data), 'test' : 'test' } return render(request , 'redirected_page.html' , context ) After some research, I found that WebSockets might help with this, but I'm still not sure if it's the solution I need. This is my consumer.py: class LoadingConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() # Send "loading..." message when the connection is established await self.send(text_data=json.dumps({ 'message': 'loading...', "status" : False })) data = match_algo() # Send "loading completed" message after processing is done await self.send(text_data=json.dumps({ 'message': "loaded", "status" : True, # "matches" : data })) # Close the connection after sending the final message await self.close() for testing purpose I commented this line data = match_algo() then added time.sleep(5). this actually works. But when i run with match_algo after few seconds the websockets disconnects. but … -
Djagno ORM diacritic and case insensitive query with matching at least 3 chars
I'd like to quiry the columns "title" and "content" of the following django model w postgresql integration in a diacritic- and casing-insensitive way. The query should return articles when the string "Ronald" is present in either of these columns, for every of the following user inputs: "ronálD", "Ron" and even "ronald reagan" for example. class Article(models.Model): date = models.DateField() content = models.TextField() title = models.CharField(max_length=300) category = models.CharField(max_length=50) length = models.IntegerField(default=4, null=True) thumbnail = models.TextField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) img_location = ArrayField(models.TextField(), blank=True, default=list, null=True) Thanks for the assistance! I came as far as returning articles casing and diacritic-insensitively w substring mathcing, but did not manage to return articles when only a set of letters are matching: eg: "Reagen" for the input "Ronald Reagan", or when querying multiple columns: from django.db.models import Func, Value, F, Q class Unaccent(Func): function = 'unaccent' class Lower(Func): function = 'lower' def normalize_field(field_name, is_array=False): if is_array: return Unaccent(Lower(F(field_name), function='unnest')) return Lower(Unaccent(F(field_name))) normalized_term = Lower(Unaccent(Value(input_term))) articles = list(Article.objects.annotate( normalized_content=normalize_field('content'), ).filter( Q(normalized_content__icontains=normalized_term) ).order_by("-id").values()[:20]) -
Switching execution engine from Celery to Kubernetes for my django app
In my current Django application i'm using celery to execute my tasks. After knowing capabilities of kubernetes i want to switch from celery to Django. I have implemented one architecture but it is incomplete I'm using docker to host BE and FE which is primarily outside k8s cluster, I have define a message broker like redis same as celery which keeps track of new task, after receiving task my kube.py will generate pod in k8s cluster and will execute that task. This was the overview of my current architecture Note: My app is monolithic (don't want to convert it to microservice for some reason) My concerns are straight forward. How can i pass tasks from my native application to k8s cluster how to keep track of tasks i.e success, failed if failed i want to re-execute it how to keep logs, i want to keep one pod running at all time i want to scaleup and scale down pods based on tasks available -
Encoding cookies in Django
It seems like Django does not encode my cookies properly I tried using: resp = request.get_signed_cookie('age', salt='code') However the output for number '20' would be '20:1sl4MF:RUUEG71gABt4-MeCj_lZiuklArWiCOLTKsxKfjLvlUg', meaning that the value is still visible, and the code just adds ':' and a bunch of characters. Same goes for other numbers and strings. Is it normal or am I doing something wrong? -
Send response from a function as real time in Django
I am writing a program to retrive data and display it in django template. I have a function match_algo() This takes a long time to run. What i want it is to load and display "Loading.........." in the page. After getting the response from the function . display this content in the page. This is the view I tried first : def redirected_page(request): data = match_algo() context = { 'data' : json.dumps(data), 'test' : 'test' } return render(request , 'redirected_page.html' , context ) after few research I found out that websockets can help with that. Still I am not sure if it is the one that i need. This is my consumer.py: class LoadingConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() # Send "loading..." message when the connection is established await self.send(text_data=json.dumps({ 'message': 'loading...', "status" : False })) data = match_algo() # Send "loading completed" message after processing is done await self.send(text_data=json.dumps({ 'message': "loaded", "status" : True, # "matches" : data })) # Close the connection after sending the final message await self.close() for testing purpose I commented this line data = match_algo() then added time.sleep(5). this actually works. But when i run with match_algo after few seconds the websockets disconnects. but … -
Apple social login using django rest auth
View Code: from dj_rest_auth.registration.views import SocialLoginView as DJSocialLoginView from allauth.socialaccount.providers.apple.client import AppleOAuth2Client from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter class CustomAppleLoginView(DJSocialLoginView): adapter_class = AppleOAuth2Adapter callback_url = f'{domain}/api/v1/user/accounts/apple/login/callback' client_class = AppleOAuth2Client def post(self, request, *args, **kwargs): try: return super().post(request, *args, **kwargs) except Exception as e: # Handle the OAuth2Error here error_message = str(e) return Response({"error": error_message}, status=status.HTTP_400_BAD_REQUEST) settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'django_filters', 'drf_yasg', 'django.contrib.gis', 'ckeditor', # local apps 'user', 'core', 'api', 'webapi', 'rental', 'marketplace', 'kora', # 3rd party 'dj_rest_auth', 'dj_rest_auth.registration', 'corsheaders', 'import_export', 'rangefilter', 'django_q', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.apple', 'fcm_django', 'celery', 'django_celery_beat', 'django_celery_results', ] SOCIALACCOUNT_PROVIDERS = { # IOS login credentials "apple": { "APP": { # Your service identifier. "client_id": os.environ.get('APPLE_CLIENT_ID'), # The Key ID (visible in the "View Key Details" page). "secret": os.environ.get('APPLE_SECRET'), # Member ID/App ID Prefix -- you can find it below your name # at the top right corner of the page, or it’s your App ID # Prefix in your App ID. "key": os.environ.get('APPLE_KEY'), # The certificate you downloaded when generating the key. "certificate_key": os.environ.get('APPLE_CERTIFICATE_KEY') } } } domain/api/v1/user/accounts/apple/login/?process=login error pic Also: On passing access_token, id_token to the above view I am getting: { "error": "Invalid id_token" } I … -
Django and apache2(ssl) production setup
I have three web applications currently running in production on Apache2 with SSL. I plan to containerize all of these applications (a Django app) using Docker while continuing to use Apache2 for serving it. Previously, Apache2 ran the Django application with WSGI. how to configure Apache2 (which will also be running in Docker) to work with this Dockerized Django application. I Tried running in manage.py runserver but it is only for development and configured docker ip in apache2 it is running but on production we cannot use that right. -
Model inheritance with existing DB models. Migration issue with “_prt” field
I’ve started to refactor some legacy code and having some difficulties with Model Multi-Table Inheritance on existing model. Let’s say I have a parent class Item: class Item(models.Model): brand = models.CharField(null=True, blank=True) model = models.CharField(null=True, blank=True) category = models.CharField(ItemCategory, null=True, blank=True) I have a child class Phone: class Phone(Item): serial_number = models.CharField() price = models.PositiveIntegerField() For a transition period I’ve allowed Item fields to be null=True and blank=True for a later manual population. However during a migration call I receive it is impossible to add a non-nullable field 'item_ptr' to phone without specifying a default. I understand a nature of this warning as django doesn’t know where to link item_ptr which hides under the hood and links to Item model with OneToOne relation. So I have a dummy Item instance I want to use for linking but how to point the Item id/pk on the console with choosen option 1 as it doesn’t recognize raw int as pk. Is it possible overall or the way is to manipulate with migrations manually? I don't see the option of dropping DB as it's already contains important data. -
Page not found error using django urlconfig
I'm having trouble mapping a page to another page in Django. The app name is Task, and the html files are inside templates\tasks file. the files exist, it's just Django can't find them for some reason! when I just write the path in the browser the pages appear, but when I put the path in the html it gives me page not found error. The settings of the main app settings.py INSTALLED_APPS = [ 'Home', 'Date', 'Task', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] The URLs of the created apps urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('Home/', include('Home.urls')), path('Date/', include('Date.urls')), path('Task/', include('Task.urls')) ] views.py from django.shortcuts import render taskslist = ["add", "edit", "delete"] # Create your views here. def index(request): return render(request, "tasks/index.html", { "taskslist": taskslist }) def add(request): return render(request, "tasks/add.html") ursl.py from django.urls import path from . import views app_name = "Task" urlpatterns = [ path("", views.index, name="index"), path("add", views.add, name="add") ] index.html {% extends "tasks/layout.html" %} {% block body%} <h1>Tasks</h1> <ul> {% for t in taskslist %} <li><a href="{ url '{{t}}'}">{{t}}</a></li> {% endfor %} </ul> <!-- This part didn't work --> <a href="{% url 'Task:add' %}">Add a task!</a> … -
How to connect Django to SQL Server docker in Mac OS?
I cannot connect Django to SQL Server in mac OS. How to connect Django to SQL Server docker in Mac OS ? Pip Install pip install mssql-django Setting: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'sa', 'HOST': 'localhost', 'PORT': 1433, 'USER': 'SA', 'PASSWORD': 'xxxxx', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } Run python3 manage.py runserver, it display error message as below. is there any way fix that error ? File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/contrib/auth/models.py", line 94, in <module> class Group(models.Model): File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 139, in __new__ new_class.add_to_class(obj_name, obj) File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 305, in add_to_class value.contribute_to_class(cls, name) File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/db/models/fields/related.py", line 1583, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/db/models/fields/related.py", line 1051, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/functional.py", line 149, in __mod__ return str(self) % rhs ^^^^^^^^^ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/functional.py", line 113, in __text_cast return func(*self.__args, **self.__kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/translation/__init__.py", line 75, in gettext return _trans.gettext(message) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/translation/trans_real.py", line 286, in gettext _default = _default or translation(settings.LANGUAGE_CODE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/translation/trans_real.py", line 199, in translation _translations[language] = DjangoTranslation(language) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/translation/trans_real.py", line 90, in __init__ self._init_translation_catalog() File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django/utils/translation/trans_real.py", line 131, in _init_translation_catalog translation = self._new_gnu_trans(localedir) … -
Vue.js Request Returns Empty Array in created Hook, But Works on Button Click
I'm trying to fetch new notifications when my component is created, but the response data is empty. However, when I trigger the same logic with a button click, the API returns the correct data. Here’s part of my Vue.js component: export default { data() { return { showNotification: true, notificationsQueue: [], currentNotification: null, }; }, created() { this.checkForNotifications(); }, methods: { checkForNotifications() { console.log('call hook'); this.$http .get('/notifications/') .then((response) => { console.log('This should succeed from hook', response); console.log('This should succeed from hook', response.data); this.notificationsQueue = response.data; this.showNextNotification(); }) .catch((error) => { console.error('Error captured:', error); }); }, // ... Here’s the output from the console.log() when the request is made in the created hook: This should succeed from hook [{…}]length: 0[[Prototype]]: Array(0) However, when I make the same request by clicking a button, the response data is correct: <button @click="getNotif">Get new notifi</button> getNotif() { this.$http.get('/notifications/').then(response => { console.log('This should succeed', response.data) }) .catch(error => { console.error('Error captured:', error) }) } Here’s the console.log() output from the button click: This should succeed [{…}]0: {id: 2, message: 'test first notification', created_at: '2024-08-29 07:48'}length: 1[[Prototype]]: Array(0) On the Django side, the API seems to work fine: class BusinessNotificationView(APIView): permission_classes = [IsAuthenticated] serializer_class = NotificationSerializer def … -
replace in old project exists Django User model to my User model
I have an old project in which there is a user model that was made by default. Next, we were asked to change the default user model. We have redefined the user model as: class Staff(AbstractUser): # ... new fields ... # no need in model user_permissions = None groups = None class Meta(AbstractUser.Meta): db_table = 'auth_user' swappable = "AUTH_USER_MODEL" Next, we added it to the settings.py file: # user model AUTH_USER_MODEL = 'test.Staff' # django authentication backend AUTHENTICATION_BACKENDS = [ # 'django.contrib.auth.backends.ModelBackend', # Django's default authentication backend 'test.backends.ModelBackend', # Custom authentication backend ] the necessary lines and we can't start the migration (just re-run for tests). ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'test.staff', but app 'test' doesn't provide model 'staff' Please tell me how to properly replace users in django. -
React How to get all free available plugins and tools for CKEditor, similar to Django
In my Django backend, I have all available CKEditor tools and plugins, but in React, I have very few plugins available. See the two screenshots django screenshot react screenshot Why am I not getting all the tools and plugins like I have in Django in my React app? my react config: import { CKEditor } from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; function CreateBlog() { upload() { return this.loader.file.then((file) => new Promise((resolve, reject) => { const formData = new FormData(); formData.append('upload', file); handleAxois(`${domain}/ckeditor/upload/`, 'post', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then((res) => { console.log(res.data); // Debugging: Check the response to ensure the full URL resolve({ default: `${domain}${res.data.url}` // Use the full URL returned from the server }); }) .catch((err) => { reject(err); }); }) ); } abort() {} } return ( <> <CKEditor editor={ClassicEditor} data={subtitle.description} onChange={(event, editor) => { const data = editor.getData(); handleSubtitleChange(index, subtitleIndex, 'description', data); }} config={{ extraPlugins: [CustomUploadAdapterPlugin], mediaEmbed: { previewsInData: true }, filebrowserUploadUrl: '/ckeditor/upload/', filebrowserImageUploadUrl: '/ckeditor/upload/', height: 500, }} /> </> } -
When does Djangos CONN_MAX_AGE get checked/used?
I recently had a "Too many connections" issues of my Django+Celery application with a Postgres DB on Heroku. Could dyno restarts be the issue? The idea is that the dyno restart drops the connection, but Postgres keeps them. Setting CONN_MAX_AGE seems to have solved the issue, but I'm uncertain. The question now is: How does CONN_MAX_AGE work? (1) Does Django actively check the age of the connection and close + restart it when it's too old or (2) Is CONN_MAX_AGE a parameter of the connection itself, so that postgres automatically closes the connection after that time? -
MySQL Authentication Plugin Issues on macOS
I’m working on a blog project using Python and Flask, and I’m using the MySQL database from XAMPP for user registration. The project worked perfectly on my Windows machine, but after switching to macOS, I’ve been encountering various issues with the registration process. I’ve managed to resolve most of the issues, but I’m still struggling with one particular error. I’ve been working on this for a week now and could use some help. Error Details: MySQLdb.OperationalError: (2059, "Authentication plugin 'mysql_native_password' cannot be loaded: dlopen(/opt/homebrew/Cellar/mysql/9.0.1/lib/plugin/mysql_native_password.so, 0x0002): tried: '/opt/homebrew/Cellar/mysql/9.0.1/lib/plugin/mysql_native_password.so' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/Cellar/mysql/9.0.1/lib/plugin/mysql_native_password.so' (no such file), '/opt/homebrew/Cellar/mysql/9.0.1/lib/plugin/mysql_native_password.so' (no such file)") enter image description here Context: • The application is running on macOS using XAMPP. • The database is configured correctly, and I can connect to it using other tools. • I’ve tried various solutions like asking chatgpt or searching on google Has anyone encountered this issue or have any suggestions on how to resolve it? Thanks in advance for your help! -
Should authentication_classes and permission_classes in Django's APIView Be Defined with Lists or Tuples?
I'm trying to understand the best practice for setting authentication_classes and permission_classes in Django's APIView. Specifically, I’ve seen both tuples and lists being used to define these attributes: Using a tuple: class Home(APIView): authentication_classes = (JWTAuthentication,) permission_classes = (permissions.IsAuthenticated,) Using a list: class Home(APIView): authentication_classes = [JWTAuthentication] permission_classes = [permissions.IsAuthenticated] Both approaches seem to work correctly, but I'm unsure if there are any specific reasons to prefer one over the other. Should I use a list or a tuple in this scenario? Are there any implications for using one over the other in terms of performance, readability, or following Django's best practices? I tried using both tuples and lists for authentication_classes and permission_classes in Django’s APIView. Both work fine, but I’m unsure which one is better or recommended. I was expecting to find clear guidance on this.