Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: NameError with instance of model with Generic Foreign Field in, created by post_save signal
I have 3 models that I am dealing with here: SurveyQuestion, Update, and Notification. I use a post_save signal to create an instance of the Notification model whenever an instance of SurveyQuestion or Update was created. The Notification model has a GenericForeignKey which goes to whichever model created it. Inside the Notification model I try to use the ForeignKey to set __str__ as the title field of the instance of the model that created it. Like so: class Notification(models.Model): source_object = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() source = GenericForeignKey("source_object", "object_id") #more stuff def __str__(self): return f'{self.source.title} notification' I am able to create instances of SurveyQuestion and Update from the admin panel, which is then (supposed to be) creating an instance of Notification. However, when I query instances of Notification in the shell: from hotline.models import Notification notifications = Notification.objects.all() for notification in notifications: print (f"Notification object: {notification}") NoneType --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 for notification in notifications: ----> 2 print (notification) File ~/ygzsey/hotline/models.py:27, in Notification.__str__(self) 26 def __str__(self): ---> 27 return f'{self.source.title} notification' AttributeError: 'NoneType' object has no attribute 'title' When I query instances of SurveyQuestion: from hotline.models import SurveyQuestion surveys = SurveyQuestion.objects.all() for survey in surveys: … -
How to allow the admin to change the uses's password in the Django admin panel?
I want to allow the admin to change any user's pasword, but th admin panel doesn't have that option anymore. I had to extend the abstract user class to add some fields to my users when they are created. I wanted to know what I can do to allow my admin users to change the user's passowrds. This is my User class: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): numero_de_empleado= models.CharField(max_length=100, unique=True, default="0", verbose_name="Puente") class Meta: permissions = [ ("view_retiro", "Ver retiro"), ("make_changes","Crear dotaciones y arqueos"), ("create_user","Crear un usuario"), ("view_all","Ver toda la información") ] And this is my admin.py from my user app: from django.contrib import admin from .models import User # Register your models here. admin.site.register(User) I am not an expert in django and i don't lnow why it's doing this, Thanks in advance. -
How to Disable Re-authentication in Django's allauth MFA's TOTP
I am trying to customize the reauthentication form of the mfa. I aslo customized the TOTP activate and deactivate form and it works, but now i am struggling to customize the reauthentication form with my defined route name in django. and is there any way to disable this reauth of the allauth mfa - 2fa settings/urls.py path('mfa/reauthenticate/', views.CustomReauthenticateView.as_view(), name='mfa_reauthenticate'), settings/views.py class CustomReauthenticateView(BaseReauthenticateView): template_name = "settings/mfa/reauthenticate.html" # Ensure the correct template is used def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['custom_message'] = 'This is a custom message for reauthentication.' return context def form_valid(self, form): response = super().form_valid(form) return response but it always rendering to localhost:8000/accounts/reauthenticate/?next=... and not my defined url. I also tried another way by customizing the allauth.account.decoders - reauthentication_required but not work Please someone help, that i want to redirect to my customize reauth form -
How to add dict to QuerySet
I have a result from the DB which I want to enriche with a row. A queryset is a dict right? So I created a new dict and wanted to merge those two. But it told me you cant merge a dict and QuerySet. How can this be done? -
Localhost route can't load static file
I am currently creating a dockerized web application. It is composed of the following elements : React for the frontend (with the routes managed by react-router-dom) Django for the backend PostgreSQL for the database managment Nginx for the reverse proxy I have created the reverse proxy for the back-end and front-end. I have created a route named /element/:id (id is an URL parameter) which would allowed me to see the informations of an object stored in a database. Unfortunately, when I try to load the page localhost/element/1, the page displayed nothing. In the web console, I have an error, telling me Uncaught SyntaxError: Unexpected token '<' for the file http://localhost/element/static/js/file.js. After inspection, he loads the index.html file. The home page works without a problem. Here is my nginx configuration file : server{ include /etc/nginx/mime.types; listen 80 default_server; error_log /var/log/nginx/app-error.log info; access_log /var/log/nginx/app.log main; location /admin/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://admin-backend/admin/; } location /api/v1/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://admin-backend/api/v1/; } location /static/ { alias /staticfiles/$1; } error_page 500 502 503 504 /50x.html; location = /50x.html { root … -
Django request.GET adds and extra quote to the data
When I pass my parameters via Django request.GET I get an extra comma in the dictionary that I do not need. Encoded data that I redirect to the endpoint: /turnalerts/api/v2/statuses?statuses=%5B%7B%27conversation%27%3A+%7B%27expiration_timestamp%27%3A+%271735510680%27%2C+%27id%27%3A+%2757f7d7d4d255f4c7987ac3557bf536e3%27%2C+%27origin%27%3A+%7B%27type%27%3A+%27service%27%7D%7D%2C+%27id%27%3A+%27wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA%3D%27%2C+%27pricing%27%3A+%7B%27billable%27%3A+True%2C+%27category%27%3A+%27service%27%2C+%27pricing_model%27%3A+%27CBP%27%7D%2C+%27recipient_id%27%3A+%272349039756628%27%2C+%27status%27%3A+%27sent%27%2C+%27timestamp%27%3A+%271735424268%27%7D%5D The request: <rest_framework.request.Request: GET '/turnalerts/api/v2/statuses?statuses=%5B%7B%27conversation%27%3A+%7B%27expiration_timestamp%27%3A+%271735510680%27%2C+%27id%27%3A+%2757f7d7d4d255f4c7987ac3557bf536e3%27%2C+%27origin%27%3A+%7B%27type%27%3A+%27service%27%7D%7D%2C+%27id%27%3A+%27wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA%3D%27%2C+%27pricing%27%3A+%7B%27billable%27%3A+True%2C+%27category%27%3A+%27service%27%2C+%27pricing_model%27%3A+%27CBP%27%7D%2C+%27recipient_id%27%3A+%272349039756628%27%2C+%27status%27%3A+%27sent%27%2C+%27timestamp%27%3A+%271735424268%27%7D%5D'> Data after request.GET: {'statuses': "[{'conversation': {'expiration_timestamp': '1735510680', 'id': '57f7d7d4d255f4c7987ac3557bf536e3', 'origin': {'type': 'service'}}, 'id': 'wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA=', 'pricing': {'billable': True, 'category': 'service', 'pricing_model': 'CBP'}, 'recipient_id': '2349039756628', 'status': 'sent', 'timestamp': '1735424268'}]"} The issue here is the double quote in the list as in "[{'conversation'... Expected result is: {'statuses': [{'conversation': {'expiration_timestamp': '1735510680', 'id': '57f7d7d4d255f4c7987ac3557bf536e3', 'origin': {'type': 'service'}}, 'id': 'wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA=', 'pricing': {'billable': True, 'category': 'service', 'pricing_model': 'CBP'}, 'recipient_id': '2349039756628', 'status': 'sent', 'timestamp': '1735424268'}]} Here's my view: class StatusesPayloadLayerView(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): payload = request.GET data = payload.dict() From the url encoding reference here, the encoded data looks fine as it doesn't appear to have a double quote before the list which would be "%22" notation so I can't quite understand where the double quote is coming from. -
How to store Django media folder in different EC2 instance
I have to host Django project on multiple server for load balancing. I have 4 EC2 server. I have used first for Nginx setup, 2nd and 3rd for Django application host and host 4th server to store all media folder. Now my problem is how can i save all media from server 2 & 3 to server 4? i tried some tutorial from google and couldn't get success. NOTE: i cant use s3 bucket to store media. -
handle situation where Django UpdateView does not have any data to update
I have created a forms wizard where a user will be able to create and update data for the models after which I will calculate the result by gathering all the data from all the forms and present them with an output. My user has the freedom to pick up where they left off and continue filling in data when they revisit. Each CreateView is linked to the next CreateView using the success_urls. So each UpdateView goes to the next UpdateView in the series of Views using the success_urls. So when a user updates data for a form and click next, they might arrive at a form which does not have any data to update because they have not filled in that data in thier previous visit. So get_object() returns an error as there is no data in the database for that form of that project. How to handle this situation ? class UserUseUpdateView(UpdateView): model = UserUse form_class = UserUseForm template_name = 'user_use.html' success_url = reverse_lazy('controller', kwargs={'step': 10, 'action': 'update'}) def get_object(self, queryset=None): try: project_instance = get_project(self.request) return UserUse.objects.get(project=project_instance) except Project.DoesNotExist: return redirect('step-9-create') # raise Http404(f'Project not found.') except UserUse.DoesNotExist: raise Http404(f'UserUse for project not found.') def form_valid(self, form): try: … -
Error when passing argument to custom tag in Django
Getting following error when using a custom tag that needs an argument. I am on Django version 4.2, does this still need a separate assignment to variable instead of using in if ? TemplateSyntaxError at /view/users/ "Unused 'PERM_CREATE_USER' at end of if expression" Inside view {% load my_tags %} {% if has_permission 'PERM_CREATE_USER' %} <a>Create User</a> {% endif %} #my_tags.py file @register.simple_tag(takes_context=True) def has_permission(context, perm): return True -
deploying django in vercel function timeout
i have a function called FetchAjaxs, which works fine in my local machine but not when i deploy view.py FetchAjaxs: #makes a api call to a different url which then returns a json to display in webpage i am calling that function from a ajaxs in my html index.html $.ajax({ url: "{% url 'FetchAjaxs' %}", // Django URL for the view type: "POST", data: $(this).serialize(), // Serialize form data headers: { "X-CSRFToken": "{{ csrf_token }}" // Add CSRF token for security }, dataType: 'json', my url.py looks like this path('fetch-ajax/', FetchAjaxs, name='FetchAjaxs'), and my vercel.json looks like this { "builds": [{ "src": "AppName/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9", "maxDuration": 300} } ], "routes": [ { "src": "/(.*)", "dest": "AppName/wsgi.py" } ] } when i run this in my local machine it works but when i run it in vercel it doesnt i figured it has to do with time out this is the error i get in my xhr {"error": {"code": "504", "message": "An error occurred with your deployment"}} i have increased the timeout in the settings in vercel however i still get the same error, any help would be appreciated , also please note i am … -
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')