Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
spell check chrome extension
i am building a chrome extension for spelling correction and i want to make the result display on any input field as red line under the mispelled word and a drop down menu this is the background.js chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.prevWord) { fetch('http://localhost:8000/spelling_correction/' + request.prevWord ) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.sentence) { fetch('http://localhost:8000/spelling_correction/' + request.sentence ) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } }); and this is content.js var prevWord = ''; var currentWord = ''; if (event.code === 'Space') { var words = event.target.value.trim().split(' '); prevWord = words[words.length - 2]; chrome.runtime.sendMessage({prevWord: prevWord}, function(response) { var obj = JSON.parse(response); obj.response.errors.forEach(function(error) { if (prevWord === error.bad) { var suggestions = error.better.join(', '); var div = document.createElement('div'); div.innerHTML = '<span style="text-decoration: underline; color: red;">' + prevWord + '</span>: Did you mean ' + suggestions + '?'; document.body.appendChild(div); } }); }); } else { currentWord += event.key; } }); document.addEventListener('keydown', function(event) { var currentSentence = ''; if (event.code === 'Period') { currentSentence = event.target.value; chrome.runtime.sendMessage({sentence: currentSentence}, function(response) { var obj = JSON.parse(response); obj.response.errors.forEach(function(error) { if (currentSentence.includes(error.bad)) { var suggestions = error.better.join(', '); var div = document.createElement('div'); … -
POST Request to Django Backend from Flutter/Dart
I am trying to make a POST Request from my Flutter Frontend to my Django Backend, I am using DIO. The Error I get is: Bad Request: /api/homeapi/Users/ [20/Jun/2023 18:16:38] "POST /api/homeapi/Users/ HTTP/1.1" 400 58 This is my Code: serializer.py: from rest_framework import serializers from .models import Brand, User class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = [ 'imgURL', 'brand_name' ] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'email', 'selected_colors' ] views.py class BrandViewSet(viewsets.ModelViewSet): queryset = Brand.objects.all() serializer_class = BrandSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def create(self, request): serializer = UserSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) except ValidationError as e: return Response({'errors': e.detail}, status=status.HTTP_400_BAD_REQUEST) Models.py: class Brand(models.Model): imgURL = models.CharField(max_length=120) brand_name = models.CharField(max_length=200) class User(models.Model): email = models.EmailField(max_length=120) selected_colors = models.JSONField() urls.py router = routers.DefaultRouter() router.register('Brands', BrandViewSet, basename='brand') router.register('Users', UserViewSet, basename='User') urlpatterns = [ path('admin/', admin.site.urls), path('api/homeapi/', include(router.urls)), path('api/get-csrf-token/', get_csrf_token, name='get-csrf-token'), ] This is my Dart Code: api.dart import 'package:dio/dio.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; const dataUrl = 'http://127.0.0.1:8000/api/homeapi/Brands/'; Future<void> postData(String url, Map<String, dynamic> fields) async { final headers = {'Content-Type': 'application/json'}; try { final response = await http.post(Uri.parse(url), headers: headers, body: json.encode(fields)); // Convert fields to JSON string if (response.statusCode … -
How to display products from category in dajngo?
I want to filter product by category I have made two categories one main category and category. Product is filtering according to main category but not according to category please someone tell me. models.py enter image description here enter image description here views enter image description here enter image description here html enter image description here enter image description here -
can you give me advice on django?
I would like help with a problem during a class project on django hi everyone i am new to django; I would like to know how I could create a kind of form (table) that a user can enter information such as courses, course start time, course end time and d other information. he can also add courses, by dynamically displaying a django course form already created. If I can get any leads or ideas that would be great. THANK YOU -
Unable to import views from an app in Django
I am trying to import views from my app "first_app", the command from first_app import views doesn't work in Pycharm. What am I doing wrong? I also have tried: from first_project.first_app import views, but I get "ModuleNotFoundError" exception. -
Find nearest neighbor by distance
I have a problem in my code to find the nearest neighbor, I am building a route optimizer for people who travel on foot, now if I tell you, the error that I am experiencing. First I have a model in django with the following fields: # Create your models here. class Pdv(BaseModel): name = models.CharField(unique=True, max_length=150, verbose_name="Nombre del PDV:") direction = models.CharField(max_length=200, verbose_name="Dirección:") business_name = models.CharField(max_length=200, null=True, blank=True, verbose_name='Razón Social:') pdv_code = models.CharField(max_length=100, verbose_name='codigo de PDV:', null=True, blank=True) pdv_channel = models.CharField(max_length=200, null=True, blank=True, verbose_name='Canal de PDV:') chain_pdv = models.CharField(max_length=200, verbose_name='Cadena:', null=True, blank=True) time_pdv = models.CharField(max_length=20, verbose_name='Tiempo en PDV:', null=True, blank=True) frequency_pdv = models.CharField(max_length=4, verbose_name='Frecuencia PDV:') latitude = models.FloatField(verbose_name="Latitud:") longitude = models.FloatField(verbose_name="Longitud:") city = models.CharField(max_length=50, verbose_name='Ciudad:') department = models.CharField(max_length=50, verbose_name='Departamento:') customers = models.ForeignKey(Customers, on_delete=models.CASCADE, null=False, blank=False, verbose_name="Cliente:") # We create the str that returns us when the class is called def __str__(self): # self.datos = [self.name, self.direction, self.latitude, self.longitude, self.city, self.department] return self.name In the model I store the coordinates separately, guaranteeing that the client correctly stores the data of each point. In the view I am building a process where: Find the northernmost point of all points and make it as the reference point Order them by distance from … -
Running a java jar from Django with subprocess.run
I am going mad over something that should be very simple. I have a jar program that needs to read stuff from a database, called from Django. It takes the db connection url as an arg. When I run it in the command line, all's fine: C:\Dev\mcl>java -jar mcl.jar "jdbc:postgresql://<IP:PORT>/DBName?user=<user>&password=<pwd>" However when I run it within Django from a thread, it doesn't find the postgres driver. I use: result = subprocess.run(['java.exe', '-jar', 'mcl.jar', '"jdbc:postgresql://<IP:PORT>/DBName?user=<user>&password=<pwd>"'], cwd=r'C:\\Dev\\mcl', capture_output=True, shell=True, text=True) It doesn't work, I get: No suitable driver found for "jdbc:postgresql://<IP:PORT>/DBName?user=&password=" I have tried many things, embedding the postgres jar in mcl.jar, changing the arguments in the subprocess.run call but nothing works. In the java I have tried with and without Class.forName("org.postgresql.Driver"); The Java code is: try { mConn = DriverManager.getConnection(mURL); mConn.setAutoCommit(true); } catch (SQLException ex) { System.err.println("Database connection error: " + ex.getLocalizedMessage()); mConn = null; } There must be something specific to Django environment, but what? -
How to go to another url without reloading the page
I have a chat. One view is responsible for displaying the list of chats and chat content: def chats_view(request, chat_uuid=None): if chat_uuid: context = { # Variables for displaying both the list and chat content } return render(request, 'chats/chats.html', context) else: context = { # Variables for displaying only the list of chats } return render(request, 'chats/chats.html', context) On the "/chats/" URL, only the list of chats should be displayed, and on the "/chats/<chat_uuid>/" URL, both the list of chats and the content of the selected chat should be displayed. When clicking on any chat without reloading the page, a window with the chat content should appear next to it, and the URL should change from "/chats/" to "/chats/<chat_uuid of the selected chat>". I tried to do this using AJAX, but in the HTML content there are Django template tags and they are rendered as text. -
Testing Django Model Form with Overridden Save Method and Custom Email Sending Function
I'm trying to test a Django model form that overrides the save method and implements a custom send_mail function. The send_mail function uses loader.render_to_string to generate an email body and then calls a custom send_email function to send the email. I'm having trouble writing the test case to properly assert the usage of these functions. Here's my code: class MockObjects: def mock_render_to_string(self): return 'This is an email' class FormsTestCase(TestCase): mock = MockObjects() @patch('django.template.loader.render_to_string') @patch('ext_libs.sendgrid.sengrid.send_email') def test_send_mail(self, mock_send_email, mock_render_to_string): form = CustomPasswordResetForm() context = {'site_name': 'YourSiteName'} to_email = 'testuser@example.com' mock_render_to_string.return_value = self.mock.mock_render_to_string() mock_send_email.return_value = None form.send_mail(context, to_email) mock_render_to_string.assert_called_once_with('registration/password_reset_email.html', context) mock_send_email.assert_called_once_with( destination=to_email, subject="Password reset on YourSiteName", content=mock_render_to_string.return_value ) class CustomPasswordResetForm(PasswordResetForm): def send_mail(self, context, to_email, *args, **kwargs): print('got here') email_template_name = 'registration/password_reset_email.html' print('should call them') body = loader.render_to_string(email_template_name, context) print(f'got body {body}') print('sending mail') send_email(destination=to_email, subject=f"Password reset on {context['site_name']}", content=body) print('sent') #ext_libs.sendgrid.sengrid.send_email def send_email(destination, subject, content, source=None, plain=False): print('did it get here') print(f'{destination}, {subject} {content}') The issue I'm facing is that the test is failing with the following error: AssertionError: Expected 'mock' to be called once. Called 0 times. I traced the execution and the mocked classes are being called. Here is the full logs with prints python .\manage.py test user.tests.test_forms.FormsTestCase.test_send_mail {'default': {'ENGINE': … -
Problem with table creation through Models Django
I am working on a Hotel site (educational project) on Django. I have BookingForm(ModelsForm) and respectively Booking(models.Model). Although form is working correctly (I debugged, data is valid), my form doesn't create Booking table in default Django database sqllite3, it's never appeared in admin panel. models.py from django.db import models import datetime from django.db.models import EmailField from django.core.validators import EmailValidator, RegexValidator ROOM_TYPES = [ ('1', "Single - 200"), ('2', "Double - 350"), ('3', "Twin - 350"), ('4', "Double-Double - 600"), ('5', "King Room - 450"), ('6', "Luxury - 800") ] GUESTS_NUMBER = [ ('1', "1 person. Single comfort room"), ('2', "2 people. Recommended Double, Twin or King room"), ('3', "3 people. Double-Double or Luxury will match your needs"), ('4', "4 people. Double-Double or Luxury will match your needs"), ('5', "5 people. Our Luxury room is for you!") ] STAT = [ ('0', "Waits for payment"), ('1', "Paid") ] class Booking(models.Model): check_in = models.DateField(default=datetime.date.today()) check_out = models.DateField(default=datetime.date.today()) room_type = models.CharField(max_length=200, choices=ROOM_TYPES, default=2) guests_number = models.CharField(max_length=200, choices=GUESTS_NUMBER, default=2) name = models.TextField(max_length=50) surname = models.TextField(max_length=100) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) email = EmailField(max_length=254, blank=False, validators=[EmailValidator()]) payment_status = … -
How to give multi select for foreign key without many to many field or through table django admin
class StudentPlatformDefaultDocuments(models.Model): id = models.AutoField(db_column='id', primary_key=True, db_index=True) document = models.ForeignKey(Documents, db_column='DocumentId') I am trying to give multi select in forms.py, but it does not work. def save(self, commit=True): document = self.cleaned_data['document'] print(document,'document get') instance= super(MyModelForm, self).save(commit=False) if document: documents = [] for doc in document: print(doc,'doc1212121') print(doc.documentid,'doc1212121') document1 = Documents.objects.get( documentid=doc.documentid).documentid print(document1,'document1') documents.append(document1) test = StudentPlatformDefaultDocuments.objects.create( document=doc.documentid) test.save() print(documents) return instance Tried overrding save method in forms.py but getting error.` -
django messages not displaying
If i post the message to the webapp, i can find it if i log in as a django super user and check in the backend using the django admin pannel but they are not displaying on my website.. I'll put up screengrabs of all the related code. these are my django imports This is the room view code This is the room template html This is how it is outputting to me I think i should also mention I'm following a tutorial by Traversy media and have sent 2 days trying to figure this out. I thought maybe it was typing errors or a mistake in my loops but i re-wrote that code multiple times now -
No module named, Python-Django
i have problem with start in django. After command cd manage.py runserver, is problem no module named 'first' Sc with my file.(https://i.stack.imgur.com/wcRod.png)(https://i.stack.imgur.com/8o7sB.png) (https://i.stack.imgur.com/Dod2r.png) and in views.py i have def index(request): return HttpResponse("Hello world") Thanks for help. I try change to url(r'^$',views.index, name='index') but deosn't working. Maybe problem is in files places? -
django slugify thailand umlauts
i need to create Thai language slug but after i use slugify not working Models.py from django.utils.text import slugify title = models.CharField(max_length=80,unique=True) slug = models.SlugField(max_length=80,unique=True,allow_unicode=True) def __str__ (self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Blog, self).save(*args, **kwargs) Admin from django.contrib import admin from .models import category,Blog class BlogAdmin (admin.ModelAdmin): prepopulated_fields = {'slug':('title',)} admin.site.register(category) admin.site.register(Blog,BlogAdmin) enter image description here i need : slug = สวัสดีครับ ยินดีที่ได้รู้จัก but not : slug = สวสดครบ-ยนดทไดรจก if i input สวัสดีครับ ยินดีที่ได้รู้จัก to slug error alert " Enter a valid “slug” consisting of Unicode letters, numbers, underscores, or hyphens. " how i can fix it -
How to setup webrtc connection between django server and browser using aiortc?
I want to setup webrtc connection between iot device with django server, that located behind NAT, and browser. I'm trying to use aiortc. When I'm using standalone aiortc example, that contains aiohttp server, it works, but when I'm trying to estabilish connection with my django app, I'm getting WebRTC: ICE failed, add a TURN server and see about:webrtc for more details (in Firefox), but standard "webcamera" example works ok without TURN (only with STUN). I testing it locally, so it couldn't be problem of network. Here is my code: import os from aiortc.contrib.media import MediaPlayer, MediaRelay from aiortc import RTCPeerConnection, RTCSessionDescription from aiortc.contrib.media import MediaPlayer, MediaRelay import asyncio import atexit ROOT = os.path.dirname(__file__) relay = None webcam = None pcs = set() def create_media_streams(): global relay, webcam options = {"framerate": "30", "video_size": "640x480"} if relay is None: webcam = MediaPlayer("/dev/video0", format="v4l2", options=options) relay = MediaRelay() return None, relay.subscribe(webcam.video) async def create_peer_connection(sdp, con_type): global pcs offer = RTCSessionDescription(sdp=sdp, type=con_type) pc = RTCPeerConnection() pcs.add(pc) @pc.on("connectionstatechange") async def on_connectionstatechange(): print("Connection state is %s" % pc.connectionState) if pc.connectionState == "failed": await pc.close() pcs.discard(pc) # open media source audio, video = create_media_streams() if video: pc.addTrack(video) await pc.setRemoteDescription(offer) answer = await pc.createAnswer() await pc.setLocalDescription(answer) return (pc.localDescription.sdp, … -
IIS 10 url rewrite with reverse proxy 404 errors
I am currently running 2 python applications on IIS 10. Django app bind to https://mydomain.ca/ Flask app bind to http://localhost:8000 The default page for the flask app is http://localhost:8000/databases I am trying to url rewrite https://mydomain.ca/datatools to my flask app. I am receiving my flask app's error 404 page each time. Here are the rules in my web.config file: <rewrite> <rules> <rule name="Redirect" stopProcessing="true"> <match url="^datatools$" /> <conditions logicalGrouping="MatchAll" trackAllCaptures="false" /> <action type="Redirect" url="https://mydomain.ca/datatools/" /> </rule> <rule name="Reverse Proxy" stopProcessing="true"> <match url="^datatools/$" /> <conditions logicalGrouping="MatchAll" trackAllCaptures="false" /> <action type="Rewrite" url="http://localhost:8000/databases/" /> </rule> <rule name="ReverseProxyInboundRule1" stopProcessing="true"> <match url="^datatools/*(.*)$" /> <action type="Rewrite" url="http://localhost:8000/{R:1}" /> </rule> </rules> </rewrite> Any help is appreciated! -
How to update user session from backend after updating user's metadata?
I´m using Next.js for the client side, auth0 to handle authentication and Django Rest Framework for the backend. Following the Auth0's Manage Metadta Using the Management API guide, I achieved to set new metadata values (I have checked it from the Dashboard). As it is spectated, if the user refresh its profile page (pages/profile.js), the old session metadata is rendered. So my question is, how can I update user session after the metadata values has been set? I have tried to use updateSession from @auth/nextjs-auth I also have tried nextjs-auth0: update user session (without logging out/in) after updating user_metadata , but checkSession() is not defined so I got lost there. index.js async function handleAddToFavourite() { if (selected) { const data = await axios.patch("api/updateUserSession",) // Update the user session for the client side checkSession() //this function is not defined } } api/updateUserSession.js async function handler(req, res) { const session = await getSession(req, res); if (!session || session === undefined || session === null) { return res.status(401).end(); } const id = session?.user?.sub; const { accessToken } = session; const currentUserManagementClient = new ManagementClient({ token: accessToken, domain: auth0_domain.replace('https://', ''), scope: process.env.AUTH0_SCOPE, }); const user = await currentUserManagementClient.updateUserMetadata({ id }, req.body); await updateSession(req, res, … -
Deploy python Django project on Azure Web App Error log/supervise not found
TL;DR: While trying to deploy a Django application on Azure web app running with Python 3.11 i'm getting this fatal error and the Azure web app is unable to start: Error: [Errno 2] No such file or directory: '/etc/runit/runsvdir/default/ssh/log/supervise' Long explanation: I'm currently trying to deploying a Django Application on Azure Web apps. Since i'm running the latest python version, the Web app is a configured as following: Publishing model: Code (not docker) Runtime Stack: Python - 3.11 Os: Debian (default) i'm currently deploying the code by Zipping the project and running the following Azure command in the Cloud shell (or in the pipeline, is the same stuff): az webapp deploy --subscription "My supersecret subscription" --resource-group "secret" --name "secret" --src-path my_project_zipped.zip --clean true --restart true Moreover, since i want to create a virtual environment i must configure some environment variables that are handling the deploy life-cicle (oryx build ecc.). Here's the list: SCM_DO_BUILD_DURING_DEPLOYMENT : True (this is for running oryx build) CREATE_PACKAGE: False DISABLE_COLLECTSTATIC: True ENABLE_ORYX_BUILD: False Here's the current folder structure: MYAPPLICATION: │ manage.py │ requirements.txt │ ├───deployments │ │ azure-pipelines.yml │ │ __init__.py │ │ │ ├───Dev │ │ │ deploy.sh │ │ │ dev_settings.py │ │ │ … -
Django guardian several permissions with get_objects_for_user
If I pass in one permission at a time get_objects_for_user works fine >>> projects = get_objects_for_user(alvin, 'view_project', klass=Project) >>> projects <QuerySet [<Project: Central whole.>]> >>> projects = get_objects_for_user(alvin, 'change_project', klass=Project) >>> projects <QuerySet [<Project: Education soldier.>, <Project: Evening cold.>]> Now from the docs It is also possible to provide list of permissions rather than single string, But this does fail to return anything >>> projects = get_objects_for_user(alvin, ('change_project', 'view_project'), klass=Project) >>> projects <QuerySet []> what am I doing wrong when passing the permissions list? -
How is this possible that the same serializer produces different results in Django?
I am facing a rather annoying issue than a difficult one. The problem is the following: a given djangorestframework ModelSerializer class called UserSerializer serializes the authenticated user instance with proper image result from the model's FileField attribute when calling some generic API view of djangorestframework, and using the exact same serializer, the image path receives a domain address by default Django version: 4.2.2, Django REST Framework version: 3.14 What I do want to receive in output: the path of the stored file as mentioned in Django documentation (MEDIA_URL is 'media/'), without the localhost domain appended to it. The below image shows that in the RootLayout, I receive the correct path starting with /media/etc. so I append domain address from environmental variable depending on mode, while in UsersLayout, each user gets my MANUAL appended domain and an automatic one from somewhere. This is my urls.py from django.urls import include, path from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from .views import * urlpatterns = [ path('change-password/<int:pk>', UserChangePasswordView.as_view(), name='auth_change_password'), # ---- Untestable path('languages/', LanguagesL.as_view()), # ----------------------------------------------------------- Tested path('password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), # ----- path('payment/barion/ipn/', PaymentBarionIPN.as_view()), # -------------------------------------------- Untestable path('payment/barion/start/<int:pk>', UserSubscriptionCreateStart.as_view()), # ----------------------- Untestable path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), # ---------------------------- path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), # --------------------------- path('user-factor-relation-strategies/', UserFactorRelationStrategiesLC.as_view()), # … -
The Spotify API callback url has '#' in it instead of '?' how to access parameters in python django
I am using the Implicit grant authorisation (1 of 3) types of authorisation provided by Spotify. The callback url looks something like this http://localhost:8000/callback/#access_token=BQDRRPQ1Nulwcxx...mFNtnTsVUNlkCg&token_type=Bearer&expires_in=3600&state=NtiLgMVtLPx926Ay If it was http://localhost:8000/callback/**?**access_token Then I am able to obtain the query parameters using request.GET in my view, but since it has #, request.GET returns empty dictionary. I also tried request.build_absolute_uri(), but it returns just http://localhost:8000/callback/ Here is how my view looks def callback(request, format=None): print(request.GET) if "access_token" in request.GET: print(request.GET["access_token"]) return HttpResponse("Callback") I was expecting request.GET to have the access_token, expires in and the parameters that are in the uri, but I'm getting empty dict. -
Best approach for implementing configurable permissions and roles in Django
I'm working on a Django application and I need to implement configurable permissions and roles. I want to be able to add new roles and associate multiple tasks with each role for specific modules in my Django app. What would be the best approach to achieve this? I would like to have the flexibility to define different roles with specific permissions and assign them to users. Additionally, I want to be able to manage these roles and permissions easily, preferably through my application not django admin. Any insights, recommendations, or examples of how to implement this functionality in Django would be greatly appreciated. Thank you! -
can't find the object in discount system in django
I made a discount system in django that gets a code from user and if it was valid,it will save it as a session in user browser. here is models.py : class Discount(models.Model): code = models.CharField(max_length=20) discount = models.IntegerField(null=True , blank=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() active = models.BooleanField(default=False) and there is its view i'm using: def Coupon_view(request): if request.method == 'POST': form = CouponForm(request.POST) if form.is_valid(): data = form.cleaned_data try: cop = Discount.objects.get(code__iexact=data['code'] , valid_from__lte = now() , valid_to__gte = now() , active=True) request.session["coupon"] = cop.id except: messages.error(request , "code is not exist") try: url = request.META.get('HTTP_REFERER') return redirect(url) except: return redirect("Order:Checkout_page") here is the CouponForm: class CouponForm(forms.Form): code = forms.CharField(max_length=30) at the end , there is the form that i am using : <form action="{% url 'Order:Coupon_page' %}" method="post"> {% csrf_token %} <input type="text" name="code" placeholder="code"> <button type="submit">submit</button> </form> but the problem is it's showing me "code is not exist" error (even if i create the object that matches) ! where is the problem? -
Any ideas how can I export schemas of all the django model's inside a django project into an external format?
I got a requirement from my manager that they require a generic python script that export schemas of all the model present in the django project into excel. Generic because we want to do the same for multiple microservices running on django in our company. Each row in excel is supposed to contain infromation about field in that model. Each model is supposed to be represented in new sheet. I can't seem to figure out what would be a good way to do this. One approach I can think of is using recursion to iterate inside all the files inside the codebase and look for files names like models.py and iterate inside of them to find different classes and extract info like field type, constraints, max length/size, nullable or not, etc. but not sure if this would be a good approach because edge case handling would be hard in the case I think. -
How to change SpectacularSwaggerView's authentication_classes in drf_spectacular?
I have a class that inherits from SpectacularSwaggerView. When I call that view, it shows two authentication methods. basicAuth and cookieAuth. I want to use a custom authentication or maybe use no authentication at all. but when I set authentication_classes attribute like this: class CustomSpectacularSwaggerView(SpectacularSwaggerView): authentication_classes = [ CustomAuthentication, ] it shows the same two authentication methods. How can I change that?