Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i solve? django - ValueError: ModelForm has no model class specified
i don't understand, what is the wrong. could you please let me know? which one do i need adjust? ValueError at /blog/15/ ModelForm has no model class specified. error messege picture which one do i need adjust? i want to know solve it blog/forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Mata: model = Comment fields = ("content", ) # exclude = ("post", "author", "created_at", "modified_at", ) blog/models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.author}::{self.content}" def get_absolute_url(self): return f"{self.post.get_absolute_url()}#comment-{self.pk}" blog/urls.py from django.urls import path from . import views urlpatterns = [ # FBV 방식의 패턴 # path('', views.index), # path('<int:pk>/', views.single_post_page) # CBV 방식의 패턴 path("", views.PostList.as_view()), path("<int:pk>/", views.PostDetail.as_view()), path("category/<str:slug>/", views.category_page), path("tag/<str:slug>/", views.tag_page), path("<int:pk>/new_comment/", views.new_comment), path("create_post/", views.PostCreate.as_view()), path("update_post/<int:pk>/", views.PostUpdate.as_view()) ] blog/views.py def new_comment(request, pk): if request.user.is_authenticated: post = get_object_or_404(Post, pk=pk) if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect(comment.get_absolute_url()) else: return redirect(post.get_absolute_url()) else: raise PermissionDenied -
How to extend a User's profile to save data in Django
I'm new to Django and I'm attempting to build a website where a user can view a DB of books and related authors and add any book to their 'favourites'. I've been searching lots and I can't find a satisfactory way of doing this - or indeed of saving any user data other than customising fields when you create a user. My current idea is to extend the UserModel to add an extra field which links their favourite book to the user. Tips on UserModel found here I can now see the UserProfile with some favourites by logging in to the Admin account, but I cannot link the View class/function with my bookfavs.html for the User to see their favourited books. The bookfavs.html states the username but not favourites. readable_project app_name = bookshelf #Models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Book, related_name='favourites') class Author(models.Model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) dob = models.DateField() bio = models.CharField(max_length=300) def __str__(self): return self.first_name + " " + self.last_name def get_absolute_url(self): return reverse('authorlist') class Book(models.Model): id = models.AutoField(primary_key=True) users = models.ManyToManyField(User) title = models.CharField(max_length=50) num_page = models.IntegerField() date_pub = models.DateField() tags = models.CharField(max_length=200) blurb = models.CharField(max_length=300) def get_absolute_url(self): return reverse('')` #views.py #Add favourite button...? def favorite(request, … -
invalid_client when trying to authenticate with client_id and client_secret using django oauth toolkit and rest framework
I’m running a Django service that exposes endpoints via Django REST Framework. I want to secure these endpoints using Django OAuth Toolkit for authentication. When I create an application from the admin panel, I use the following settings: As shown in the screenshot, I disable client_secret hashing. With this configuration, everything works perfectly, and I can obtain an access token without any issues. * Preparing request to http://localhost:8000/o/token/ * Current time is 2024-12-19T10:47:03.573Z * Enable automatic URL encoding * Using default HTTP version * Enable timeout of 30000ms * Enable SSL validation * Found bundle for host localhost: 0x159f21ed0 [serially] * Can not multiplex, even if we wanted to! * Re-using existing connection! (#106) with host localhost * Connected to localhost (127.0.0.1) port 8000 (#106) > POST /o/token/ HTTP/1.1 > Host: localhost:8000 > User-Agent: insomnia/0.2.2 > Content-Type: application/x-www-form-urlencoded > Accept: application/x-www-form-urlencoded, application/json > Authorization: Basic MkVDdzAwWkN1cm1CRFc4TEFrSmpjSGt1bnh1OW9WZlRpY09DaGU5bDpKVTl6SURzd0Zob09JMzJhRjhUMVI2WnhYZDVVTU84TWwwbHdiZldNWFNxcHVuTGdsaXBLT2xLTFBNMTBublV1TGp3WGFWOVBPR2ZxYUpURzF5Smx2VGRMWHVPRzN0SVg4bE9tQ1N6U09lbTV4Z2ExaWZrNWRUdjVOYWdFV2djQQ== > Content-Length: 29 | grant_type=client_credentials * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Thu, 19 Dec 2024 10:47:03 GMT < Server: WSGIServer/0.2 CPython/3.12.8 < Content-Type: application/json < Cache-Control: no-store < Pragma: no-cache < djdt-store-id: b377d48fbdae4db989aabb760af12619 < Server-Timing: TimerPanel_utime;dur=28.13699999999919;desc="User CPU time", TimerPanel_stime;dur=2.7200000000000557;desc="System CPU time", TimerPanel_total;dur=30.856999999999246;desc="Total CPU time", TimerPanel_total_time;dur=56.63733399705961;desc="Elapsed time", SQLPanel_sql_time;dur=5.738208987168036;desc="SQL … -
Reverse ForeignKey orm django
hi i am new to django orm , can some body help me i have data tables something like that class userprofile(models.model): foreignkey User related_name='fU' class A(models.model) foreignkey userprofile related_name='fa' Class b(models.model): forign key A related_name="fb" class C (models.model): foreignkey B related_name="fC" so what i am trying to achieve is , with User id i want to get information from all tables from top to bottom hierarchy . -
Why does updating to psycopg 3.x cause database timeouts?
I have a Django 5.x app. I've been using psycopg2, and I'm now trying to update to psycopg 3. This is pretty simple: I uninstalled everything to do with psycopg2 and installed psycopg[binary]. However, when I run my test suite now (in parallel), I am suddenly getting connection timeout expired and canceling statement due to statement timeout errors that I weren't getting before! My database configuration is pretty straightforward: STATEMENT_TIMEOUT = get_from_env( "POSTGRES_STATEMENT_TIMEOUT", default=30000, type_cast=int ) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": get_from_env("DB_NAME", "my-db"), "USER": get_from_env("DB_USERNAME", "my-db-user"), "PASSWORD": get_from_env("DB_PASSWORD", DEFAULT_DB_PASSWORD), "HOST": get_from_env("DB_HOSTNAME", "localhost"), "PORT": get_from_env("DB_PORT", "5432"), "OPTIONS": { "connect_timeout": 3, "options": f"-c statement_timeout={STATEMENT_TIMEOUT}ms", }, # Keep database connections open for 1 minute "CONN_MAX_AGE": 60, # But ensure that persistent connections are healthy before using them "CONN_HEALTH_CHECKS": True, }, } Is this configuration no longer valid with psycopg 3? Or are there some other changes in 3.x that could mean more timeouts? This is all using synchronous Python, no async or anything. -
RuntimeError: Model class modules.firebase-push-notifications.models.Notification doesn't declare an explicit app_label
error RuntimeError: Model class modules.firebase-push-notifications.models.Notification doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. for some reason i do not get this error when i try run manage.py runserver but if i use vscode debugger, this error shows up the debugger was working fine, this error popped up randomly setting.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites" ] LOCAL_APPS = [ 'home', 'users.apps.UsersConfig', 'chat.apps.ChatConfig', 'admin_panel.apps.AdminPanelConfig', ] -
Retrieve exect previous or next occurrence of a recurring event from Google Calendar
I have a recurring event in Google Calendar, and I need to fetch either the previous and next occurrence of this event, based on a given event ID. Specifically, I want to retrieve the event details for the exact occurrence before or after the specified recurring event ID. How can I use the Google Calendar API to get the exact details for the previous or next recurrence of a given event, considering its recurrence rule (e.g., daily, weekly, etc.)? I attempted to use the Google Calendar API to fetch the details of the previous or next occurrence of a recurring event, using the event ID and its recurrence rule. I expected to retrieve the exact details for the previous or next occurrence based on the recurrence pattern (e.g., daily, weekly, etc.). However, I wasn't able to correctly retrieve the previous or next event occurrence. Instead, the API only returned the original event or no matching results at all. this is my code def fetch_event_by_id(service, event_id,future,past): if future or past: pass # here i want to pass ,exect future or past one event detail, without giving timeMin and timeMax,here future and past is the number of future and past event, else: … -
Django + ODBC Driver 17 for SQL Server: Raw query can't process list or tuple arguments
Code I wrote a function that wraps Django's standard processing for raw SQL queries. def run_mssql_query(query, connection="prod", args=None): """Method will run query on MSSQL database Args: query (str): MSSQL Query connection (str): Which connection to use. Defaults to "prod". Returns: dict: Results of query """ if connection == "omron": results = {} conn = get_oracle_connection() with conn.cursor() as cursor: try: if args == None: args = dict() cursor.execute(query, args) cursor.rowfactory = lambda *args: dict(zip([d[0] for d in cursor.description], args)) results = cursor.fetchall() except: results = {} return results with connections[connection].cursor() as cursor: if args == None: args = list() cursor.execute(query, args) # Replace with your actual query try: columns = [col[0] for col in cursor.description] results = [dict(zip(columns, row)) for row in cursor.fetchall()] except: results = {} return results Execution looks something like this: data = run_mssql_query(f"""SELECT * FROM EVENTS.dbo.MES_BARCODES WHERE BARCODE = %s""", args=["123"]) Problem When i'm using string, int, etc..., it's working like a charm, but when i'm tring to pass list to the params of my params, like this (for example): barcodes = ["123", "321"] data = run_mssql_query(f"""SELECT * FROM EVENTS.dbo.MES_BARCODES WHERE BARCODE IN %s""", args=[list(barcodes)]) It's giving me this error: ('42000', '[42000] [Microsoft][ODBC Driver 17 for … -
Using different table for authentication and simple jwt - Django rest framework
Im a bit new to Django REST and Django as a whole, how do you use a different table for auth since my api is looking for auth_user , it keeps saying "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'auth_user'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)" when I try to add my jwt token bearer to an [isAuthenticated] apiview. by the way my django uses mssql I tried adding AUTH_USER_MODEL to my model but it says the same error -
Override the accounts/login/ in Django
So I'm using django.contrib.auth.urls and I would prefer to continue that. But I want the accounts/login url to be replaced with users/c-login or whatever. I would really like to understand why this is not working: my urls.py (project): from core import views urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("django.contrib.auth.urls")), path("", include("core.urls")), path("user/", include("user.urls")), path("accounts/login", views.atest, name="login"), path("accounts/login/", views.atest, name="login"), ] The idea here was that path("accounts/login/", views.atest, name="login"), should "replace" the django auth urls. views.py user app: def atest(request): return redirect("c-login") And the custom login views.py user app: def custom_login(request): template_name = "registration/login.html" Any help appreciated. Thanks -
Sending serial port-data via websocket in Django framework
I need to visualize data on Django-based webserver; which data is captured on serial port, like a stream. I use python **serial ** package to listen on the serial port, and I store these data in DB. I also have my Django application using async websocket with the purpose to update immediately the client side when new data is captured. Although I cannot connect these two application together. I was believing that ChannelLayer might be the key, although there are no more different instances of the application; only one. So it might be a wrong approach. I also thinking on Worker or Background Task, however I don't see how/where should I implement the serial-port listener, which is basically an infinite loop: while True: data = serial_connection.read_until() if data == b"EOF": break print(data) Using https://channels.readthedocs.io/en/stable/topics/worker.html as reference, I think, it should be inside the consumer: # Inside a consumer self.channel_layer.send( "serialport-listener", { "type": "listener", "id": 123456789, }, ) What is the concept and the architecture that might resolve this problem? Once criterion: as the performance matters, I would prefer to send captured data to client before saving that in the DB. -
How to Automatically Detect PySpark Home Path from PyInstaller Executable?
In my local development environment, I can easily run a PySpark application without configuring anything. However, on the server, we are using PyInstaller for EXE deployment. PyInstaller does not include the PySpark libraries' _internal folder in the executable, so I have to manually set the path. Here's a snippet of my PyInstaller manage.py script: # -*- mode: python ; coding: utf-8 -*- # Analysis for manage.py a_manage = Analysis( ['manage.py'], pathex=['/app/app_name/app_name-backend-dev'], # I tried adding .venv/lib/python3.11/site-packages to the pathex, but it didn't work binaries=[ ('/usr/lib/x86_64-linux-gnu/libpython3.11.so.1.0', './_internal/libpython3.11.so.1.0') ], datas=[], hiddenimports=[ # I tried adding pyspark imports, but it didn't work 'pyspark', 'pyspark.sql', 'pyspark.sql.session', 'pyspark.sql.functions', 'pyspark.sql.types', 'pyspark.sql.column', 'app_name2.apps', 'Crypto.Cipher', 'Crypto.Util.Padding', 'snakecase', 'cryptography.fernet', 'cryptography.hazmat.primitives', 'cryptography.hazmat.primitives.kdf.pbkdf2', 'apscheduler.triggers.cron', 'apscheduler.schedulers.background', 'apscheduler.events', 'oauth2_provider.contrib.rest_framework', 'app_name.apps', 'app_name.role_permissions', 'django_filters.rest_framework', 'app_name.urls', 'app_name.others.constants', 'app_name.models', 'app_name', 'sslserver' ], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], noarchive=False, ) pyz_manage = PYZ(a_manage.pure) exe_manage = EXE( pyz_manage, a_manage.scripts, [], exclude_binaries=True, name='manage', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, ) coll_manage = COLLECT( exe_manage, a_manage.binaries, a_manage.datas, strip=False, upx=True, upx_exclude=[], name='manage', ) When I try to run the executable, I encounter the following error: Traceback (most recent call last): File "portal/operations/load_data/load_data.py", line 57, in start File "portal/pyspark/operations.py", line 498, in get_session File "pyspark/sql/session.py", line 497, in getOrCreate File … -
Race condition with django GET
I wrote a function in Django which looks roughly like this: @login_required def make_appointment(request): existing_appointments = Appointment.objects.all() print('existing_appointments = ', len(existing_appointments)) new_appointment = Appointment() new_appointment.save() # ... And I call this from javascript using the following code: for(i=0; i<2; i++){ const xhr = new XMLHttpRequest(); xhr.open('GET', "make_appointment/") xhr.send(); } I would expect that the GET command is called first, which in turn causes Django to execute the make_appointment function. The log I would expect is: [18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0 existing_appointments = 0 [18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0 existing_appointments = 1 But the log that I usually get is: existing_appointments = 0 existing_appointments = 0 [18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0 [18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0 But I also already got existing_appointments = 0 existing_appointments = 1 [18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0 [18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0 For me, this is problematic because the time of the second appointment depends on the existance of the first appointment so they should be created subsequently. How can I fix this code? -
Static file references differ on servers with same configuration
I'm using Django 5.1.3 for a project and the template references to the static files, despite being identical on three different servers, don't all point to the same relative location. The template tag {% static 'mystyle.css' %} is rendered in the following ways on our different servers (right-click, view source, HTML, yada yada): Server 1 (DEV): rendered/served HTML references /djangodir/static/mystyle.css Server 2 (TEST): rendered/served HTML references /djangodir/static/mystyle.css Server 3 (PROD): rendered/served HTML references /djangodir/djangodir/static/mystlye.css The first two work. What would cause a template to render two different paths with the same tag? settings.py is the same on all the servers (all the files in /djangodir and /staticfilesdir are identical). ./manage.py collectstatic has been run on all servers. Apache's httpd.conf is identical across them. Why does PROD get the extra djangodir rendered in the path from staticfiles? How would I go about further debugging this particular issue? -
QuotaGuard Heroku Django and Azure SQL DB
import pandas as pd from PIL import Image from sqlalchemy import create_engine from sqlalchemy.pool import NullPool from dotenv import load_dotenv import socks import socket import os import io load_dotenv() CLIENT_ID = os.getenv("CLIENT_ID") TENANT_ID = os.getenv("TENANT_ID") CLIENT_SECRET = os.getenv("CLIENT_SECRET") DB_SERVER = os.getenv("DB_SERVER") DB_NAME = os.getenv("DB_NAME") DB_DRIVER = os.getenv("DB_DRIVER") DB_TIMEOUT = os.getenv("DB_TIMEOUT") QUOTAGUARD_URL = os.getenv("QUOTAGUARD_URL") if QUOTAGUARD_URL: proxy_protocol, proxy_auth_host = QUOTAGUARD_URL.split("://") proxy_auth, proxy_host_port = proxy_auth_host.split("@") proxy_user, proxy_pass = proxy_auth.split(":") proxy_host, proxy_port = proxy_host_port.split(":") proxy_port = int(proxy_port) socks.set_default_proxy(socks.SOCKS5, proxy_host, proxy_port, username=proxy_user, password=proxy_pass) socket.socket = socks.socksocket connection_string = ( "mssql+pyodbc:///?odbc_connect=" + f"Driver={{{DB_DRIVER}}};" + f"Server={DB_SERVER};" + f"Database={DB_NAME};" + "Encrypt=yes;" + "TrustServerCertificate=yes;" + f"Connection Timeout={DB_TIMEOUT};" + "Authentication=ActiveDirectoryServicePrincipal;" + f"UID={CLIENT_ID};" + f"PWD={CLIENT_SECRET};" + f"Authority Id={TENANT_ID};" ) engine = create_engine(connection_string, poolclass=NullPool) try: query = "SELECT * FROM list_photos" with engine.connect() as conn: df = pd.read_sql(query, conn) print("DataFrame loaded successfully!") print(df.head()) except Exception as e: print(f"Error: {e}") for index, row in df.iterrows(): holdon = input("Press Enter to view the next image...") try: image = Image.open(io.BytesIO(row['photo'])) image.show() except Exception as e: print(f"Error displaying image at index {index}: {e}") I'm trying to pull the data from Azure SQL database via proxy but it is not using this proxy to connect to it therefore I'm getting an error from database where it … -
Classed Based Views : Why do URL parameters in Django/DRF go into `self.kwargs` instead of another attribute (e.g., `self.url_params`)?
While working with Django/Django Rest Framework, I noticed an inconsistency in how URL parameters are acccessed in class-based-views. Problem Description In Generic Class Based Views, I can access URL parameters in two different ways - depending on the method: Trough the positional arguments: For example in the get method, I can access URL parameters as a positional arguments passed directly to method: #urls.py path('test/<str:param1>/<int:param2>/', MyView.as_view()) #views.py class MyView(View): def get(self, request, param1, param2): return JsonResponse({'param1': param1, 'param2': param2}) Trough self.kwargs attribute For example when i want to access the same parameters in the get_queryset method, I have to use self.kwargs #views.py class MyView(ListView): model = MyModel def get_queryset(self): param1 = self.kwargs.get('param1') param2 = self.kwargs.get('param2') return MyModel.objects.filter(field1=param1, field2=param2) I know that i can access url parameters from kwargs anywhere but it leads me to some questions My questions: Why didn't Django/DRF introduce a dedicated attribute for URL parameters ? Wouldn't it be more intuitive to have these parameters stored in dedicated attribute such as self.url_params - are there any specific reasons why self.kwargs nameing is preferred - i got the convention but its a bit confusing for me, we got a lot of others attributes such as idk self.data or self.method, … -
Cart in Django is not updating in frontend but working fine in database
I'm making an ecom site. When customer select Product size from dropdown boxes, it sends the correct selected size in backend but showing default value in frontend. My HTML code for this: <select class="form-select form-select-sm" id="size-cart{{ product.id }}"> {% for key, value in sizes.items %} {% if key == product.id %} <option selected value="{{ value.id }}">{{ value.size }}</option> {% endif %} {% endfor %} {% for size in all_sizes %} <option value="{{ size.id }}">{{ size.size }}</option> {% endfor %} </select> Related code in views.py file def cart_update(request): cart = Cart(request) if request.POST.get('action') == 'post': print("request POST data:", request.POST) product_id = int(request.POST.get('product_id')) product_qty = int(request.POST.get('product_qty')) size_id = int(request.POST.get('product_size')) selected_size = get_object_or_404(Product_Size, id=size_id) print("Selected size: ", selected_size) cart.update(product=product_id, quantity = product_qty, size=selected_size) response = JsonResponse({'qty': product_qty}) messages.success(request, ("Your cart has been updated....")) return response Related code in cart.py in Cart class: def update(self, product, quantity, size): prdct = get_object_or_404(Product, id=product) #print(f"Found product: {prdct}") product_id = str(prdct.id) product_qty = int(quantity) print("Size passed in cart.update ", size) if product_id in self.cart: self.cart[product_id]['quantity'] = product_qty if size: self.cart[product_id]['size']= size.size print(f"Updated cart: {self.cart[product_id]['size']}") else: self.cart[product_id]['size']= None self.session['cart'] = self.cart self.session.modified = True print("session updated: ", self.session.get('cart')) if self.request.user.is_authenticated: current_user = Profile.objects.filter(user__id=self.request.user.id) carty = str(self.cart) carty = … -
There is problem in inegrate onlyoffice text editor in react and python django
enter image description here see using docker i take onlyoffice container then create api and integrate in react during run the code document not open in text editor help me to solve these issue if not then provide another way to inntegrate only office below is apicode backend django these are docker logs 0 [{"type":0,"userid":"1"}],"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJmOGU2ZmRkZjRkNDM2NTFjMDllNDg4YTc0ZWE5ZjU4NjI0NDE1NzVmNGJhNzQzYTA2NTdkODRlMzkzYmNiMDQxIiwic3RhdHVzIjo0LCJhY3Rpb25zIjpbeyJ0eXBlIjowLCJ1c2VyaWQiOiIxIn1dLCJpYXQiOjE3MzQ1MTkwMjUsImV4cCI6MTczNDUxOTMyNX0.f5XPsyLeWfJCMgqNnLCRtMbseCj-MDdgO7M6wWYQwTA"} Error: Error response: statusCode:404; headers:{"content-security-policy":"default-src 'none'","x-content-type-options":"nosniff","content-type":"text/html; charset=utf-8","content-length":"170","date":"Wed, 18 Dec 2024 10:50:25 GMT","connection":"keep-alive","keep-alive":"timeout=5"}; body: -
AWS Instance EC2 - Ubuntu stops after sometime
i am new to AWS. I had my Python Django project setup to host on AWS using EC2 INSTANCE WITH UBUNTU. It works when i run the project. After a while, may be 5 minutes later, when the site or console is not in use, the site seems to be unreachable. It show 502 Bad Gateway nginx/1.24.0 (Ubuntu) . How can i solve this issue? I want my site to be reachable once all time once when i run the project. -
Error 500 - Internal Server Error on Django on Production server
I’m facing an issue with my Django application running in production on CPanel, and I'm using Passenger for WSGI. The application works fine on the local machine but on the live server it only works the root route (/), but all other routes return a 500 - Internal Server Error. I haven’t been able to pinpoint what’s causing the issue. Note: even a teste route like this returns the error 500 on live server: path('test/', lambda request: HttpResponse('Test route works!')), Main URL.py from django.urls import include, path from django.http import HttpResponse urlpatterns = [ path('', include('accommodation.urls')), path('test/', lambda request: HttpResponse('Test route works!')),#This works only on local machine ] Accommodation URL.py from django.urls import path from .views.dashboard_view import dashboard from .views.booking_view import newBooking,manageBooking,walk_in,walk_in_checkin,check_out,book_workspace,book_room,check_in,booking_requests,get_booking_request_details,delete_booking_request,workspace,check_bed_availability from .views.guest_view import new_client,new_guest,manageClient,manageGuest,update_guest,delete_guest from .views.room_view import roomList,room_and_bed_availability,roomMaintenance,stayView,stay_data,dirtyRoom,clean_bed from .views.settings_view import add_site,manageSite,roomCategory,addRoomCategory,editRoomCategory,bedManagement,addBed,roomManagment, workspaceManagment from .views.finance_view import Debits,payments,mark_as_paid,completedPayments,rates,processReport,costCenter from .views.incidents_medical import incidents,medical_cases,add_incident,add_case from .views.reports_view import generate,generate_report from .views.miscellaneous_view import meals,vehicleRent urlpatterns = [ # Dashboard Routes path('', dashboard, name='accommodation_dashboard'), #only this works on live server #Booking Routes path('new_booking/', newBooking, name='new_booking'), path('new_booking/book/', book_room, name='book_room'), path('manage_booking/', manageBooking, name='manage_booking'), path('manage_booking/check_in/<int:booking_id>/', check_in, name='check_in'), path('online_request/', booking_requests, name='online_request'), path('online_request/<int:booking_id>/', get_booking_request_details, name='get_booking_request_details'), path('online_request/check_bed_availability/<int:bed_id>/<str:checkin_date>/<str:checkout_date>/', check_bed_availability, name='check_bed_availability'), path('delete_booking_request/<int:booking_id>/', delete_booking_request, name='delete_booking'), path('booking/workspace', workspace, name='workspace'), #Check-in Routes path('check_in/', walk_in, name='check_in'), … -
What is the best way to write a serializer for enum and subsequent display in drf_spectacular?
I want to create a constructor for enum serializers to use them in views later and correctly display data in Swagger, especially in the schema. My typical enum: class EServicePlatform(models.IntegerChoices): ONLINE = 1, 'Online' OFFLINE = 2, 'Offline' Which are directly sent to views as a dictionary: django Copy code class DictionaryPlatforms(APIView): @extend_schema(responses={ 200: OpenApiResponse(response=DictionarySerializer(enum_class=EServicePlatform, many=True)), 400: OpenApiResponse(description='Bad Request')} ) def get(self, request, *args, **kwargs): data = [{"value": item.value, "label": item.label} for item in EServicePlatform] serializer = DictionarySerializer(data=data, many=True, enum_class=EServicePlatform) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The serializer constructor itself: class DictionarySerializer(serializers.Serializer): value = serializers.ChoiceField(choices=[]) # Set an empty list by default label = serializers.CharField() def __init__(self, *args, **kwargs): # Expect enum_class to be passed via kwargs enum_class = kwargs.pop('enum_class', None) if not enum_class: raise ValueError("enum_class is required") # Dynamically set choices based on the passed enum class self.fields['value'].choices = enum_class.choices super().__init__(*args, **kwargs) self.enum_class = enum_class def validate(self, data): # Automatically add the label corresponding to the value data['label'] = dict(self.enum_class.choices)[data['value']] return data In the current implementation, two problems arise: It seems to me that the logic is overly complicated and it can be significantly simplified. But how? For some reason, Swagger pulls data from a different … -
Django web application on azure deployment
I am trying to deploy my Django web application on azure. It is running fine with debug = true. but after deployment on azure app service with debug = False in settings.py, it is not able to load user uploaded media files in an iframe, saying URL not found. I am able to delete and move media files but i am not able to show using Iframe in HTML. This is settings.py: MEDIA_URL = '/media/' # URL for accessing media files MEDIA_ROOT = BASE_DIR / 'media' # Directory where files will be uploaded to this is urls.py: urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is html: <iframe src="{{ MEDIA_URL }}{{ row.document.url }}" title="Document View" frameborder="0" width="100%" height="600px"></iframe> I tried adding core headers, but it is not working. -
Django - show data across all views for selected year
I’m developing a learner tracking system which shows all data for administration and management views relating to the current academic year. AcademicYear model has a boolean field of is_current, this is used to filter related models by the returned pk of the object where is_current = True. How can I set up the system so the default views offer what I currently have set up but then offer the user an archive option where they select a year from a dropdown menu of is_current = False, and all views then show data relating to the selected year? -
Where to place a sitemap.xml file in my django project?
I created a sitemap.xml file using Screaming Frog and now I want to place it in my django project so that it is reacheable at example.com/sitemap.xml. But I am not sure where to put it? Where should I put it? -
Django MultipleChoiceField not sending valid data in POST
My django form has a field MultipleChoiceField in with a list of tuples as the options. choice = forms.MultipleChoiceField( choices = [("1", "Option 1"), ("2", "Option 2"), ("3", "Option 3")], label="Choose an option", widget=forms.Select(), required=True, ) This creates the DOM element when it is loaded <select name="choice" id="id_choice"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> However, when it sends the POST request on the form being submitted, instead of giving a value ("1", "Option 1"), it just sends "1". As such, this triggers a ValidationError in the MultipleChoiceField when it is validated, as it has this function which requires the POST value to be a list or a tuple. def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list" ) return [str(val) for val in value] Is there any way of setting the POST value of the DOM element so that it sends this tuple? I tried to change it in the views.py function using field.data, but got This QueryDict instance is immutable Thanks in advance.