Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Customize Validation Error Response in Django REST Framework?
I am developing a RESTful API using Django REST Framework (DRF) and I need to implement a common error handling mechanism for various validation errors that occur throughout the application, including but not limited to JWT authentication failures. when validation errors occur, DRF returns default error responses that may not be user-friendly or consistent across different endpoints. For example, a JWT token validation error produces a response that looks like this: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } I would like to standardize the error responses throughout my application to improve the user experience. Specifically, I want to create a common function that can return a structured error response for all validation errors in the following format: { "status": false, "responseCode": 0, "message": "Validation ", "data": {} } I tried by creating custom_exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: custom_response_data = { 'status': False, 'responseCode': 0, 'message': 'Validation error', 'data': {} } if isinstance(response.data, dict): errors = {} for field, detail in response.data.items(): if isinstance(detail, list): errors[field] = detail[0] if detail else 'Invalid … -
Django Progress bar for the backend to later integrate with frontend
I want to implement a progress bar since the request takes some time to give out the response when the api request is called i want the progress bar to start from 0 to 100 when the response loads views.py: class AllNodeReportView(View): def get(self, request, *args, **kwargs): start_date = request.GET.get('start') end_date = request.GET.get('end') format_type = request.GET.get('format', 'json') try: start_datetime = datetime.strptime(start_date, '%Y-%m-%d') end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1) except ValueError: return JsonResponse({"error": "Invalid date format. Use 'YYYY-MM-DD'."}, status=400) nodes = Node.objects.only('mac', 'location', 'unicast') response_data = [] node_unicasts = nodes.values_list('unicast', flat=True) loc_tag_relations = LocTagRelation.objects.filter( unicastAddr__in=node_unicasts, uuid__gte=start_datetime.timestamp(), uuid__lt=end_datetime.timestamp() ).values('unicastAddr', 'tagMac').annotate( intime=Min('uuid'), outtime=Max('uuid') ).order_by('tagMac', 'intime') loc_tag_relation_map = {} for relation in loc_tag_relations: if relation['unicastAddr'] not in loc_tag_relation_map: loc_tag_relation_map[relation['unicastAddr']] = [] loc_tag_relation_map[relation['unicastAddr']].append(relation) tag_macs = [relation['tagMac'] for relation in loc_tag_relations] tag_data = TagHistory.objects.filter( mac__in=tag_macs, lastUpdated__gte=start_datetime.timestamp(), lastUpdated__lt=end_datetime.timestamp() ).order_by('mac', 'lastUpdated') tag_data_map = {} for entry in tag_data: if entry.mac not in tag_data_map: tag_data_map[entry.mac] = [] tag_data_map[entry.mac].append(entry) for node in nodes: if node.unicast in loc_tag_relation_map: for relation in loc_tag_relation_map[node.unicast]: tag_mac = relation['tagMac'] if tag_mac in tag_data_map: tag_entries = tag_data_map[tag_mac] current_location = None entry_time = None entry_date = None # Capture the actual date of entry last_exit_time = None ongoing_entry = None for tag_entry in tag_entries: timestamp = datetime.fromtimestamp(float(tag_entry.lastUpdated)) … -
Apache Superset embed Dashboard with Guest Token in DJango
I have the following setup. I'm running a Django Application with Postgres and Apache Superset on the same network (through docker-compose). The setup works fine; I can access my data (Postgres) from both the Django application and Superset. I have created a dashboard in Superset with some data and want to embed it on a DJnago page. I have already enabled dashboard sharing and I can use an iFrame to do so. However, this works because I have an active tab in the same browser with Superset, which I'm logged in to. If I go to another browser, the embedded Superset dashboard will show the login page. This is logical. However, how can manage a guest login from my Django application to the Superset so my users won't receive Superset's login page? I've tried the following code, in which I'm using Superset Guest Token API, I managed to receive a token successfully but every time I'm going to access the following URL, I'm redirected to Superset's login page with a red message "Access Denied". http://localhost:8088/superset/dashboard/1/?access_token=TOKEN/?standalone=4 <- 1 is the dashboard ID import requests import json url = "http://127.0.0.1:8088/api/v1/security/login" headers = { 'Content-Type': 'application/json' } payload = json.dumps({ "username": "guest_username", "password": … -
Django: Custom BaseInlineFormSet. Extra forms
I'm trying to implement an inline for the Product model admin, so that in addition to the forms for existing ProductAttribute relationships, forms for all attributes of the category of the product currently being edited are also added by default. The problem is that while the forms are there, saving doesn't result in creating the ProductAttribute relationship in the database, and the cleaned_data of these forms is empty. My code: admin.py ... class ProductAttributeInline(admin.TabularInline): model = ProductAttribute formset = ProductAttributeInlineFormset extra = 0 fields = ('attribute', 'value') readonly_fields = ('attribute',) can_delete = False def has_add_permission(self, request, obj=None): return False @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ( 'name', 'category', 'price', 'sku', 'created_at', 'updated_at' ) search_fields = ('name', 'sku') list_filter = ('category',) inlines = (ProductAttributeInline,) ... forms.py from django import forms from .models import ProductAttribute class ProductAttributeInlineFormset(forms.models.BaseInlineFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance and self.instance.pk: category = self.instance.category if category: attributes = category.attributes.all() existing_attributes = set( self.queryset.values_list('attribute', flat=True) ) for attribute in attributes: if attribute.id not in existing_attributes: form_index = ( len(self.forms) + len(existing_attributes) - 1 ) form = self._construct_form( instance=ProductAttribute( product=self.instance, attribute=attribute, ), i=form_index ) self.forms.append(form) self.total_forms = len(self.forms) I noticed that 'attributes-TOTAL_FORMS' in form.data is equal to 1, but … -
Getting "Page not found (404) No Product matches the given query." error
I've started getting this error after deleting all my products from my database (I did this because it was dummy data just for testing). When I runserver and go to localhost I see this error The error states that this issue was raised in "home.views.index" despite the fact that the products are not called on the home page. I feel like my app is looking for the products and crashing when it cant find them. here is the code for my app urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('products/', include('products.urls')), path('checkout/', include('checkout.urls')), path('bag/', include('bag.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my product/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name='products'), path('<int:product_id>/', views.product_detail, name='product_detail'), ] Here is the code for products/views.py from django.shortcuts import render from .models import Product def all_products(request): products = Product.objects.all() context = { 'products': products, } return render(request, "products/products.html", context ) def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) context = { 'product': product, } return render(request, 'products/product_detail.html', context) Any help you can offer is greatly appreciated and sorry if I'm … -
raise ValueError( ValueError: Cannot assign "'TJFIDEL2401'": "Order.discount_code" must be a "DiscountCode" instance
I'm trying to implement a checkout page using Django framework. I have DiscountCode model linked to the Order model as "discount_code = models.ForeignKey(DiscountCode, on_delete=models.SET_NULL, null=True, blank=True)". When I proceed to click on the place order button on the checkout page, an error message occurs that is, "raise ValueError(ValueError: Cannot assign "''": "Order.discount_code" must be a "DiscountCode" instance." - I have spent already a couple of hours trying to resolve this issue. The problem occurs when the form.is_valid() is triggered Models: class DiscountCode(models.Model): code = models.CharField(max_length=50, unique=True) # Unique discount code discount_amount = models.DecimalField(max_digits=5, decimal_places=2) # e.g., 10.00 for a fixed amount discount discount_percent = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # e.g., 10.00% for percentage discount valid_from = models.DateTimeField() valid_until = models.DateTimeField() max_uses = models.PositiveIntegerField(default=1) # Number of times the discount can be used users = models.ManyToManyField(Account, blank=True) # Assign to specific users or leave empty for all users is_active = models.BooleanField(default=True) # Active status def __str__(self): return self.code def is_valid(self): now = timezone.now() return self.is_active and self.valid_from <= now <= self.valid_until and self.max_uses > 0 class Order(models.Model): STATUS_CHOICES = ( ('New', 'New'), ('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, … -
Djongo y Django REST Framework
Actualmente trabajo en el desarrollo de una red social y estoy usando Django para crear el back de la aplicación, pero la estoy conectando con Mongo usando el paquete de Djongo: https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/ para el tema de los likes quiero referenciar con otra colección pero tengo problemas al usar REST framework para crear las API's de este modelo El post ya lo puedo crear sin problema pero a la hora de enviar un like o un comentario no se incrustan o no se referencian he usado ArrayField y actualmente estoy usando ArrayReferenceField -
assert not sociallogin.is_existing error when logging in using google with allauth
So I have been trying to login using google to my website but when I try to login it gets an assert error. I tried to add a presocial adapter to override it but I still get it. My settings are good I think. Even if I take off the adapter I try to login and get the same error. This is the error. AssertionError at /accounts/google/login/callback/ No exception message supplied Request Method: GET Request URL: http://127.0.0.1:8000/accounts/google/login/callback/?state=F6gfXDcxDejwMv6J&code=4%2F0AQlEd8z3snMAR_7qPFDabY-q_zHedLdND40cQdWn7AH_Akjs3q7R8hx0cjOlB_K0LrQBJQ&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&hd=afreebird.org&prompt=none Django Version: 4.2.13 Exception Type: AssertionError Exception Location: C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 36, in pre_social_login Raised during: allauth.socialaccount.providers.oauth2.views.view Python Executable: C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\Scripts\python.exe Python Version: 3.8.10 Python Path: ['C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\python38.zip', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\DLLs', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\lib', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10', 'C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0\\env', 'C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0\\env\\lib\\site-packages'] Server time: Mon, 30 Sep 2024 09:11:33 -0500 Traceback Switch to copy-and-paste view C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 103, in view return self.dispatch(request, *args, **kwargs) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 152, in dispatch return complete_social_login(request, login) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\helpers.py, line 67, in complete_social_login return flows.login.complete_login(request, sociallogin) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 46, in complete_login pre_social_login(request, sociallogin) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 36, in pre_social_login assert not sociallogin.is_existing … Local vars … -
DRF Custom Generic View
I tried create a complete generic view with mixins to automate my app, and write less code. When i try make a 'POST' request i receive a 405 error = code(method_not_allowed) I cant find the error I also want to know if is this a good aproac to improve my code. `class BaseGenericView(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): serializer_class = YourModelSerializer permission_classes = [IsAuthenticated] # Adapte conforme necessário def get_queryset(self): return YourModel.objects.all() def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response({'message': 'Dados encontrados', 'data': serializer.data}, status=status.HTTP_200_OK) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) return Response({'message': 'Criado com sucesso!', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response({'message': 'Erro na validação', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response({'message': 'Dados encontrados', 'data': serializer.data}, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response({'message': 'Atualizado com sucesso!', 'data': serializer.data}, status=status.HTTP_200_OK) return Response({'message': 'Erro na validação', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response({'message': 'Removido com sucesso!'}, status=status.HTTP_200_OK)` -
How Can I Setup Celery in my Flask Project
So I've been working on a project for a couple months now and I've been trying to implement Celery into my flask project and it has not gone well. I thought maybe it's my computer or windows or something like, and all the responses I've seen are from a couple years ago and I don't think that they would still work because those were the ones I tried using. So thank you for any responses in advance. I tried using the celery config from the documentation and some chat gpt tutorials but they haven't been of help. And I'm running redis on the localhost -
Modifing ticket creating in django helpdesk
im tring to figure out how can i modify the field that are in the creating ticket area im modifed my admin.py code, i succsed to ad custom fields, but not in the desired way im just wondering if it possible to customize it in my own way without creating new model -
How to Attach Files from a web app to Local Outlook Client?
I'm working on a task where I need to implement a button in the frontend that opens the local Outlook client to compose an email. The user selects files (.dat or .csv) in the frontend, and upon clicking the button, Outlook should open with a default message and the selected files already attached, allowing the user to review the email before sending it. I understand that it might be easier to send the emails directly from the application, but that’s not the desired approach for this project. Can you please let me know if this is even possible, and if so, how I could implement it? I’ve tried using the Outlook API, but it didn’t meet my needs because it doesn’t open Outlook before sending the email, which is a key requirement for this project. Additionally, I cannot use links; the files must be attached directly as they are. -
creating a category system with MVT in django
I am working on a project and I created a system that has cars model and some user models . I want to create another model for user's skills and give the user model a relation to skill model . But I don't know how to do this optimize? for example , some users may can't fix the gearbox of one car But others Can , And some users may can fix some engine problems with some cars that others can't! So with this I need to have ralations to 'Car' model and also I have to save the skills with cars in the database . But there is more than 2000 cars in database! What do you think I can do? -
Logs are not transferred correctly
I have a logger set up to save logs to a file, but I'm encountering an issue with log rotation. Not all logs are being transferred during the rotation process, and the majority of logs are missing. What could be the problem? Why are many of my logs not being transferred during log rotation, and how can I resolve this? Here’s my logger configuration: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": {"correlation_id": {"()": "django_guid.log_filters.CorrelationId"}}, "formatters": { "standard": { "format": "[%(levelname)s] %(asctime)s [%(correlation_id)s] %(name)s: %(message)s", }, }, "handlers": { "file": { "level": "ERROR", "class": "logging.handlers.TimedRotatingFileHandler", "formatter": "standard", "filters": ["correlation_id"], "filename": "logging_view/logs/server-logs/server.log", "when": "midnight", "interval": 1, "backupCount": 30, "encoding": "utf-8", "delay": True, "utc": True, "atTime": None, "errors": None, }, "custom_mail_admins_handler": { "level": "ERROR", "class": "logging_view.logger.CustomAdminEmailHandler", "formatter": "standard", }, "js_file": { "level": "ERROR", "class": "logging.handlers.TimedRotatingFileHandler", "formatter": "standard", "filters": ["correlation_id"], "filename": "logging_view/logs/client-logs/client.log", "when": "midnight", "interval": 1, "backupCount": 30, "encoding": "utf-8", "delay": True, "utc": True, "atTime": None, "errors": None, }, }, "loggers": { "": { "handlers": ["file", "custom_mail_admins_handler"], "level": "ERROR", "propagate": False, }, "js_logger": { "handlers": ["js_file"], "level": "ERROR", "propagate": False, }, }, } settings.py # log_viewer LOGGING = LOGGING LOG_VIEWER_FILES_DIR = "logging_view/logs/server-logs" LOG_VIEWER_FILES_CLIENT_DIR = "logging_view/logs/client-logs" LOG_VIEWER_PAGE_LENGTH = 25 LOG_VIEWER_MAX_READ_LINES = 1000 LOG_VIEWER_FILE_LIST_MAX_ITEMS_PER_PAGE = … -
Unable to create superuser after creating CustomUser
After creating Custom user when i tried to create a superuser it gave error TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' Then after creating CustomUserManager its showing Expression of type "CustomUserManager" is incompatible with declared type "UserManager[Self@AbstractUser]" "CustomUserManager" is incompatible with "UserManager[Self@AbstractUser]" Expression of type "CustomUserManager" is incompatible with declared type "UserManager[Self@AbstractUser]" "CustomUserManager" is incompatible with "UserManager[Self@AbstractUser]" class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser, PermissionsMixin): username = None email = models.EmailField(unique=True) daily_reminders = models.IntegerField(default=0) start_at = models.TimeField(null=True, blank=True) end_at = models.TimeField(null=True, blank=True) notification_status = models.IntegerField(null=True, blank=True) device_type = models.CharField(choices=DIV_CHOICES, max_length=10, null=True, blank=True) device_token = models.CharField(max_length=255, null=True, blank=True) categories = models.JSONField(default=list, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email I BaseUserManager imported from django.contrib.auth.base_user import BaseUserManager but still showing error -
Django RestFramework make lookup_field accept special characters (".")
I am working on a DRF viewset which has a custom query (using annotate to group data), for this I want to implement list, retrive and delete functions based on a field called "batch" which contains a string with special characters like "-" and ".". I am able to make the viewset to list and retrive data but the data retrival fails when special characters (".") are present in the batch string. How can I setup viewset router to allow "." in the batch name? class BatchViewSet(viewsets.ModelViewSet): queryset = Product.objects.values('batch', 'customer', 'order_number').annotate( total_quantity=Sum('total_quantity'), ready_quantity=Sum('ready_quantity') ).filter(deleted_at__isnull=True).all() serializer_class = BatchSerializer lookup_field = 'batch' filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['batch', 'customer', 'order_number'] ordering_fields = ['batch', 'customer', 'order_number', 'total_quantity', 'ready_quantity'] ordering = ['batch'] def create(self, request, *args, **kwargs): raise MethodNotAllowed('POST') router.register(r'batches', BatchViewSet, basename="batches") These are the routes generated to get the batch details products/ ^batches/(?P<batch>[^/.]+)/$ [name='batches-detail'] products/ ^batches/(?P<batch>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='batches-detail'] which is not working on my batch TEATECH.01427964.11.08 but working on TEATECH. I tried making a custom router to get the batch number but it is also not working and I can't create a regex which can process the batch. Similarly I can't setup lookup_field_regex to catch the batch string. I can navigate my … -
Django Server URL not running [closed]
I am trying to run the django backend server using the intergrated terminal but the url is not running it is saying Not found tried to open it in the browser but it wasnt running still.I was expecting it to say welcome to the student task tracker -
django factory boy, image fields not created?
I tried to follow the standard recipe for image fields for django factory boy: class ConfigurationSingletonFactory(DjangoModelFactory): class Meta: model = Configuration django_get_or_create = ("id",) id = 1 custom_theme = ImageField(color="blue", width=200, height=200) class GeneralConfiguration(SingletonModel): custom_theme = PrivateMediaImageField("Custom background", upload_to="themes", blank=True) However whenever I try to test it: def test_config(self): conf = GeneralConfigurationSingletonFactory( custom_theme__name="image.png" ) print(conf.custom_theme.width) self.assertEqual(conf.custom_theme.width, 200) The following error pops up: ValueError: The 'custom_theme' attribute has no file associated with it. What am I misunderstanding, I thought I did exactly what https://factoryboy.readthedocs.io/en/stable/orms.html#factory.django.ImageField says? -
Removing success message after deleting was denied
Given the fact, that this is already some years old and no perfect answer was provided: How do I overwrite the delete_model/queryset functions in the admin, so the success message is not shown if the deletion was denied? class BookAdmin(admin.ModelAdmin): def delete_queryset(self, request, queryset): if not can_delete(): messages.error(request, "cannot delete ...") return super().delete_queryset(request, queryset) The logic works, but I get a success AND an error message which is confusing for the user. I know I can go the long way and implement a whole custom logic, but then I would face the issue of not seeing the "are you sure ..." page? I have the same problem I show here for delete_queryset() also with the delete_model(). -
Django Channels: WebSocket Consumer event handling method doesnt get trigerred
I'm working on a Django project using Django Channels with Redis as the channel layer. My setup allows WebSocket connections, and I am able to send and receive data from Redis without issues. However, when I try to send data to specific WebSocket channels using self.channel_layer.send, the send_online_users method in my AsyncWebsocketConsumer is not triggered. I’ve verified that my Redis server is working and communicating with the Django server. The channels and users are being stored correctly in Redis. The self.channel_layer.send() function runs without throwing errors, but the send_online_users method is never triggered (the print statements inside send_online_users do not show in the logs). Here is my Consumers.py code: from channels.generic.websocket import AsyncWebsocketConsumer import redis from django.conf import settings import redis.client from asgiref.sync import sync_to_async import json from channels.layers import get_channel_layer redis_client = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0) class UserActivityConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] if self.user.is_anonymous or not self.user.is_authenticated: await self.close() else: self.channel_name = f'user_activity_{self.user.username}' await sync_to_async(redis_client.sadd)('online_users', self.user.id) await sync_to_async(redis_client.sadd)("online_channels",self.channel_name) await self.accept() await self.send_to_all() async def disconnect(self,close_code): user_id = self.scope['user'].id await sync_to_async(redis_client.srem)("online_users", user_id) await sync_to_async(redis_client.srem)("online_channels", self.channel_name) await self.send_to_all() async def send_to_all(self): try: online_users = await sync_to_async(redis_client.smembers)("online_users") online_users = [int(user_id) for user_id in online_users] online_channels = await sync_to_async(redis_client.smembers)("online_channels") channel_layer = get_channel_layer() … -
Why in the Django + Tailwindcss project, styles are used in one file and not in another?
Here is the project's file system: enter image description here All classes work in this file: file: navbar.html <nav class="bg-white shadow-lg"> <div class="max-w-6xl max-auto px-4"> <div class="flex justifly-between"> <div class="space-x-7"> <div class="flex"> <a href="#" class="flex items-center px-2 py-4"> <img class="h-8 w-8" src="{% static 'myapp/images/logo.png' %}" alt="logo"> <span class="font-semibold text-xl"> Shop </span> </a> </div> <div class="items-center flex space-x-1"> <a href="#" class="py-4 px-2 font-semibold border-b-4 border-black ">Sell</a> <a href="#" class="py-4 px-2 font-semibold ">Sold</a> <a href="#" class="py-4 px-2 font-semibold ">Home</a> </div> </div> </div> </div> </nav> In this file tailwind classes for some reason do not work. Why is this happening??? file: contacts.html <div class=" p-10 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-3 xl:grid-cols-3 lg:grid-cols-3 gap-3 "> {% for item in items %} <a href="{% url 'site:detail' item.id %}"> <div class=" px-10 py-10 rounded overflow-hidden shadow-lg"> <img src="{{item.images.url}} " alt="img"> {{item.name}} {{item.price}} <br> </div> </a> {% endfor %} </div> Why does tailwind work in one part of the code and not in another? Even though both files are in the same folder. You need to make tailwind work in the contacts.html file. -
i'm trying to acess my django project admin page(local) and i keep getting this trackback
ModuleNotFoundError at /admin/login/ No module named 'users.backends' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 5.0.6 Exception Type: ModuleNotFoundError Exception Value: No module named 'users.backends' Exception Location: <frozen importlib._bootstrap>, line 1324, in _find_and_load_unlocked Raised during: django.contrib.admin.sites.login Python Executable: C:\Users\DELL\Documents\Jamor_tech\Jam_T\Jam_T\Scripts\python.exe Python Version: 3.12.3 Python Path: ['C:\\Users\\DELL\\Documents\\Jamor_tech\\Jam_T', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\DELL\\Documents\\Jamor_tech\\Jam_T\\Jam_T', 'C:\\Users\\DELL\\Documents\\Jamor_tech\\Jam_T\\Jam_T\\Lib\\site-packages'] Server time: Sun, 29 Sep 2024 18:06:12 +0000. i tried "http://127.0.0.1:8000/admin" on my browser expecting my admin page so that i can test my superuser details as well as generally testing the whole project, -
Django ` [ERROR] Worker (pid:7) was sent SIGKILL! Perhaps out of memory?` message when uploading large files
My dockerized Django app allows users to upload files(uploaded directly to my DigitalOcean Spaces). When testing it on my local device(and on my Heroku deployment) I can successfully upload small files without issue. However when uploading large files, e.g. 200+MB, I can get these error logs: [2024-09-29 19:00:51 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) web-1 | [2024-09-29 19:00:52 +0000] [1] [ERROR] Worker (pid:7) was sent SIGKILL! Perhaps out of memory? web-1 | [2024-09-29 19:00:52 +0000] [29] [INFO] Booting worker with pid: 29 The error occurs about 30 seconds after I've tried uploading so I suspect it's gunicorn causing the timeout after not getting a response. I'm not sure what to do to resolve it. other than increasing the timeout period which I've been told is not recommended. Here is my code handling file upload: views.py: @csrf_protect def transcribe_submit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size session_id = str(uuid.uuid4()) request.session['session_id'] = session_id try: transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() ... except Exception as e: # Log the error and respond with a server error status print(f"Error occurred: {str(e)}") return HttpResponse(status=500) ... else: return HttpResponse(status=500) else: form = … -
Why does my Celery task not start on Heroku?
I currently have a dockerized django app deployed on Heroku. I've recently added celery with redis. The app works fine on my device but when I try to deploy on Heroku everything works fine up until the Celery task should be started. However nothing happens and I don't get any error logs from Heroku. I use celery-redis and followed their setup instructions but my task still does not start when I deploy to Heroku. Here is my code: heroku.yml: setup: addons: plan: heroku-postgresql plan: heroku-redis build: docker: web: Dockerfile celery: Dockerfile release: image: web command: python manage.py collectstatic --noinput run: web: gunicorn mysite.wsgi celery: celery -A mysite worker --loglevel=info views.py: from celery.result import AsyncResult task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) task.py: from celery import Celery app = Celery('transcribe')# @app.task def transcribe_file_task(path, audio_language, output_file_type, dest_dir, session_id): print(str("TASK: "+session_id)) #rest of code return output_file celery.py: from future import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery("mysite") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I ensured that my CELERY_BROKER_URL and CELERY_RESULT_BACKEND are getting the correct REDIS_URL from environment variables by having it printing it's value before the task is to be started. So I know that's not … -
Google Login with Django and React
I am trying to integrate google login with Django and React (Vite) but I keep getting an error. I have set up the credential on google cloud console, I use @react-oauth/google for the login in the frontend. The login in the frontend goes through but not the backend. I don't know what I am doing wrong. Below is the error and the code. The frontend works well but the backend has issues settings.py AUTH_USER_MODEL = "base.User" # Application definition INSTALLED_APPS = [ "django.contrib.sites", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # App "base", # Third party apps "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "dj_rest_auth.registration", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", "corsheaders", # Debug toolbar for development "debug_toolbar", ] SITE_ID = 1 MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "allauth.account.middleware.AccountMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] AUTHENTICATION_BACKENDS = [ "base.auth_backends.CaseInsensitiveModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] # Social login settings CALLBACK_URL = config("CALLBACK_URL") LOGIN_REDIRECT_URL = "/api/auth/google/callback/" SOCIALACCOUNT_LOGIN_ON_GET = True ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_PROVIDERS = { "google": { "APP": { "client_id": config("CLIENT_ID"), "secret": config("CLIENT_SECRET"), "key": "", }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, "METHOD": "oauth2", # "REDIRECT_URI": "http://localhost:8000/api/auth/google/callback/", } } # Simple jwt config for dj-rest-auth SIMPLE_JWT = { "ROTATE_REFRESH_TOKENS": True, "ACCESS_TOKEN_LIFETIME": …