Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting value of certain attribute of a model related to User
I have a model related to User (relationship: OneToOne), in this model I have a field named email_confirmation. I can access to this field but I can't updated it. models.py class Profile(models.Model): profile_user = models.OneToOneField(User, ...) profile_email_confirmation = models.BooleanField(default=False) views.py def mail_confirmation(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) ... if user is not None and account_activation_token.check_token(user, token): user.profile.profile_email_confirmation = True user.save() #This isn't working and doesn't cause any error login(request, user) #This is working return redirect('/home') #This is working This function isn't causing any error so I don't know what is wrong I actually get redirect to /home (logged). I also can access to the field profile_email_confirmation When I check the model in the Admin page, the profile_email_confirmation field has not been altered. -
Django (fields.E304) - AbstractUser
I would like to create new fields in the model of the Django's User system. I am following the official documentation, but I keep getting the same error: My changes so far to the code have been the following: models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): bio = models.TextField(max_length=500,blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) -
How to organize the applications in django project
I getting started with Django. I want to build a work_manager website with the following content: hour calculation - enter shifts per day and can view the hours per day, week and month. shift for each week(maybe a month too) - view table for all the schedules of the employees. salary calculation per employee for month. And maybe in the future more things. For start I have this DB structures: Now, my question is what is the recommended way to organize the project? I searched here and find some people the recommended putting all in one app because strong relations between the models can cause problems if you split into several apps. And some other people recommended to split it that each I can explain each app with one sentence (like I did here up). So, what is the best practice for that? If to split so how to arrange the models? Thank You! -
Issue with django at runserver command
im new in django and i have suposedly a really simple issue which is driving me crazy. once i create superuser and hit the runserver command i go to the http://127.0.0.1:8000/admin/ enter acc and pass and server throws me out. enter image description here on random basis i sucseed in entering the admin panel, but once i get in and press anything it again throws me out and i see the below message enter image description here any ideas how i can fix this? -
How to get my Django template to recognize a model method?
In my django template <p>This user is unsubscribed {{sub.is_unsubscribed}}</p> always displays "This user is unsubcribed False" even when it should show True based on the following models.py from django.shortcuts import get_object_or_404 class Subscriber(models.Model): email = models.CharField(max_length=12) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) create_date = models.DateTimeField(auto_now_add=True) def is_unsubscribed(self): try: get_object_or_404(MasterUnsubscriber, unsubcriber_email=self.email) return True except: return False def __str__(self): return self.email class MasterUnsubscriber(models.Model): unsubscriber_email= models.CharField(max_length=12) And for structural reasons of my app, I do not want to move the unsubscribe to the Subscriber model as a boolean. How can this be resolved while keeping same model formats. -
Image created in views isnt being rendered in template django
Im trying to render a simple graph that i create with matplotlib in my template. I want to render the graph in the body of the page not just return an HttpResponse with that graph. But i cant get it to work. Here is what i tried. views.py code def showGraph(request): content_x = [10, 20, 30] content_y = ['one', 'two', 'three'] plt.bar(content_x, content_y) plt.title('Some chart') plt.show() buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") content_type = "Image/png" buffercontent = buffer.getvalue() graphic = (buffercontent, content_type) plt.close() return render(request, 'projectRelated/LAN/graphs.html', {'graphic': graphic}) html page code {% extends 'base.html' %} {% load static %} {% block container_content %} <img src="data:image/png;base64,{{ graphic }}"> {% endblock container_content %} The above code just displays a random icon.. -
JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?
I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument. How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ? The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/ $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, add: function(e, data) { $.each(data.files, function(index, file) { // pack our data to get signature url var formData = new FormData(); formData.append('filename', file.name); formData.append('type', file.type); formData.append('size', file.size); // Step 3: get our signature URL $.ajax({ url: '/api/getsignedurl/', type: 'POST', processData: false, contentType: false, dataType: 'json', headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, context: 'hello', data: formData, }).done(function (data) { // Step 5: got our url, push to GCS const xhr = new XMLHttpRequest(); if ('withCredentials' in xhr) { xhr.open("PUT", data.signed_url, true); } else if (typeof XDomainRequest !== 'undefined') { xhr = new XDomainRequest(); xhr.open("PUT", data.signed_url); } else { xhr = null; } xhr.onload = () => { const status = … -
How to stop Django PasswordInput prefilling form
I am trying to create a django form to allow users to login. forms.py class LoginForm(forms.ModelForm): username = forms.CharField(label='User name', max_length=30) password = forms.PasswordInput() class Meta: model = User fields = '__all__' widgets = {'password': forms.PasswordInput()} views.py def login_view(request): form_context = {'login_form': LoginForm,} url = "users/login.html" if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) ... else: context = form_context return render(request, url, context) login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ login_form.username.label_tag }}</td> <td>{{ login_form.username }}</td> <td rowspan="2"><button type="submit" class="btn btn-success">Login</button></td> </tr> <tr> <td>{{ login_form.password.label_tag }}</td> <td>{{ login_form.password }}</td> </tr> </table> </form> The problem I have is that if the line widgets = {'password': forms.PasswordInput()} is used, then the form is pre-filled with username and password If the line is commented out, the the form is not prefilled, but the password is in plain text. What is wrong here? -
What do you think about my idea to build my personal finance tracker with Django - too ambitious? [closed]
I would love to have feedback on my idea. Thanks in advance :) First of all: Im relatively new to Python and Programming in general. I did a lot of tutorials, learned the standard syntax and tried out a lot of modules. I feel like I don't learn enough anymore and want to have my first real big project to really get out of the watch-tutorial-flow and really learn the modules by working with them. My idea: A personal finance tracker: I thought about using Django, because i want to learn a popular Web-Framework. I thought about dividing it into different apps: In one app you should be able to input data of the expenses(price, category, automatic timestamp, etc.) that is going to be saved to a database (sqlite) In another app you should have an (interactive) dashboard, that uses the data from the database and plots some graphes etc. optional: User-System to make the Webapp usable for other people Update sqlite to MySQL or other bigger databases Use some API or something to get data from your bank, so you don't need to manually type in the expenses My questions: Is the project too ambitious/to big? As I already … -
Is possible to update or create objects just using django bulk_create
In some cases I need to update existing objects in others I need to create them. It is possible to use a mixed list of updated/created objects to bulk_create() so I don't have to use save() for the updated objects? -
Synchronized Model instances in Django
I'm building a model for a Django project (my first Django project) and noticed that instances of a Django model are not synchronized. a_note = Notes.objects.create(message="Hello") # pk=1 same_note = Notes.objects.get(pk=1) same_note.message = "Good day" same_note.save() a_note.message # Still is "Hello" a_note is same_note # False Is there a built-in way to make model instances with the same primary key to be the same object? If yes, (how) does this maintain a globally consistent state of all model objects, even in the case of bulk updates or changing foreign keys and thus making items enter/exit related sets? I can imagine some sort of registry in the model class, which could at least handle simple cases (i.e. it would fail in cases of bulk updates or a change in foreign keys). However, the static registry makes testing more difficult. I intend to build the (domain) model with high-level functions to do complex operations which go beyond the simple CRUD actions of Django's Model class. (Some classes of my model have an instance of a Django Model subclass, as opposed to being an instance of subclass. This is by design to prevent direct access to the database which might break consistencies and … -
Django generic relations, unique together and abstract models
I have a Tag model and an intermediate model to relate it class Tag(models.Model): name = models.CharField(max_length=255) slug = models.CharField(max_length=255, blank=True) class TagIntermediate(models.Model): # Relation to custom content model content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() customcontent = GenericForeignKey('content_type', 'object_id') # Relation to tag tag = models.ForeignKey(Tag, on_delete=models.CASCADE) class Meta: unique_together = ["content_type", "object_id", "tag"] I add this to an abstract base class class BaseModel(models.Model): blog_tags = GenericRelation('TagIntermediate') class Meta: abstract = True And then I define two models derived from it class ModelOne(BaseModel): model_one_field = models.CharField() class ModelTwo(BaseModel): model_two_field = models.CharField() When I now create a Tag object and add it to a ModelOne object and a ModelTwo object, then I get the message triggered by my "unique together" definition: The combination of content_type, object_id and tag does already exist. Why? ModelOne and ModelTwo should be two different content_types, right? Or did I forget something? I`m using Django Version 3.0.4 -
Displaying data in Django by grouping
Basically, I have worked on this project and I am stuck in displaying the data according to my needs on the html page. Right now all that is shown is the 0-4 data but I'm unsure of how to show it correctly. For the children: I want it to show the user's children. For the timeline: Depending on which child is selected, the timeline table will show the data from the specific child.I want to group the data by age range (the column headers) and then when clicked, it will show the pdfs associated with the current timeline cell. My views file: def timeline(request): timeline = Timeline.objects.all() return render(request, 'timeline.html', { 'timeline': timeline }) My model file: HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) child = models.OneToOneField(Children, on_delete=models.CASCADE) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) My html page: {% extends 'pages/home_page.html' %} {% block content %} <style> .rightMenu { position:relative; … -
Django ModelForm ignores the data supplied via form and saves a an existing record
Here are the files, forms.py from django.forms import ModelForm from .models import * class NewCustomer(ModelForm): class Meta: model = Customer fields = ('name', 'mobile_number', 'email', 'address') Views.py from django.shortcuts import render, get_object_or_404, redirect from .models import * from .forms import * # Create your views here. def customers(request): customers = Customer.objects.all().order_by('id') return render(request, "customers.html", {'customers': customers, 'custactive': "active"}) def customer_details(request, pk): customer = get_object_or_404(Customer, pk=pk) return render(request, "customer_details.html", {'customer': customer}) def new_customer(request): if request.method == 'POST': form = NewCustomer(request.POST) if form.is_valid(): customer = form.save(commit=False) customer.name = request.user customer.mobile_number = request.user customer.email = request.user customer.address = request.user customer.save() return redirect ('customers') else: form = NewCustomer() return render(request, "new_customer.html", {'form': form}) Can someone tell me what's wrong with the code? Understandably I need to save new data that I supply with the form. -
Obtaining the fields using the ListView class from Django
I'm learning to manage the ListView class from django, obtain the data is really easy. from django.views.generic import ListView from .models import Fleet class fleet_bbdd_view(ListView): template_name = 'data_app/fleets-bbdd.html' paginate_by = 20 model = Fleet context_object_name = 'FleetsList' But what I can't find is how to obtain the fields of my model and pass they in my context object. Is possible to do this using the ListView class ? I know how to obtain it, in a normal function, but if it is possible I prefer to use ListView class. def getData(request): cols = [i.name for i in Fleet._meta.get_fields()] ctx = {'Cols':cols} return JsonResponse(ctx) Can somebody help me? Thank you very much. -
My Django is showing me importError am i doing it wrong
i tried running my django project on the Virtual Studio IDE , created a virtualEnv, but it does not import anything from the django framework, it always underline the "from" with red indicators.this is the error message am getting ..please i need your help because i still don't know why its happening -
Passing parent object into CreateView for a child object
I'm creating a dashboard to edit a tour app. Per tour I have a child record in which I define steps. The 2 models look like this: models.py class Tour(models.Model): tour_id = models.CharField(primary_key=True,unique=True, max_length=10) country = models.ForeignKey(Countries, models.DO_NOTHING, db_column='country') language = models.ForeignKey(Language, models.DO_NOTHING, db_column='language') lastupddtm = models.DateTimeField(default=timezone.now) productid = models.CharField(max_length=50) title = models.CharField(max_length=50) description = models.CharField(max_length=100) descrlong = models.CharField(max_length=1000) live = models.CharField(max_length=1) image = models.ImageField(upload_to=upload_tour_image, storage=OverwriteStorage(), blank=True, null=True) class Meta: db_table = 'tour' verbose_name_plural = "tour" def get_language_flag(self): return self.language.flag.url def __str__(self): return str(self.tour_id) + ' - ' + str(self.title) + ' - ' + str(self.description) class Toursteps(models.Model): # tour_id = models.OneToOneField(Tour, models.DO_NOTHING, db_column='tour_id') tour = models.ForeignKey(Tour, related_name='toursteps', on_delete=models.CASCADE) step = models.IntegerField(unique=True) title = models.CharField(max_length=50) description = models.CharField(max_length=100) descrlong = models.CharField(max_length=1000) audiotext = models.TextField() latitude = models.FloatField() longitude = models.FloatField() radius = models.FloatField() image = models.ImageField(upload_to=upload_tour_step_image, blank=True, null=True) class Meta: db_table = 'tourSteps' verbose_name_plural = "tourSteps" def __str__(self): return str(self.tour) + "|" + str(self.step) After I created a Tour, I go to a detail page. From there I can click a link to add a step for this tour. This is where the problem is. I pass the tour_id as a variable into the url, but I can't find a … -
Best way to create models for shopping lists in Django
I am thinking how to create models in Django when designing a shopping list. So basically I want to have Shopping Item and Shopping List. Shoping Item can be added to different shopping lists multiple times. Could you please advise on that? -
Django - 'tuple' object has no attribute 'status_code'
I'm trying to save some data to my database, but I keep getting the error. 'tuple' object has no attribute 'status_code'. I'm not entirely sure where i'm going wrong . Models.py class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() assigned_to = models.CharField(max_length=30) def save(self, *args, **kwargs): self.slug = slugify(self.text) super(Task, self).save(*args, **kwargs) def __str__(self): return self.text Form.py class CreateNewTask(ModelForm): text = forms.CharField(max_length=300, help_text="Please enter task: ") assigned_to = forms.CharField(max_length=30, help_text="Assigned to: ") complete = forms.BooleanField() slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Task fields = ( 'text', 'assigned_to', 'complete') views.py def createTask(request): form = CreateNewTask() if request.method == "POST": form = CreateNewTask(request.POST) if form.is_valid(): temp = form.save(commit=False) temp.board = Board.objects.get(id=id) temp.save() return redirect("/dashboard") return(request, 'boards/create_task.html', {'form':form}) -
Issue with dropdown submitting selected value - Django/Python
I am trying to get the selected value in the dropdown to add to the cart. The way I have it prints out different dropdowns but submits the data into the cart. I just want one dropdown that submits the selected value. Thank you. {% for product in products %} <form class = 'pull-right' method ='GET' action='{% url "update_cart" product.slug 1 %}'> <select id="menulist"> <option>{{ product.name }}: ${{ product.price }}</option> {% endfor %} </select> <button type = 'submit' class ="btn btn-info btn-md" class ='pull-right'>Add To Order</button> </form> -
django.db.utils.ProgrammingError: relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary"
i did everything used python manage.py migrate, etc. But when i click on my model in django admin panel it shows this error. ProgrammingError at /admin/fdiary/fdiary/ relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary" ^ Request Method: GET Request URL: http://127.0.0.1:8000/admin/fdiary/fdiary/ Django Version: 3.0.4 Exception Type: ProgrammingError Exception Value: relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary" ^ Exception Location: J:\Program Files\Python3.8\lib\site-packages\django\db\backends\utils.py in _execute, line 86 Python Executable: J:\Program Files\Python3.8\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Dell\diary\diary', 'J:\Program Files\Python3.8\python38.zip', 'J:\Program Files\Python3.8\DLLs', 'J:\Program Files\Python3.8\lib', 'J:\Program Files\Python3.8', 'C:\Users\Dell\AppData\Roaming\Python\Python38\site-packages', 'J:\Program Files\Python3.8\lib\site-packages'] Server time: Fri, 3 Apr 2020 20:15:51 +0530 Meta:- ALLUSERSPROFILE 'C:\\ProgramData' APPDATA 'C:\\Users\\Dell\\AppData\\Roaming' COLORTERM 'truecolor' COMMONPROGRAMFILES 'C:\\Program Files\\Common Files' COMMONPROGRAMFILES(X86) 'C:\\Program Files (x86)\\Common Files' COMMONPROGRAMW6432 'C:\\Program Files\\Common Files' COMPUTERNAME 'DESKTOP-S6NQ606' COMSPEC 'C:\\Windows\\system32\\cmd.exe' CONTENT_LENGTH '' CONTENT_TYPE 'text/plain' CSRF_COOKIE 'mNHRnYHHB1kzOdnahlwlppBHiLEKYeO0ghFTgshaQGSXzzbS6aU5TI1rnpkWa9vT' DJANGO_SETTINGS_MODULE 'diary.settings' DRIVERDATA 'C:\\Windows\\System32\\Drivers\\DriverData' GATEWAY_INTERFACE 'CGI/1.1' HOMEDRIVE 'C:' HOMEPATH '\\Users\\Dell' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' HTTP_ACCEPT_ENCODING 'gzip, deflate' HTTP_ACCEPT_LANGUAGE 'en-US,en;q=0.5' HTTP_CONNECTION 'keep-alive' HTTP_COOKIE ('csrftoken=mNHRnYHHB1kzOdnahlwlppBHiLEKYeO0ghFTgshaQGSXzzbS6aU5TI1rnpkWa9vT; ' 'sessionid=amcqamjjcw9chtndh5nzib8nfdv8n1yy; ' 'PGADMIN_INT_KEY=fc56bb57-0d57-4b35-8b29-282be1e4197b; ' 'pga4_session=d8dcf70d-50e4-4474-9aef-6e057e2a6216!P0ZEZvLq08QDIa+4HpmE8XSwdWE=; ' 'PGADMIN_LANGUAGE=en') HTTP_DNT '1' HTTP_HOST '127.0.0.1:8000' HTTP_REFERER 'http://127.0.0.1:8000/admin/' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0' LANG 'en_GB.UTF-8' LOCALAPPDATA 'C:\\Users\\Dell\\AppData\\Local' LOGONSERVER '\\\\DESKTOP-S6NQ606' NUMBER_OF_PROCESSORS '4' ONEDRIVE 'C:\\Users\\Dell\\OneDrive' ONEDRIVECONSUMER 'C:\\Users\\Dell\\OneDrive' OS 'Windows_NT' PATH ('J:\\Program Files\\Python3.8\\Scripts\\;J:\\Program ' … -
Unable to find static files - Joined path located outside of base path components
Django noob here. My static files are working fine using my local development server, but as soon as I pushed changes to my production server on A2, it could no longer find my static files. For example, it can't find a js file at: https://mywebsite.com/static/js/jquery.waypoints.min.js The file actually exists at: https://mywebsite.com/project_root/static/js/jquery.waypoints.min.js This corresponds to: /home/user/public_html/project_root/static In my settings.py I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'public') When printed, Staticfile_dirs is /home/user/public_html/project_root/static, which seems right. but once I run python manage.py findstatic js/infinite.min.js It gives me the error django.core.exceptions.SuspiciousFileOperation: The joined path (/js/infinite.min.js) is located outside of the base path component (/home/user/public_html/project_root/static) Can someone help me understand what i'm missing? -
Django forms.ChoiceField to be dynamically created based
Im building a website with django where a user could create a shop > choose maximum one of each category > choose multiple products for each category; in that order I have a DetailView which allows them to see the details of the shop and create a category underneath it. I`m using FormMixin to allow them create a category, and a ChoiceField for the type of category. What I want: Let them choose only from the categories they didnt choose in the past, eg: I have 3 categories: Woodworks, Food, Tools; if they already have added a Tools category to their shop, they should be able to choose it again (i want the form not display it at all) My views: class OrganizationDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView, FormMixin): model = Organization queryset = Organization.objects.all().prefetch_related() template_name = 'org/org_view.html' form_class = CategoryForm def test_func(self): org = self.get_object() if self.request.user.profile == org.owned_by: return True return False def get(self, request, *args, **kwargs): # getting the post to display self.object = self.get_object() context = self.get_context_data() categories = Category.objects.filter(org=self.object).values_list('cat_name') context['categories'] = [] for category in categories: context['categories'].append(*category) return self.render_to_response(context) def post(self, request, *args, **kwargs): pk = self.get_object().serializable_value('pk') org_id = Organization.objects.get(org_id=pk) cat_name = self.request.POST.get('cat_name') new_category = Category.objects.create(org=org_id, cat_name=cat_name) return … -
how to use django template language inside script tag using django-jsRender
As I know, there is no way to use Django template language inside Javascript block so I searched for a way how to do it, I found a Django app on GitHub called Django-jsrender but unfortunately, there isn't enough documentation for this app and when I tried to use it I couldn't and this is my code: -
Django serializer "field is required"
I want a serializer to return all the distinct countries. It just query's the db and returns it. But it always return "field is required" on the "countries" field. This is my serializer: class AdminCountrySiteSerializer(serializers.ModelSerializer): countries = serializers.ListField() class Meta: model = Site fields = ["countries"] def get_countries(self): return list( Site.objects.values_list("country", flat=True) .order_by("country") .distinct() ) test class: def test_get_all_distinct_countries(self): self.client.force_login(self.admin_user) url = reverse("admin-site-countries") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data["countries"]), 3) view: class AdminSiteCountryView(GenericAPIView): def get_permissions(self): return IsAuthenticated(), IsSoundTalksCS() def get_serializer_class(self): return AdminCountrySiteSerializer @swagger_auto_schema( responses={200: openapi.Response(_("Successfully fetched all the countries."),)} ) def get(self, request): """ GET all distinct countries """ serializer_class = self.get_serializer_class() # serializer = serializer_class(data=request.data) serializer = serializer_class(data={"request": request}) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=status.HTTP_200_OK,)