Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding sync_to_async method in Django?
I have never worked with asyncio and/or asynchronous methods with django and am having a little difficulty understanding. I am trying to convert a synchronous helper function (create_email_record) into an asynchronous function inside of a form method. I will minimize some code for better understanding. my form method (begin_processing) has a good amount of logic inside. def create_email_record(submission): print("-----CREATE EMAIL RECORD-------") creation = EmailRecord.objects.create() class Form(forms.Form): comments = forms.TextArea() def begin_processing(): submission = Submission.objects.get(id=1) print("----------BEGIN ASYNC--------") create_email_notification = sync_to_async(create_email_record)(submission) asyncio.run(create_email_notification) print("----------END ASYNC----------") When I print this to my console I would think to expect: ("----------BEGIN ASYNC--------") ("----------END ASYNC----------") ("-----CREATE EMAIL RECORD-------") What I receive is: ("----------BEGIN ASYNC--------") ("-----CREATE EMAIL RECORD-------") ("----------END ASYNC----------") My Object gets created, and seems to work, but I don't believe that my converted sync_to_async function is being converted/called correctly. Maybe I am having some trouble understanding, but what I want to do is call an asynchronous function from a synchronous function/method. I have read a lot on other posts, and online resources, but none seem to fit what I am looking to do. I have not seen this done inside of a form method. -
Django - select onchange event not working anymore if using jquery-editable-select
I'm using a select item from a django model with a onchange event to trig a JS script : forms.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField(queryset=models_products.objects.values_list('product_denomination', flat=True),required=False, widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id,this.value)'}),empty_label=None ) It works very well but if I'm using jquery-editable-select to transform my select item in sort of a searchable datalist, the onchange event does not trig the JS script anymore ... Anybody knows a workaround for this ? template.html <script> function populate_selected_product(product_selectbox_id, product_selectbox_value){ $.ajaxSetup({ data: { product_num: product_selectbox_value, csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "GET", url: "../populate_selected_product/", success: function (data) { $("#div_update_row_bdc_product").html(data) $('#'+product_selectbox_id).parent().find('#id_id_bdc').val($("#id_product_denomination").val()) } }); } // and here is the code to transform the select item with jquery-editable-select $('#editable-select-2').editableSelect({effects: 'fade'}); </script> -
Python Django Web App Returning 404 Error for the GET request
I have created a basic web app using Python Django. Currently only one API is implemented i.e. User/GetUserName.aspx which return as simple "Hello" message. The web service is running on Django's inbuilt dev server. The API get hit successfully from web browser with URL 127.0.0.1:8001/User/GetUserName.aspx or 192.168.10.120:8001/User/GetUserName.aspx and from PostMan as well. Now there is one legacy device on the same network which hits this API. I have configured it with my machine IP & web service port. When that device hits the API, it get 404 error. I performed analysis of the issue and have following observations: When I hit the API from browser or PostMan, then Django prints API on console as GET User/GetUserName.aspx 200. When the device hits the API, then Django prints API on console as GET https://192.168.10.120:8001/User/GetUserName.aspx. I also implemented same API in Python Flask where it runs smoothly. On reading the documents of the device, I found that device always make https connection with the server. However, for few APIs it set some flag "verify=false" which disables certificate verification. For other APIs, it performs certificate verification. I tried setting up https server with self signed certificate but in that case my web app don't … -
I need help changing my veterinary website to a hardware sales website
I need help changing my veterinary website to a hardware sales website What I expected when I changed it was that it would work in the same way as the veterinary one, but it falls off and I don't know how to make it work. please help -
Django hosted on Render - Media Files/template vars
I've got a Django app that stores its static and media files in an AWS S3 bucket. Retrieval, usage and storage of these files work fine locally. The issue is, when accessing through the live site hosted on Render, if I try to upload and display an image the web app errors and times out. I don't usually host my projects, so this might be something totally silly. I'd assumed that since the files are stored in S3, it would still be accessible the same? Perhaps I need to make some adjustments in Render? In Render logs, I've gotten some errors where it doesn't like/can't find values in the template variables I am using to display media images. These errors don't occur locally, so I'm a bit confused. It's a super long traceback, so I've tried to snippet the important/repeating bits. I'm not sure if this is to do with Render, my S3 bucket u;loads or Django template :( See the images/videos below: live issue video: https://drive.google.com/file/d/1yriXvreGSWv_FiRKOwxKEg-5TDzfyejU/view?usp=sharing working locally video: https://drive.google.com/file/d/1UA-_kUaE6f1HPjqrUkqNIR1gSXmBNHz3/view?usp=sharing You can find my code here for further inspection: https://github.com/KianaR/Colour-Picker Any ideas? -
Unable to enter json in django admin
In my model I have the following field - data_fields = ArrayField(models.JSONField(null=True, blank=True), blank=True, null=True) In order to test this out, I entered the following in the data_field in the django admin - [{"key": "name", "label": "Name"}, {"key": "amount", "label": "Amount"}] But I get an error saying Item 1 in the array did not validate: Enter a valid JSON. Item 2 in the array did not validate: Enter a valid JSON. Item 3 in the array did not validate: Enter a valid JSON. Item 4 in the array did not validate: Enter a valid JSON. I only get this error if there are multiple key-value pairs in the JSON. If there is only one JSON element with one key-value pair, it works. If there are multiple elements in the array, or there are multiple key-value pairs in the JSON field, I get the error above. Why is this happening, and how do I fix it? -
Managing Inconsistent Model Attribute State on WebSocket Reconnect (Django Channels)
import json, jwt, uuid, random from channels.generic.websocket import AsyncWebsocketConsumer from django.conf import settings from asgiref.sync import sync_to_async from .models import GameRoom class BattleshipConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = self.scope['url_route']['kwargs']['room_id'] token = self.scope['url_route']['kwargs']['token'] try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) self.username = payload['username'] self.guest_id = payload['guest_id'] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Fetch the current state of the room self.room = await sync_to_async(GameRoom.objects.get)(room_name=self.room_group_name) initial_lobby_phase = self.room.lobby_phase # Log current state before making changes print(f"Initial room state for {self.username}: {initial_lobby_phase}") # Check if player1 or player2 is None and assign self.guest_id accordingly if self.room.player1 is None and self.room.player2 != self.guest_id: self.room.player1 = self.guest_id print(f'{self.username} has been added as player1') await sync_to_async(self.room.save)() elif self.room.player2 is None and self.room.player1 != self.guest_id: self.room.player2 = self.guest_id self.room.lobby_phase = 'setup' # Save the updated room and fetch it again to ensure consistency await sync_to_async(self.room.save)() print(f'{self.username} has been added as player2') self.room = await sync_to_async(GameRoom.objects.get)(room_name=self.room_group_name) #this works correctly, the lobby phase sent here is 'setup',as expected print("broadcasting phase change to setup") await self.channel_layer.group_send( self.room_group_name, { 'type': 'phase_change', 'phase': self.room.lobby_phase } ) # Fetch the latest state from the database after making changes self.room = await sync_to_async(GameRoom.objects.get)(room_name=self.room_group_name) lobby_phase = self.room.lobby_phase # Log updated state after changes print(f"Current room … -
Django sessionid cookies disappearing upon refresh
I am using a Django DRF backend with SessionAuthentication and a NextJS frontend. They are hosted on different ports. I am trying to use the django login function to automatically log the user in when creating an account. When I run this, the sessionid and csrf cookie gets saved into cookies but upon refresh they disappear. Before refresh: cookies in dev tools After refresh: cookies gone after refresh Relevant settings.py settings: CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CORS_ALLOWED_ORIGINS = [ "https://localhost:3000", ] CSRF_TRUSTED_ORIGINS = { "https://localhost:3000" } View used: class UserView(APIView): renderer_classes = [JSONRenderer] permission_classes = [ permissions.AllowAny ] decorators = [sensitive_variables('password'), ensure_csrf_cookie] @method_decorator(decorators) def post(self, request, format=None): """Create User""" serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() username = serializer.validated_data['username'] password = serializer.validated_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) return Response(data={'response': 'Successfully created account'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Request: const response = await fetch(`https://127.0.0.1:8000/user/`, { method: 'POST', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }); Both django server and NextJS are running on a dev SSL certificate so both have https. -
Error While Running dajngo project server through WSL
I am using Postgres as my db for this project. My project directory is in my windows system. Virtual environment was created in both windows and wsl (ubuntu) with all the dependencies. Postgres-16 and pgadmmin4 are installed in my windows. I was try to run the server from WSL2 (ubuntu) using python3 manage.py runserver. Getting error in Exception in thread django-main-thread:. connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? port - 5432 is used by postgres for connection and i was unable to connect to postgres in my windows from WSL. PSQL is installed in my WSL psql --version psql (PostgreSQL) 14.12 (Ubuntu 14.12-0ubuntu0.22.04.1) I tried to add the subnets in my pg_hba.conf # IPv4 local connections: host all all 172.18.64.0/20 scram-sha-256 host all all 127.0.0.1/32 scram-sha-256 host all all 0.0.0.0/0 scram-sha-256 Double checked the listen_addresses = '*' in postgresql.conf I tried to connect the WSL with postgers but get an error psql -h 'localhost' -U postgres -d encryptdata2 psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? -
403 error in django and enginx static files
I run the Django app with gunicorn and nginx on a virtual server. But it gives a 403 error for loading static files this is nginx config: enter image description here this is nginx sites-evailabel: enter image description here this is django project settings.py: enter image description here When I open the site, it gives this error in the browser console: enter image description here how can i fix this error? -
InvalidCursorName in django project
This is my models.py file: class TaskDetails(models.Model): TASK_CHOICES = [ ('ploughing', 'Ploughing'), ('sowing', 'Sowing'), ('watering', 'Watering'), ('harvesting', 'Harvesting'), ] task = models.CharField(max_length=50, choices=TASK_CHOICES) start_date = models.DateField() end_date = models.DateField() task_assigned_to = models.ForeignKey(WorkerDetails, on_delete=models.CASCADE) equipment_required = models.ManyToManyField(EquipmentDetails, related_name='tasks') def __str__(self): return self.task def clean(self): # Ensure all required equipment is available for equipment in self.equipment_required.all(): if equipment.status != 'available': raise ValidationError(f'Equipment {equipment.equipment} is not available.') def save(self, *args, **kwargs): self.clean() # Ensure clean method is called before saving super().save(*args, **kwargs) I am getting the following error: cursor "_django_curs_20672_sync_2" does not exist And i am using postgresql for database How to resolve this error? -
how to autogenerate context for APIView methods
I need to write my own APIView class which overrides drf's APIView and it will have autogenerated self.context which I can pass into serializer. For example class SomeView(APIView): def post(self, request): ser = SomeSerializer(data=request.data, context = self.context) ser.is_valid(raise_exception=True) return Response(ser.validated_data) -
Python Django : ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2427)
Traceback (most recent call last): File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\ADMİN\AppData\Roaming\Python\Python311\site-packages\django\core\servers\basehttp.py", line 173, in finish_response super().finish_response() File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 184, in finish_response self.write(data) File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 292, in write self._write(data) File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 466, in _write result = self.stdout.write(data) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\socketserver.py", line 834, in write self._sock.sendall(b) File "C:\Program Files\Python311\Lib\ssl.py", line 1274, in sendall v = self.send(byte_view[count:]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\ssl.py", line 1243, in send return self._sslobj.write(data) ^^^^^^^^^^^^^^^^^^^^^^^^ ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2427) Hello Friends The problem I have is that the SSL Error error in the python layer is caught and processed in the Django layer. Here is the issue: We are developing a project in Python Django environment. We are using openssl for runsslserver architecture. We have designed an advanced logging architecture for this situation. However, despite prioritizing middelware first, we could not catch and log this ssl error. Thank you in advance to anyone who has ideas or suggestions on this issue. class SSLErrorMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response # İstek başladığında ve bittiğinde sinyalleri bağla request_started.connect(self.log_request_start) request_finished.connect(self.log_request_finish) def __call__(self, request): # Request processing try: response = self.get_response(request) except ssl.SSLEOFError as e: error_details = traceback.format_exc() … -
Reverse for 'post_detail' with arguments ... not found
i'm having NoReverseMatch error message. already spend hours everything looks ok to me but couldn't figure it out. I would appreciate any help. thanks views.py from django.http import Http404 from django.shortcuts import get_object_or_404, render from blog.models import Post # Create your views here. def postList(request): posts = Post.objects.all() return render(request, 'blog/post/list.html',{'posts':posts}) def post_detail(request,year,month,day, post): post = get_object_or_404(Post, status = Post.Status.DRAFT, slug = post, publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post':post} ) urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.postList, name="post_list"), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name="post_detail"), ] models.py from django.urls import reverse from django.utils import timezone from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DR', 'Draft' PUBLISHED = 'PB','Published' user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() created = models.DateTimeField(auto_now_add=True) publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length= 2, choices=Status.choices, default=Status.DRAFT) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']), ] def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:post_detail", args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) list.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <a href="{{ post.get_absolute_url }}">{{post.title}}</a> <p>{{post.body|truncatewords:30|linebreaks}} <p>{{post.created}}</p> {% … -
the filtered product can't be added to cart in django
I am working on a Django-based web application that includes a product filtering feature. Products are filtered based on various criteria such as category, vendor, and price range. The filtered products are correctly displayed on a page. However, I am facing an issue where the filtered products cannot be added to the shopping cart, while the unfiltered products can be added without any problems. I am a beginner in Django development, and I have tried troubleshooting this issue but have not been successful. I suspect there may be an issue with the way the filtered products are handled or how the add-to-cart functionality is implemented for these products. Any help or guidance from experienced developers to resolve this problem would be greatly appreciated. Thank you in advance! This is the filtered product list html which I have replicated from the product-list.html async/product-list.html {% for p in products %} <div class="col-lg-3 col-md-4 col-sm-6 mix oranges fresh-meat"> <div class="featured__item"> <div class="featured__item__pic set-bg" style="cursor: pointer; background-image: url('{{ p.image.url }}');" onclick="redirectToProductDetail('{{ p.pid }}')"> {% if p.get_percentage %} <div class="discount-badge"> {{ p.get_percentage | floatformat:0 }}% </div> {% endif %} <ul class="featured__item__pic__hover"> <li><a href="#" class="no-redirect"><i class="fa fa-heart"></i></a></li> <li><a href="#" class="no-redirect"><i class="fa fa-retweet"></i></a></li> <li> <div class="add-cart"> <input … -
Django form.cleaned_data switches values between Form class choice fields
I am trying to filter a model's objects dynamically depending on what the user selects in a form. The form allows selecting from two dropdown lists. Selecting from either dropdown is optional. If the user does not select anything and clicks Submit, there will be an empty search results page. I believe I didn't do some things correctly. When I extract data from form.cleaned_data, when field_1 is only selected by the user, its value is assigned to field_2 and field_1 ends up being assigned the string "field_1". Same for when only field_2 is selected. Why is it switching the value assignment and assigning the string name of each to itself? Output self.kwargs = {"field_1": "field_1", "field_2": field_1_value} self.kwargs = {"field_1": field_2_value, "field_2": "field_2"} However, when the user selects a value from each dropdown list, the values are properly assigned. Here is my code: views.py class MyDataView(generic.ListView): template_name = "my_data/my_data.html" context_object_name = "my_data_list" def get_context_data(self, **kwargs): context = super(MyDataView, self).get_context_data(**kwargs) context["form"] = SearchForm return context def get_queryset(self): # Update and create data in the MyData model populate_my_data() return MyData.objects.all() class MyDataSearcher(FormView): form_class = SearchForm def form_valid(self, form): field_1 = form.cleaned_data.get("field_1 ", "") field_2 = form.cleaned_data.get("field_2 ", "") kwargs = {} if … -
I want to configure my django admin as subdomain on nginx
I've configured Nginx to proxy requests for admin.myproject.com to my Django application running on port 8000. However, when accessing admin.myproject.com, it redirects to admin.myproject.com/admin and displays a "502 Bad Gateway" error. Here's my Nginx configuration for admin.myproject.com: `server { listen 80; server_name admin.myproject.com; location / { proxy_pass http://127.0.0.1:8000/admin/; 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-Proto $scheme; proxy_redirect off; } }` I expect requests to admin.myproject.com to be proxied to http://127.0.0.1:8000/admin without displaying /admin in the browser. However, it currently adds /admin to the URL and results in a "502 Bad Gateway" error. The Django application is correctly configured to handle requests to /admin. -
django DATETIME_INPUT_FORMATS not working after upgrading to django 5.0
I just upgraded to django 5.0, and the DATETIME_INPUT_FORMATS is no longer working in the settings.py file. It is not accepting DOY (%j) dates like it did before. I have looked at similar questions on stackoverflow, and I see that USE_L10N is deprecated and USE_L18N should be disabled. Even with these updates, it seems to be ignoring the DATETIME_INPUT_FORMATS. Ideas? ''' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' DATETIME_FORMAT = 'Y-z H:i:s' USE_I18N = False USE_TZ = False DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M', '%Y-%m-%d', '%Y-%j %H:%M:%S.%f', '%Y-%j %H:%M:%S', '%Y-%j %H:%M', '%Y-%jT%H:%M:%S.%f', '%Y-%jT%H:%M:%S', '%Y-%jT%H:%M', ] ''' -
why can not post this data in rest_framework django? [closed]
I'm encountering an error when testing this code with Postman. Can you help me identify the cause? "AssertionError at /POST_Create_NewInvoiceBuy/ ("Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = '__all__' to the Create_NewInvoiceBuy_serializers serializer.",) " "I want to store invoice data in three tables that have a one-to-many relationship. However, I keep getting the following error: I've tried various approaches, but I'm still unable to identify the source of the issue. Can anyone provide guidance?" the code is : # -----------models products--------------------- class Tbl_Products (models.Model): Code_product=models.IntegerField(blank=False,null=False) Name_product=models.CharField(max_length=30, blank=True , null=True) Unit_counting=models.CharField(max_length=20)# واحد شمارش Amount=models.IntegerField(blank=True,null=False) Unit_price=models.IntegerField(blank=True , null=True) #-------------tables -------- class Tbl_ListAccounting (models.Model): Code_Account=models.IntegerField(default=100 , blank=False, null=False) Name_Account=models.CharField(max_length=50 , blank=True , null=True) Type_Account=models.CharField(max_length=50 , blank=True , null=True) class Tbl_purches (models.Model): Custom_id = models.CharField(max_length=10, primary_key=True) Code_Invoice_purches=models.IntegerField(default=100 , blank=False, null=False) Create_DateInvoice=models.DateField(auto_now_add=True,blank=False, null=False) Due_date=models.DateField(auto_now_add=True, blank=False, null=False) Name_customer=models.ForeignKey(Tbl_Customers,on_delete=models.PROTECT, blank=False, null=False) class Tbl_Detail_invoice_purches(models.Model): # Code_product=models.ForeignKey(Tbl_Products, on_delete =models.CASCADE) Name_product= models.CharField(max_length=20 , blank=False, null=True) Unit_Counting=models.CharField(max_length=100 ,blank=False ,null=True) Amount_product=models.DecimalField(max_digits=13,decimal_places=2 ) Unit_price=models.DecimalField(max_digits=13,decimal_places=2) Total_price=models.DecimalField(max_digits=13,decimal_places=2 ) ID_Tbl_detail=models.ForeignKey(Tbl_purches, on_delete=models.CASCADE,blank=False,null=False ) #--------------------------------serializer create newinvoice ----------- class Detail_NewInvoice_Serializers(serializers.ModelSerializer): class Meta : model=Tbl_Detail_invoice_purches fields= '__all__' class Create_NewInvoiceBuy_serializers (serializers.ModelSerializer): Detail_invoice_purches =Detail_NewInvoice_Serializers(read_only=True) class Meta : model=Tbl_purches fileds=['Custom_id','Code_Invoice_purches','Create_DateInvoice','Name_customer','Due_date','Detail_invoice_purches'] def create (self,validated_data) : … -
Manager isn't available; 'auth.User' has been swapped for 'main.User'
I had to recreate User model. I have added custom phone and zip_code fields to the model. But I am encountering Manager isn't available; 'auth.User' has been swapped for 'main.User' error. This is my settings.py: AUTH_USER_MODEL = 'main.User' This is my models.py: class User(AbstractUser): phone = models.IntegerField(blank=True, null=True) zip_code = models.IntegerField(blank=True, null=True) class Meta(AbstractUser.Meta): swappable = "AUTH_USER_MODEL" User = get_user_model() This is my views.py where I am encountering an error: @api_view(['POST']) @permission_classes([AllowAny]) def register(request): try: first_name = request.data.get('first_name') last_name = request.data.get('last_name') phone = request.data.get('phone') username = request.data.get('username') password = request.data.get('password') confirm_password = request.data.get('confirm_password') if password == confirm_password: User.objects.create_user( username=username, password=password, first_name=first_name, last_name=last_name, phone=phone, ) user = authenticate(username=username, password=password) login(request, user) return Response({'status':True}) else: return Response({'status':False}) except Exception as e: print(e) return Response({'status':False}) -
Use raw sql in django model default
I'm trying to set the default of a model column to the postgres function currval(pg_get_serial_sequence('public.user','id')) like recommended in a posgres related stackoverflow answer. I tried from django.contrib.auth.models import AbstractUser from django.db.models.expressions import Func from django.forms import IntegerField class CurrVal(Func): # noinspection SpellCheckingInspection function = "CURRVAL" output_field = IntegerField() class PgGetSerialSequence(Func): function = "pg_get_serial_sequence" class User(AbstractUser): substitute_user = models.ForeignKey( 'user.User', null=True, on_delete=models.SET_DEFAULT, db_default=CurrVal(PgGetSerialSequence('public.user', 'id')), ) However, it fails with user.User.substitute_user: (fields.E012) CurrVal(PgGetSerialSequence(F(public.user), F(id))) cannot be used in db_default. -
Can a Django management command tell when the server is running?
I have a management command that does some manipulation of the database so I don't want it running while the server is up. Is there a way to tell if the server is running from a management command -
Authenticating user on React frontend, against Django backend user groups using JWT
Having issues authenticating a user from React frontend, to Django backend using JWT Tokens. I have a Django instance with check_auth view in views.py: @csrf_exempt @login_required def check_auth(request): user = request.user response_data = { "message": "You are authenticated", "user": user.username, "authenticated": True, "groups": list(user.groups.values_list('name', flat=True)) } return JsonResponse(response_data) This is called on the Django side from http://127.0.0.1:8000/api/check-auth/ backend/apples/urls.py - path('check-auth/', check_auth, name='check_auth'), backend/urls.py - path("api/", include("apples.urls")), The frontend has a route on App.jsx for '/check-auth' which calls a CheckAuth.jsx component. <Route path="/check-auth" element={<CheckAuth />} /> CheckAuth.jsx import React, { useEffect, useState } from 'react'; import api from '../api'; const CheckAuth = () => { const [authStatus, setAuthStatus] = useState(null); const [error, setError] = useState(null); useEffect(() => { const fetchAuthStatus = async () => { try { const response = await api.get('/api/check-auth/'); setAuthStatus(response.data); } catch (err) { setError(err.message); } }; fetchAuthStatus(); }, []); if (!authStatus) return <div>Loading...</div>; // Example error handling if fields are missing or undefined const user = authStatus.user || 'Unknown'; const authenticated = authStatus.authenticated ? 'Yes' : 'No'; const groupsDisplay = authStatus.groups ? authStatus.groups.join(', ') : 'No groups'; return ( <div> <h1>Authentication Status</h1> <p>User: {user}</p> <p>Authenticated: {authenticated}</p> <p>Groups: {groupsDisplay}</p> </div> ); }; export default CheckAuth; When troubleshooting in … -
Django - Filtering on annotated count field returns unexpected values
I have a function that filters a Django queryset on the number of linked objects. Used inside a graphene-django project, it allows me to dynamically create filter fields for a bunch of objects without writing super repetitive code. The function works sometimes. When I pass mymodel_count__lt = 1, it only shows records with 0 linked mymodels. But when I pass mymodel_count__gte = 3, it is for some reason showing me records with only 2 linked mymodels. Am I missing something? Here's the function: def filter_on_count_field(qs, **kwargs): """ Filters a queryset based on fields that end with the word "count" and their corresponding values in kwargs. """ for filter_name, value in kwargs.items(): filter_field_name = filter_name.split("__")[0] foreign_field_name = "_".join(filter_field_name.split("_")[:-1]) + "s" if "__" not in filter_name or not filter_field_name.endswith("_count"): continue qs = qs.annotate( **{filter_field_name: models.Count(foreign_field_name)} ).filter(**{filter_name: value}) return qs -
How do I configure label-studio to use a different root URL?
I want to serve labelstudio under a different path in stead of the root URL. I am using an AWS Load Balancer that has several other services and want to use /labelstudio/ as the root for label studio. I tried to use something like setting env LABEL_STUDIO_BASE_URL=/labelstudio/ But that does not seem to work, since I am getting an error (Heidi’s down). I see 404 error in the log as well. Label studio is a DJANGO app, and I am using the docker version as part of a docker compose setup,. How do I configure labelstudio to use a different root URL?