Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How "unpythonic" is it for an exception to be the expected outcome?
In Django I am validating a request which submits something that a user is only supposed to submit once, and in the "correct behavour sequence" an Exception is raised: try: my_row = models.MyModel.objects.get(id=instance_id, user=request.logged_in_user) return HttpResponseBadRequest("Already submitted") except models.MyModel.DoesNotExist: pass // continue Scale of 1-10, how much of a crime is this? -
Unclear error in Django rest framework swagger - guid instead of uuid
I have a Django rest framework project that is documented using drf-spectacular. In one of the endpoints I use rest_framework.serializer.UUIDField inside a serializer which inherit from rest_framework.serializer.serializer. But once I assign a wrong value in the swagger page the error is "Value must be a Guid". Why Guid and not UUID? Can I change it somehow? I don't understand from where it is coming from, did someone can assist with it? Search the "drf-spectacular" repo and didn't find it. -
Django Testing: Use main database as only one database available?
I am a university student, and I decided to use Django for my final year project. This means I am limited to using the University's MySQL database server. On the server, I am only allowed to have one database under my name and do not have permission to create any more of my own. I cannot use Django's test database functionality, as I only have one available and cannot create another. So, when I run ./manage.py test, I get the error... Found 3 test(s). Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'comp24394'@'%' to database 'test_comp24394'") How can I get around this? Is it possible for "test" tables to be created in the main database? Or, can I have the test database on another server from the main - if so, what would be the steps to implement this? Thank you for any help! -
Which method is best for designing custom error pages in Django?
For example, I've seen methods which design custom views with changes to URLconf, I've seen other methods that use handler404 = "mysite.views.my_custom_page_not_found_view" in URLconf with no changes to views. I've seen both of these methods explained in the docs. The easiest method I've seen is to simply create a templates/404.html without any other changes to the app. So which method is best for a production app? -
Select TruncYear start with specific year
I have Transactions stored in a Table, to select the last 3 years I wrote a simple Query in Django. I did this mid last year and it seemed to be fine. Now it would be nice if it would return me the year 2025 with 0, how could I achive that? Current Query: Transactions.objects .annotate(year=TruncYear('timestamp')) .values('year') .order_by('-year') .annotate(total=Sum('amount')) .values('year', 'total')[:3] This returns me the data for the years 2024,2023,2022 which is okay, but it would look more nice if it would return the data for 2025,2024,2023 Something like a change to get the current year and browse the table from there on. regardless of the table transactions having data for this year or not. -
How to Remove or Skip Object Serialization in Django Rest Framework Based on Conditions?
class CreateAttributeSerializer(BaseAttributeSerializer): class Meta(BaseAttributeSerializer.Meta): fields=['id', 'required'] + BaseAttributeSerializer.Meta.fields def to_representation(self, instance): attribute = super().to_representation(instance) current_display_order = int(instance.create_display_order) old_instance = self.context.get('old_instance', None) if old_instance: attributes = [] old_attribute = self.context['old_attribute'] if int(old_instance.create_display_order) == current_display_order: attributes = [old_attribute] attributes.append(attribute) else: attributes.append(attribute) return attributes self.context['old_instance'] = instance self.context['old_attribute'] = attribute I need to conditionally skip an object during serialization in Django Rest Framework. If certain conditions are met, the object should not be included in the response at all, neither as None nor an empty list. How can I get rid of null, [ null, [ { "id": 1, "required": false, "name": "price", "slug": "price" }, { "id": 6, "required": true, "name": "currency", "slug": "currency", "choices": [ "sum", "y.e" ] } ], [ { "id": 2, "required": false, "name": "Chevrolet model", "slug": "chevrolet_model", "choices": [ "Nexia", "Damas" ] } ], ] -
Adding custom actions button to wagtail snippets
I have been trying to look through the documentation on how to add custom action buttons for wagtail snippets. No luck so far. My wagtail version is 6.1.3 This is my snippet class. class CurrentDayForecastViewSet(SnippetViewSet): model = CurrentDayForecast menu_label = 'Current Day Forecast' list_display = ('forecast_title', 'forecast_date', 'town') search_fields = ('forecast_title', 'forecast_date', 'town') panels = [ FieldPanel('forecast_title'), MultiFieldPanel([ FieldPanel('forecast_date', classname='col6'), FieldPanel('town', classname='col6'), FieldPanel('min_temperature', classname='col6'), FieldPanel('max_temperature', classname='col6'), ], heading="Forecast Details", classname='col12'), MultiFieldPanel( [ FieldPanel('weather_condition_5AM', classname='col4'), FieldPanel('wind_direction_5AM', classname='col4'), FieldPanel('wind_speed_5AM', classname='col4'), ], heading='5AM', classname='collapsible col12' ), MultiFieldPanel( [ FieldPanel('weather_condition_12PM', classname='col4'), FieldPanel('wind_direction_12PM', classname='col4'), FieldPanel('wind_speed_12PM', classname='col4'), ], heading='12PM', classname='collapsible col12' ), MultiFieldPanel( [ FieldPanel('weather_condition_5PM', classname='col4'), FieldPanel('wind_direction_5PM', classname='col4'), FieldPanel('wind_speed_5PM', classname='col4'), ], heading='5PM', classname='collapsible col12' ), MultiFieldPanel( [ FieldPanel('weather_condition_9PM', classname='col4'), FieldPanel('wind_direction_9PM', classname='col4'), FieldPanel('wind_speed_9PM', classname='col4'), ], heading='9PM', classname='collapsible col12' ), ] By default the actions dropdown has "edit, copy, delete". I need to add a custom action button just for this snippet to run some custom logic. Appreciate if anyone can point me to right direction. -
When referencing imported Django model, I get 'local variable referenced before assignment' error
I am trying to import a model into my Django view and then query all objects, sort them, and iterate over them. I am not getting any error when importing the model, however, when trying to query the model with songs = song.objects.all()#.order_by('-release_date'), I am getting an error: UnboundLocalError at /hotline/dbm local variable 'song' referenced before assignment /home/path/to/site/views.py, line 82, in dbm songs = song.objects.all()#.order_by('-release_date') I do not understand what the problem is, as the variable song is clearly imported from my models.py file, and I am not getting any errors importing it - so why is Python not recognizing song as what I imported from my models.py file? My models.py file: class song(models.Model): name = models.TextField() file = models.FileField() release_date = models.DateTimeField(default=timezone.now) class Meta: verbose_name = 'Song' verbose_name_plural = f'{verbose_name}s' my views.py file: #list of modules removed to keep code clean from .models import * @csrf_exempt def dbm(request: HttpRequest) -> HttpResponse: songs = song.objects.all()#.order_by('-release_date') response = request.POST.get('Digits') if response == None: vr = VoiceResponse() vr.say("Please choose a song, and then press pound") vr.pause(length=1) with vr.gather(finish_on_key='#', timeout=6, numDigits="1") as gather: for song, num in songs: gather.pause(length=1) gather.say(f"For {song.name}, please press {num}") vr.redirect(reverse('dbm')) return HttpResponse(str(vr), content_type='text/xml') elif response != None: vr … -
"The request is missing a valid API key."
Am making a web application that one can read books through the site. I want to use google drive to store my PDF files for the textbooks, and in my application the Drive should serve the pdfs on my site when one want to read a book, I am using drive API, but I keep on getting the ("The request is missing a valid API key.") error, am using Django. when I check the logs for my local server it is working([31/Dec/2024 13:17:54] "GET /books/9/link/ HTTP/1.1" 200 96), but on the browser the pdf is not served what should I do? enter code here drive/utils.py from google.oauth2 import service_account from googleapiclient.discovery import build from payments.models import Payment from django.utils.timezone import now from library.models import Book Path to your service account file SERVICE_ACCOUNT_FILE = 'BookShelf/credentials/vernal-segment-445921-k9-8c59294dc1a2.json' SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] def create_service(client_secret_file, api_name, api_version, scopes): """ Create and return a Google API service instance. """ credentials = service_account.Credentials.from_service_account_file( client_secret_file, scopes=scopes ) return build(api_name, api_version, credentials=credentials) def initialize_drive_service(): """ Initialize and return the Google Drive service. """ return create_service(SERVICE_ACCOUNT_FILE, 'drive', 'v3', SCOPES) def generate_pdf_link(file_id): """ Generate a shareable link for a Google Drive file. :param file_id: The ID of the file on Google Drive … -
How to create GeneratedField with lookup from settings file?
While using Django 5.1, I'm trying to create a GeneratedField which should return True or False depending on which file has been uploaded. The model will accept both image- and video files. I want to do this in order to be able to filter on e.g. CampMedia.objects.filter(is_image=True). # models.py from django.conf import settings from django.db import models from django.db.models import Case, Q, When class CampMedia(models.Model): media = models.FileField(upload_to="camps") is_image = models.GeneratedField( expression=Case( When( condition=Q([Q(media__endswith=ext) for ext in settings.VALID_IMAGE_FILETYPES], Q.OR), then=True, ), default=False, ), output_field=models.BooleanField(), db_persist=True, ) # settings.py VALID_IMAGE_FILETYPES = ["png", "jpg", "jpeg", "gif", "webp"] This is what's generated in the migration file: # migrations/0007_image.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("camps", "0006_auto"), ] operations = [ migrations.AddField( model_name="campmedia", name="image", field=models.GeneratedField( db_persist=True, expression=models.Case( models.When( condition=models.Q( [ models.Q(("media__endswith", "png")), models.Q(("media__endswith", "jpg")), models.Q(("media__endswith", "jpeg")), models.Q(("media__endswith", "gif")), models.Q(("media__endswith", "webp")), ], "OR", ), then=True, ), default=False, ), output_field=models.BooleanField(), ), ), ] However, this generates this error when running python manage.py migrations: $ ./manage.py migrate camps Operations to perform: Apply all migrations: camps Running migrations: Applying camps.0007_image...Traceback (most recent call last): File "C:\xampp\htdocs\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Owner\.virtualenvs\p1pRKLs2\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Owner\.virtualenvs\p1pRKLs2\Lib\site-packages\django\core\management\__init__.py", line 436, in execute … -
Convert a uploaded audio chunk to be playable in server
I have a hour long audio streamed to backend with websockets. I need to start transcribing the audio and give back response in near realtime. atleast prevent users from waiting an hr long before checking transcriptions. I have broken down the problem to below steps Record audio stream split stream to 30 second chunks and upload convert audio chunks to seperate files and transcribe send back transcribed text The problem i face is when i try to play the second chunk of audio i get Invalid data found when processing input error. It is unplayable and dosent seem to have any audio information associated with it. Is it possible to add audio information into the second chunk, since first chunk is plays fine. Frontend async startRecording() { this.isRecording = true; // Start WebSocket connection this.websocket = new WebSocket("URL"); this.websocket.onopen = () => console.log("WebSocket connected"); this.websocket.onclose = () => console.log("WebSocket disconnected"); this.websocket.onstop = () => console.log("WebSocket onstop"); this.websocket.onerror = (error) => { console.error("WebSocket error:", error); this.stopRecording (); }; this.websocket.onmessage = (event) => { console.log(event.data) }; const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); this.mediaStream = stream this.mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm" }); // Send audio chunks in real-time this.mediaRecorder.ondataavailable … -
Django: Unable to Retrieve Phone Number from User's Latest CartOrder in Chatbot View
Problem: I'm building a chatbot using Django and I'm having trouble getting the phone number from my CartOrder model. I have a view called log_customer_query that's supposed to return the phone number of the user's latest order, but it's not working. Code: Here's my log_customer_query view: def log_customer_query(request): user = request.user query_text = request.POST.get('query_text', '') if not user.is_authenticated: return JsonResponse({'error': 'User must be authenticated to log a query.'}, status=401) try: # Fetch the latest order for the user latest_order = CartOrder.objects.filter(user=user).latest('order_date') # Create a new customer query new_customer = customer.objects.create( user=user, title=query_text[:100], # Limit to 100 characters pid=latest_order.pid, oid=latest_order.oid, full_name=latest_order.full_name, email=latest_order.email, mobile=latest_order.mobile, address=latest_order.address, landmark=latest_order.landmark, city=latest_order.city, state=latest_order.state, postalCode=latest_order.postalCode, images=latest_order.images, price=latest_order.price, old_price=latest_order.old_price, qty=latest_order.qty, color=latest_order.color, size=latest_order.size, order_date=latest_order.order_date, return_expire_date=latest_order.return_expire_date, product_status=latest_order.product_status, ) return JsonResponse({'success': 'Query logged successfully.'}) except CartOrder.DoesNotExist: # If the user doesn't have any orders, create a new customer query without order details new_customer = customer.objects.create( user=user, title=query_text[:100], # Limit to 100 characters ) return JsonResponse({'success': 'Query logged successfully.'}) And here's my CartOrder model: class CartOrder(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) sku = ShortUUIDField(length=10, max_length=100, prefix="sku", alphabet="1234567890") pid = ShortUUIDField(null=True, blank=True, default=None) oid = ShortUUIDField(length=10, max_length=100, prefix="oid", alphabet="1234567890") full_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True, blank=True) mobile = models.CharField(max_length=100, null=True, blank=True) address … -
Django's select_for_update(skip_locked=True) not compatible with spanning
I was attempting to lock the oldest item in a queryset and bashed my head over why it was not working. Every time I used this first code snippet the entire query set would be locked. with transaction.atomic(): locked_entry = Entry.objects.select_for_update(skip_locked=True).filter( event__date=distribution_date(), status='pending', entry_type__name='Premium' ).order_by('-created_at').first() print(locked_entry) sleep(4) However, upon passing the exact FK instances the lock began to correctly only lock the oldest instance. I'm sure it has something to do with how the SQL is called but was hoping for an explanation if there are any Django experts out there :) with transaction.atomic(): locked_entry = Entry.objects.select_for_update(skip_locked=True).filter( event=Event.objects.get(date=distribution_date()), status='pending', entry_type=EntryType.objects.get(name='Premium') ).order_by('-created_at').first() print(locked_entry) sleep(4) -
NGINX is not serving static files correctly
I'm having some trouble while trying to use nginx to serve my static files. What I'm trying to do is using nginx + gunicorn to deploy my django app, and I'm using docker compose to try to ease all needed conf. Here are my files: docker-compose.yml django_gunicorn: build: context: . volumes: - static:/app/static - media:/app/media env_file: - .env expose: - 8000 depends_on: db: condition: service_healthy networks: - app_network command: > gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 3 --threads 2 # Serviço Nginx nginx: build: context: ./nginx volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static:/app/static django - Dockerfile FROM python:3.12-slim WORKDIR /app # Instala dependências do sistema RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ default-libmysqlclient-dev \ && apt-get clean # Instala dependências Python COPY requirements.txt . RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # Copia os arquivos do projeto COPY . . # Permissões para o entrypoint RUN chmod +x entrypoint.sh EXPOSE 8000 ENTRYPOINT ["sh", "./entrypoint.sh"] entrypoint.sh #!/bin/sh until python -c "import MySQLdb; MySQLdb.connect(host='${DATABASE_HOST}', port=int('${DATABASE_PORT}'), user='${MYSQL_USER}', passwd='${MYSQL_PASSWORD}', db='${MYSQL_DATABASE}')"; do sleep 1 done echo "Banco de dados disponível!" python manage.py migrate --noinput python manage.py collectstatic --noinput exec gunicorn --workers 4 --bind 0.0.0.0:8000 core.wsgi:application /nginx/default.conf location /static/ { … -
AssertionError: Class ProductSerializer missing "Meta.model" attribute although I have Meta() class with model attirbute
I'm trying to simply post data using this django serializer but I'm constantly receiving the error Class ProductSerializer missing "Meta.model" attribute. Do you know if I'm missing something: class ProductSerializer(serializers.ModelSerializer): class Meta: model : Product fields : ('title','image','likes') -
problem in getting user email in django app with sicial auth
hello i have a django e commerce app that have google social auth when new users create an account we create a some % of dicount code for them i have UserIdentifier class that when users create new account i save either their phoen number or their email address to then when a new users create account i check if we have this users before or not to stop them from abusing the discount code i have this pipeline : from django.contrib.auth import get_user_model, login from django.shortcuts import redirect from .models import Profile,UserIdentifier import re User = get_user_model() def save_profile(backend, user, response, *args, **kwargs): if backend.name == 'google-oauth2': email = response.get('email') first_name = response.get('given_name') last_name = response.get('family_name') unique_identifier = email user_exists_before = UserIdentifier.objects.filter(identifier=unique_identifier).exists() if not user_exists_before: UserIdentifier.objects.create(identifier=unique_identifier) # Update user fields if email: user.email = email if user.phone_number and not re.match(r'^\d{11}$', user.phone_number): user.phone_number = None user.first_name = first_name user.last_name = last_name user.save() # Update or create profile profile, created = Profile.objects.get_or_create(user=user) profile.first_name = first_name profile.last_name = last_name profile.email = email profile.save() # Handle login and redirection request = kwargs.get('request') # Get the request object from kwargs if request: user.backend = 'social_core.backends.google.GoogleOAuth2' login(request, user) # Log the user in regardless of … -
Django model foreign key to whichever model calls it
I am getting back into Django after a few years, and am running into the following problem. I am making a system where there are 2 models; a survey, and an update. I want to make a notification model that would automatically have an object added when I add a survey object or update object, and the notification object would have a foreign key to the model object which caused it to be added. However I am running into a brick wall figuring out how I would do this, to have a model with a foreign key which can be to one of two models, which would be automatically set to the model object which creates it. Any help with this would be appreciated. I am trying to make a model that looks something like this (psuedocode): class notification(models.model): source = models.ForeignKey(to model that created it) #this is what I need help with start_date = models.DateTimeField(inherited from model that created it) end_date = models.DateTimeField(inherited from model that created it) Also, just to add some context to the question and in case I am looking at this from the wrong angle, I am wanting to do this because both surveys and … -
Use the same logging.Handler in different main files
Cheers! I am developping a Django Projekt and I want to display my backend loggings to the forntend. Thats why i created a central logging Handler that pushes logs into a buffer. Every 20 sec my frontend sends a request to flush the buffer and display the log events. Central Loging Class (log.py): import logging class BufferedLogHandler(logging.Handler): def __init__(self): super().__init__() self.log_buffer = [] # Lokaler Puffer für Logs def emit(self, record): log_entry = self.format(record) # Format den Log-Eintrag self.log_buffer.append(log_entry) def create_external_log(self, level=None, timestamp=None, message=None): asctime = timestamp msg = message record = logging.LogRecord( level=level, msg=msg, asctime=asctime, lineno=0, exc_info=None, args=None, name= None, pathname="frontend", ) self.emit(record=record) return BufferedLogHandler.create_empty_response() def flush_buffer(self): logs_to_send = self.log_buffer[:] print(f'logs_to_send:{logs_to_send}') print("---------------------") self.log_buffer = [] return logs_to_send @staticmethod def create_empty_response(): response = {'message':""} return response buffered_handler = BufferedLogHandler() def setup_logger(bufferedHandler): # Den Logger holen (Root-Logger oder benannten Logger) logger = logging.getLogger() # Du kannst auch den Root-Logger verwenden # Setze das Log-Level (z.B. DEBUG, INFO) logger.setLevel(logging.DEBUG) # Erstelle einen Handler (z.B. für Konsole oder Datei) file_handler = logging.FileHandler('myapp.log') # Für eine Log-Datei # Erstelle ein Format für die Log-Nachrichten formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s') # Setze das Format für beide Handler bufferedHandler.setFormatter(formatter) file_handler.setFormatter(formatter) … -
Django ManyToMany through model/table indexing
For ManyToMany relationships Django will automatically create a trough model/table. For example for: class Magazine(models.Model): pass class Article(models.Model): magazines = models.ManyToManyField('Magazine', related_name='articles') there will be a Article.through manager and model. The associated table will have two separate indices for each of the columns. Two questions: How do I create a new index on both columns? I could run a raw SQL query to do it, but I wonder if there is a way to do something similar to how index_together, which is easy to maintain and track. Is there a reason why Django doesn't automatically add an index to both columns? In my test, I manually created the index and saw Postgres hit it a lot and gain performance. -
Django Project, browser not making HTTP GET request for static files in development server
Hello I’m trying to load my static files to my templates but they’re not getting passed to my browser. When I look at the developer tools, I don’t see my Javascript and HTML files being passed to the browser. For some reason when I make a request for the page that I'm trying to include the static files on, I get 'GET /login/ HTTP/1.1'. The browser isn't even making a request for the static files. When I enter in the URL for the static files such as domain/static/styles.css or domain/static/index.js, I get sent to the file and no issue occurs. It’s just for some reason when I enter the page that the static files should be included on, browser doesn’t make a request for the static files. -
Python/Django Dynamic Form creation
I have an html page, which have dropdown field. I had load dropdown values from DB. Now selecting dropdown, the required fields related to value may be load, which has been described in 1 DB Table. so how is it possible? I have done like this... class VenDocMastForm(forms.ModelForm): doc_cat = forms.ChoiceField( label='Document Type*', choices=[(0, 'SELECT')] + [(dt.doc_type_id, dt.doc_type_desc) for dt in ven_doc_mast.objects.all()], widget=forms.Select(attrs={'class': 'col-sm-12 form-control-sm dropdown'}) ven_doc_path = forms.FileField( label='Upload Document File', required=False, # This can be set to True if file upload is mandatory widget=forms.ClearableFileInput(attrs={'class': 'form-control btn-outline-primary'}) ) class Meta: model = ven_doc_hdr # Model used for saving data fields = [ 'doc_id', 'ven_id', 'doc_reg_no', 'doc_reg_dt', 'doc_last_dt', 'doc_reg_cat', ] widgets = { 'doc_id': forms.NumberInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Document Type ID'}), 'ven_id': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Vendor ID'}), 'doc_reg_no': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Number'}), 'doc_reg_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}), 'doc_last_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}), 'doc_reg_cat': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Category'}), } def save(self, commit=True): # Handle form saving to ven_doc_hdr instance = super().save(commit=False) # Save ven_doc_dtl entry if file is uploaded if self.cleaned_data.get('ven_doc_path'): ven_doc_dtl_instance = ven_doc_dtl( doc_id=instance.doc_id, ven_doc_type_id=instance.doc_id, # Example: Mapping the document type ID from … -
Best Practice for Creating a Model's Record in `post_save` Signal While Maintaining Data Integrity in Django
I am working on a Django application where I need to automatically create a Setting record with default values whenever a new User is created. My current implementation uses the post_save signal of the User model to handle this logic. from django.db.models.signals import post_save from django.db import transaction from django.contrib.auth.models import User from myapp.models import Setting @receiver(post_save, sender=User) def create_default_setting(sender, instance, created, **kwargs): if created: transaction.on_commit(lambda: Setting.objects.create(user=instance)) I used transaction.on_commit to make sure that the creation of the Setting record happens only after the User creation transaction is committed, to avoid issues where the User instance might not yet exist in the database. However, this separates the Setting creation from the User creation transaction. If for any reason the Setting creation fails (e.g., validation errors, database issues), I end up with a User record without a corresponding Setting, which violates data integrity. On the other hand, if I don't use transaction.on_commit and create the Setting directly in the post_save signal, there is a risk of attempting to create a Setting record before the User instance is fully saved in the database, or creating a Setting even when the User creation fails due to an uncommitted or rolled-back transaction. This leaves … -
Proper approach to login user in Django channels websockets?
Developing a dashboard using Django channels, two different consumers are implemented, UserConsumer and RequestConsumer. In UserConsumer methods like login, logout and get_user are implemented. The user Authentication is being done using OTP code sent to user mobile so that a user_send_code method is in charge of sending SMS while the user_login method verifies the code sent by user. UserConsumer is implemented as follow: class UserConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def receive_json(self, content=None, **kwargs): action = content.get("action", "user.get_user") if action == "user.login": await self.user_login(content) elif action == "user.send_code": await self.user_send_code(content) elif action == "user.logout": await self.user_logout() else: await self.user_get_user() async def user_send_code(self, content): await self.send("we will send sms to: {}".format(content['mobile'])) if check_mobile_pattern(content["mobile"]): code = random.randint(1111, 9999) self.scope[VERIFY_CODE] = code self.scope[MOBILE] = content["mobile"] result = await send_sms(content["mobile"], code) if result: await self.send_json(send_code(200)) else: await self.send_json(send_code(400)) else: await self.send_json(send_code(SystemErrorCodes.InvalidMobilePattern)) async def user_get_user(self): if self.scope['user'].is_authenticated: await self.send_json({"id": self.scope['user'].id}) else: await self.send_json(send_code(SystemMessageCodes.AnonymousUserMessage)) async def user_login(self, content): verify_code = self.scope.get("verify_code") code = content.get("code") mobile = self.scope.get(MOBILE) if mobile is not None and verify_code is not None and code == verify_code: user = await load_user_by_mobile(mobile) del self.scope[VERIFY_CODE] # login the user to this session. await login(self.scope, user) # save the session (if the session backend … -
Django app failing to get deployed on Azure web service
I have a Django app that was running without issues till 2 days back on Azure. I then added some Azure OAI code using semantic-kernel and since then haven't been able to complete the deploy step of github actions workflow to deploy the app. To use semantic-kernel, I had to update to python 3.11 from python 3.8 on Azure. The deployment runs for about 40 mins and then errors out. From docker logs, I see the following issue:ModuleNotFoundError: No module named 'django' 2024-12-30T01:12:32.6106267Z Using packages from virtual environment antenv located at /home/site/wwwroot/antenv. 2024-12-30T01:12:32.6117557Z Updated PYTHONPATH to '/opt/startup/app_logs:/home/site/wwwroot/antenv/lib/python3.11/site-packages' 2024-12-30T01:12:35.1840122Z [2024-12-30 01:12:35 +0000] [84] [INFO] Starting gunicorn 23.0.0 2024-12-30T01:12:35.3134084Z [2024-12-30 01:12:35 +0000] [84] [INFO] Listening at: http://0.0.0.0:8000 (84) 2024-12-30T01:12:35.3205313Z [2024-12-30 01:12:35 +0000] [84] [INFO] Using worker: sync 2024-12-30T01:12:35.3321195Z [2024-12-30 01:12:35 +0000] [89] [INFO] Booting worker with pid: 89 2024-12-30T01:12:35.4238708Z [2024-12-30 01:12:35 +0000] [89] [ERROR] Exception in worker process 2024-12-30T01:12:35.4473148Z Traceback (most recent call last): 2024-12-30T01:12:35.4475461Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/arbiter.py", line 608, in spawn_worker 2024-12-30T01:12:35.4476786Z worker.init_process() 2024-12-30T01:12:35.4477986Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/workers/base.py", line 135, in init_process 2024-12-30T01:12:35.4479379Z self.load_wsgi() 2024-12-30T01:12:35.4480603Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/workers/base.py", line 147, in load_wsgi 2024-12-30T01:12:35.4481752Z self.wsgi = self.app.wsgi() 2024-12-30T01:12:35.4484237Z ^^^^^^^^^^^^^^^ 2024-12-30T01:12:35.4485531Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/app/base.py", line 66, in wsgi 2024-12-30T01:12:35.4486749Z self.callable = self.load() 2024-12-30T01:12:35.4487911Z ^^^^^^^^^^^ 2024-12-30T01:12:35.4489069Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line … -
How to Customize Indigo Theme and CSS Variables for Micro-Frontends in Open edX?
I’m working with Open edX, specifically using the Indigo theme and Micro-Frontends (MFEs). I want to customize the theme by setting CSS variables or tokens to maintain consistent branding across the platform. However, I’ve run into some challenges and am not sure how to proceed. My Setup: Open edX platform is hosted with the Indigo theme. I’m working with Tutor for managing the Open edX instance. The Micro-Frontends (React-based) are running on apps.local.edly.io. What I’ve Tried: I’ve looked into modifying the Indigo theme’s Sass variables (e.g., $primary-color) but couldn’t figure out the process to make these changes take effect. I don’t have React components inside the indigo-theme folder to directly manage styles or tokens for MFEs. I’ve come across mentions of the edx/brand package, but I’m unclear on how to use it to integrate the custom styles with MFEs. Questions: How can I customize the Indigo theme to define CSS variables or tokens? Is it possible to ensure these customizations are applied across both the core platform and the MFEs? If yes, what’s the best way to do this? Do I need to modify or replace the edx/brand package for this, and how do I integrate it properly with Tutor-managed …