Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django Downloaded xls file is not opening and showing error
This is my code for xls file download. File is downloaded properly, but not opening as you can see in below image. Code for download file is here. views.py def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) Please help me as I am new to django and python. -
How can I set 'or' in two django model fields
Suppose I have a django model of an Image: from django.db import models class Image(models.Model): ... image = models.ImageField(upload_to='some_place') image_url = models.URLField() ... and I want that a user can upload either image or its url so I can not set both field null=True because I want atleast one of them to show in template. How can I do this? -
Reverse accessor clasher with Django
First of all, this is not duplicate question. I saw solution for such question, but it did not work for me. Please assist. I have such model in app: class Company(models.Model): owner = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE, default=None, null=True, blank=True) name = models.CharField(max_length=128, blank=True, null=True, default=None) created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True, blank=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True, blank=True) def create_folder(**kwargs): instance = kwargs.get('instance') print(instance.id) os.mkdir(f"media/company_{instance.id}") def delete_folder(**kwargs): instance = kwargs.get('instance') print(instance.id) full_patch_folder = f"media/company_{instance.id}" if os.path.isdir(full_patch_folder): shutil.rmtree(full_patch_folder) post_save.connect(create_folder, sender=Company) post_delete.connect(delete_folder, sender=Company) class Folder(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=128, blank=True, null=True, default=None) unique_folder_name = models.CharField(max_length=128, blank=True, null=True, default=None) full_path = models.CharField(max_length=256, blank=True, null=True, default=None) parent_folder = models.IntegerField(verbose_name="Parent Folder", blank=True, null=True, default=0) company = models.ForeignKey(Company, verbose_name="Company", on_delete=models.CASCADE, default=None) share = models.BooleanField(verbose_name="Share folder", null=True, default=False) created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True, blank=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True, blank=True) def __str__(self): return "(id.%s) - %s - %s - %s - %s" % (self.id, self.name, self.unique_folder_name, self.share, self.company) and I get below error: apps.Company.owner: (fields.E304) Reverse accessor for 'Company.owner' clashes with reverse accessor for 'Company.owner'. HINT: Add or change a related_name argument to the definition for 'Company.owner' or 'Company.owner'. main.Company.owner: (fields.E304) Reverse accessor for 'Company.owner' clashes with reverse accessor for 'Company.owner'. HINT: Add or change a … -
FormatException: SyntaxError: Unexpected token < in JSON at position 1 in Flutter
I have a project, backend with Django and frontend with Flutter framework. The project was working fine until I changed the proxy in my Nginx from HTTP to HTTPS. Still working in most cases without any Problem. just in some cases, where I have no Data in my Data Table, I want/have to return an empty list from the backend, I got an error: GET https://servername/project-name/api/commitments/?email=emailaddress%40companyname.de&jahr=2022&kunde=adac-ev 500 FormatException: SyntaxError: Unexpected token < in JSON at position 1 code in flutter: var uri = (APIPROTOCOL == 'http://') ? Uri.http(APIHOST, '/api/commitments/', uriQuery) : Uri.https(APIHOST, '$APIHOST_PREFIX/api/commitments/', uriQuery); try { final response = await http.get( uri, headers: {"Authorization": "Bearer $authToken"}, ); And this is working on localhost and on a server with HTTP but the problem is only on a sever with HTTPS, any idea? how can debug the code on the server? or how can I change my localhost from http:://localhost:protNumber/ to something like https://myweb/myapp/. Any idea that could help me to debug the code with https? -
Celery 'update_status' function is not working
I am using celery and django-celery-results in my Django application. My celery results are being stored in the backend and this is what celery.py looks like. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shoonya_backend.settings") # Define celery app and settings celery_app = Celery( "shoonya_backend", result_backend="django-db", accept_content=["application/json"], result_serializer="json", task_serializer="json", ) celery_app.config_from_object("django.conf:settings", namespace="CELERY") celery_app.autodiscover_tasks() I am trying to update the state of a task from within the celery function if I get an exception as follows. try: result = resource.import_data(imported_data, raise_errors=True) # If validation checks fail, raise the Exception except Exception as e: self.update_state( state=states.FAILURE, meta={ "exc_type": type(e).__name__, "exc_message": traceback.format_exc().split("\n"), }, ) The following command doesn't result in any change in the TaskResult table even when the exception is raised and the Task is always a success. -
'QuerySet' object has no attribute 'videos_set'
i am trying to get all the videos related to a curriculum, i have tried curriculum.videos.all but it return this error that says 'QuerySet' object has no attribute 'videos', i also tried using curriculum.videos_set.all then it shows the same error but this time with a 'QuerySet' object has no attribute 'videos_set'. what can be the issue with this problem? models.py class Course(models.Model): course_title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True) course_thumbnail = models.ImageField(upload_to=user_directory_path, blank=True) class Curriculum(models.Model): course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="curriculum") title = models.CharField(max_length = 100 , null = False) slug = models.SlugField(unique=True) def __str__(self): return f'{self.course.course_title} - {self.title}' class Video(models.Model): title = models.CharField(max_length = 100 , null = False) curriculum = models.ForeignKey(Curriculum , null = False , on_delete=models.CASCADE, related_name="videos") serial_number = models.IntegerField(null=False) video_id = models.CharField(max_length = 100 , null = False) def __str__(self): return self.title Now this is the view that i have written for it View.py # @login_required def course_details(request, course_slug): if request.user.is_authenticated: user = request.user course = Course.objects.get(slug=course_slug) curriculum = Curriculum.objects.filter(course=course) serial_number = request.GET.get('lecture') videos = curriculum.videos_set.all().order_by("serial_number") ... -
Why to use the extra slash (/) at the end of the Django urls?
I'm trying to create a REST API using Django. I'm currently implementing the urls.py file. In a lot of different examples, I saw that they add / at the end of the url. For example: urlpatterns = [ path('login/', obtain_auth_token, name='api_token_auth'), ] I'm trying to figure way. Surely for login POST request which returns a token (given username and password), you want to access <domain>/api/login and not <domain>/api/login/. Currently I solved it with: urlpatterns = [ re_path(r'login$', obtain_auth_token, name='api_token_auth'), ] Or: urlpatterns = [ path('login', obtain_auth_token, name='api_token_auth'), ] But what is the convention? Why a lot of different examples add the extra / at the end? When do you want to add it? -
Django Multi-table inheritance - get parent object
How can I get the parent object from the child object in Multi-table inheritance? class Property(Model): .... class Meta: abstract = False #!!! class Flat(Property): .... flat = Flat.objects.first() flat.property >>> AttributeError: 'Flat' object has no attribute 'property There is a flat.property_ptr_id which I guess I could use but I'm curious if there is a more elegant/built-in way to do that. Btw. I know I can access all the fields from the child object. I'm working on methods like create_child, convert_child_type. -
How to create a pagination for a dataframe?
I want to create a pagination system for my dataframe. I always create pagination with my queries but It doesn't work in dataframe. I cannot display on my template. This is my views.py def get_context_data(self, **kwargs): ... df = pd.DataFrame(list(Case.objects.all().values(...))) query = df.assign(cnt=1).groupby([...)['cnt'].sum().reset_index() paginator = Paginator(query, 10) page_number = self.request.GET.get('page') if page_number == None: page_number = 1 page_obj = paginator.page(int(page_number)) print(page_obj) ----> <Page 1 of 33> context['query'] = query return context And this is my template <table class="table table-bordered" > <tbody> {% for index, row in query.iterrows %} <tr> {% for cell in row %} <td> {{cell}} </td> {% endfor %} </tr> {% endfor %} </table> Table shows nothing. How can I solve that? -
Django. How to create model instance in test db using objects fabric?
I want to make my unit tests setUp function clear from repeating tons of model creation lines like 1) create user 2) now create employee with fk to this user and etc. In order to do that I've made a simple factory of dummy objects but I might've done some mistakes or just misunderstood something. Here's a piece of factory (dummy_data is just a bunch of dicts): from abc import ABC from users.models import User from employees.models import Employee from .dummy_data import( user_data, employee_data, ) class DummyObjectFactory(ABC): """Fabric representing dummy test objects""" def get_dummy_object(self): """Return dummy object""" class DummyUser(DummyObjectFactory): def get_dummy_object(self) -> User: return User.objects.create_user(**user_data) class DummyEmployee(DummyObjectFactory): def get_dummy_object(self) -> Employee: user = DummyUser().get_dummy_object() return Employee.objects.create(**employee_data, user=user) Then I make a dot notaion dictionary of all kinds of fabrics for easy calling them buy dummy_factory.Name . My intetion was that I call fabric with the desired model name and it creates it's instance. The problem is: when I call it in some test's setUp method like so test_user = dummy_factory.User it creates object in actual database but I want it to be in test database. Yes, I've searched for the solution and found Factory boy and Faker libraries, but I … -
Colour code the rows in CSV file in my react-django project
I have an application running with react as the front end and Django at the backend. I want to make a download button where my panda data frame can be exported to Excel/CSV file with colour coded format in the downloaded CSV. Currently, i am using below code to download the file which is working but it gives me just the excel with data import { CSVLink } from "react-csv"; <CSVLink data={data} filename={"my-file.csv"} className="btn btn-primary" target="_blank" > Download me </CSVLink>; -
HTML: show different sized tables on the same page depending on the user's choice
Is it possible to implement two different sized tables where only one would be displayed on the page depending on the user's choice? E.g.: user chooses data table which has the following columns: country, price, date, so 3 columns would be displayed. Then the user chooses the users table with columns: name, email, so now 2 columns would be displayed. -
Django Make read only field
I write this code for making the readonly filed, but the problem after saving the page is it make all the columns read only . I want to make the if the filled has some value then that row will become readonly not all of them my code def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ("name", "id") return self.readonly_fields -
How can I change the database time-out period in django?
I have django script which fetch the data from model. try: myuser = MyUser.objects.get(id=user_id) except Exception as e: print(e) # do next process Then, what I want to do is ,,, When database is stopped or not reached, I want to catch and do next process. However my program return the 502 immediately, because it reachs to the aws lambda's timeout. 2022-06-23 19:09:51 127.0.0.1 - - [23/Jun/2022 19:09:51] "POST /webhook HTTP/1.1" 502 - Function 'MyDjangoFunction' timed out after 300 seconds No response from invoke container for MyDjangoFunction Invalid lambda response received: Lambda response must be valid json So, my idea is set django - sql timeout shorter. Is there any good method?? -
Problem in panel of Django3.0 after migrations
why is the error appearing in django/admin? Migrations ok, I need to have 3 items in the table where I will have results. Thx for your help. class Robot(models.Model): """Robot model, speed and position simulation""" product = models.IntegerField(choices=CHOOSE) velocity = models.FloatField() positionX = models.FloatField() positionY = models.FloatField() angleTHETA = models.FloatField() class Meta:`enter code here` verbose_name = "Robot" verbose_name_plural = "Robots" def __str__(self): resum = self.get_product_display() return resum ProgrammingError at /admin/robot/robot/ column robot_robot.velocity does not exist LINE 1: ...LECT "robot_robot"."id", "robot_robot"."product", "robot_rob... -
id_username showing up in django form without reason
Im looking for some help with my custom user model. For whatever reason I cannot understand the field id_username pops up after clicking on the submit button. This field is missing from the form which I have cut down to {{ form.as_ p }} in the html urls.py path('login/', LoginView.as_view(template_name="registration/login.html"), name='login'), forms.py class LoginForm(forms.Form): email = forms.EmailField(label='Email', widget=forms.TextInput(attrs={'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) views.py class LoginView(FormView): form_class = LoginForm success_url = '/about/' template_name = 'registration/login.html' def form_valid(self, form): request = self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=email, password=password) if user is not None: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/about/") return super(LoginView, self).form_invalid(form) models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, help_text='Email Address' ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email ... etc ... @property def is_active(self): "Is the … -
Django - How to include form field logic in modelForm and not in a Createview, so that form can be unittested without also testing the view?
I have a Campaign Model, and a CampaignCreateForm which is a ModelForm. The Campaign model has a contact_list field of type JSONField. When a user is creating a campaign using the CampaignCreateFormthey upload a CSV file which is processed to create the JSON data for thecontact_list` field. What is the best way to approach this so that I can test the form separately from the view? I've built this using a CampaignCreateView which inherits from CreateView, and included the logic to parse the CSV file and create the JSON data in the views form_valid method, but this makes unit-testing the form (and any form field validation) impossible. I want to test the functions included in the forms clean method. With my current approach the view and form must be tested together, and that feels wrong. How can I create the form such that all the logic for the form (processing the CSV file to create the JSON data and discarding the uploaded file) is handled in the form only? My current CreateView and ModelForm are below: View: class CampaignCreateView(LoginRequiredMixin, CreateView): model = Campaign form_class = CampaignCreateForm # required if you want to use a custom model form, requires `model` also … -
Apps aren't loaded yet - Django, Gunicorn, Docker
I am trying to run my django project using gunicorn in docker. It worked perfectly while I used regular python manage.py runserver 0.0.0.0:8000 command. They I switched to using gunicorn command: command: > sh -c "export DJANGO_SETTINGS_MODULE='clubhouse.settings' && gunicorn clubhouse.wsgi" And now I have this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. docker-compose.yml version: '3.8' services: postgres: image: postgres ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=clubhouse - POSTGRES_DB=clubhouse - POSTGRES_PASSWORD=secret redis: image: redis restart: always ports: - '6379:6379' command: redis-server --save 20 1 --loglevel warning --requirepass eYVX7EwVmmxKPCDmwMtyKVge8oLd2t81 volumes: - redis:/data api: build: context: . dockerfile: Dockerfile command: > sh -c "export DJANGO_SETTINGS_MODULE='clubhouse.settings' && gunicorn clubhouse.wsgi" volumes: - .:/code ports: - '8000:8000' env_file: - ./.env depends_on: - postgres - redis volumes: postgres_data: redis: full log: Starting clubhousebackend_redis_1 ... done Starting clubhousebackend_postgres_1 ... done Starting clubhousebackend_api_1 ... done Attaching to clubhousebackend_postgres_1, clubhousebackend_redis_1, clubhousebackend_api_1 postgres_1 | postgres_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_1 | postgres_1 | 2022-06-23 09:41:37.225 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit postgres_1 | 2022-06-23 09:41:37.225 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2022-06-23 09:41:37.225 UTC [1] … -
Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380
I'm trying to run this command docker-compose run --rm app sh -c "flake8", but it fails with the following error: Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/bin/bash": stat /bin/bash: no such file or directory: unknown Dockerfile content: FROM python:3.9-alpine3.13 LABEL maintainer="dsha256" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ &DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="py/bin:&PATH" USER django-user docker-compose.yml content: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > - sh -c "python manage.py runserver 0.0.0.0:8000" Any ideas to fix it? Thanks! -
How to find year-on-year growth from a query?
I have a dict type object in my Django app. I want to calculate Year-on-year growth(%) for every month. And the calculation for that is Percentage Growth in Cases Number compared to the previous year. And this is my data: <QuerySet [{'date_created__year': 2018, 'count_case': 1335}, {'date_created__year': 2019, 'count_case': 3469}, {'date_created__year': 2020, 'count_case': 3585}, {'date_created__year': 2021, 'count_case': 2589}, {'date_created__year': 2022, 'count_case': 144}]> I'm trying to create a template tag for that. @register.filter(name='get_yoy_query') def get_yoy_query(val,query): yoy = ? return yoy And in the template: {% for case in query_trend %} <td>{{case.count_case|get_yoy_query:query_trend}} %</td> {% endfor %} -
Django mptt Multiple references to class objects
I need to make a model for spices. Some spices may consist of others, or be basic. I need something like TreeForeignKey with multi-select option. I tried to use TreeManyToManyField, but I can't set null for base spices there. Here is my code: class Goods(MPTTModel): category = models.ForeignKey(Category, related_name='goods', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150, db_index=True) parent = TreeManyToManyField( 'self', blank=True,) -
Mongo Aggregate - Match condition only on second collection but provide all documents from the first
Basically, I have 2 collections in my Mongo DB -> Books , Scores. Books { "BOOK_ID" : "100", "BOOK_NAME" : "Book 1", "BOOK_DESC" : "abcd", }, { "BOOK_ID" : "101", "BOOK_NAME" : "Book 2", "BOOK_DESC" : "efgh", }, { "BOOK_ID" : "102", "BOOK_NAME" : "Book 3", "BOOK_DESC" : "ijkl", } Scores { "BOOK_ID" : "100", "BOOK_CATEGORY" : "kids", "BOOK_SCORE" : "6", }, { "BOOK_ID" : "100", "BOOK_CATEGORY" : "Educational", "BOOK_SCORE" : "8", }, { "BOOK_ID" : "101", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : "6", } { "BOOK_ID" : "101", "BOOK_CATEGORY" : "Fantasy", "BOOK_SCORE" : "7", } Expected output : Searching for all books with BOOKS_CATEGORY="Kids" and BOOKS_SCORE=6 { "BOOK_ID" : "100", "BOOK_NAME" : "Book 1", "BOOK_DESC" : "abcd", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : 6 }, { "BOOK_ID" : "101", "BOOK_NAME" : "Book 2", "BOOK_DESC" : "efgh", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : 6 }, { "BOOK_ID" : "102", "BOOK_NAME" : "Book 3", "BOOK_DESC" : "ijkl", } Notice that, for all the books to which scores are available, they are appended. If a Book does not have any score associated, it still comes in the result. What I have tried? I have tried using $lookup pipeline = [ { "$lookup": { "from": "Scores", … -
Huge discrepancy between access.log, Google Analytics and Mapbox Statistics
I have a website made in django and served using gunicorn in which a single Mapbox map is loaded on the home page using mapbox-gl.js. Users can then navigate the map and change styles at will. The map is initialized and loaded only once and only in the home page. The service is billed on a "map load" basis. The Mapbox pricing page says A map load occurs whenever a Map object is initialized, offering users unlimited interactivity with your web map. I would have expected to see a count, if not exactly identical, at least comparable between the data recorded by Mapbox billing, the accesses to the home page recorded by Google Analytics and the hits on the home page recorded on the server access.log. Instead, the Mapbox count is in average about 25 times higher than Analytics and the access.log, which have similar numbers. As an example, here are the numbers for yesterday: Analytics: home page was loaded 890 times access.log: 1261 requests for the home page Mapbox: 23331 map loads I am using URL restriction from the Mapbox control panel, but I guess the enforcement is not that strict, since they strongly suggest to also rotate the … -
Pass array data through AJAX and get in python file(views.py)
I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing. display.html var SelectedID = []; function getvalues() { $(':checkbox:checked').each(function (i) { SelectedID[i] = $(this).val(); $.ajax({ url: "{% url 'display' %}", type: "POST", dataType: "json", data:{ SelectedID : SelectedID[i], csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { alert("Successfully sent the Data to Django"); }, error: function (xhr, errmsg, err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); }); } views.py def display(request): is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest' if is_ajax and request.method == "POST": SelectedID = request.POST.get('SelectedID') print(SelectedID) return render(request, 'display.html',{}) SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing. -
How to filter queryset based on serializer field?
How to filter queryset based on query parameters and dynamically calculated serializer field? What i need: filter GET request output by payment_min and payment_max query parameters. In simple cases we can perform all filtering via annotation, but I have not found a way run custom function on each queryset element. My model class MortgageOffer(models.Model): bank_name = models.CharField( 'Наименование банка', max_length=200, unique=True, ) term_min = models.PositiveIntegerField( 'Срок ипотеки, ОТ', ) term_max = models.PositiveIntegerField( 'Срок ипотеки, ДО', ) rate_min = models.DecimalField( 'Ставка, ОТ', max_digits=4, decimal_places=2, ) rate_max = models.DecimalField( 'Ставка, ДО', max_digits=4, decimal_places=2, ) payment_min = models.PositiveIntegerField( 'Сумма кредита, ОТ', ) payment_max = models.PositiveIntegerField( 'Сумма кредита, ДО', ) class Meta: verbose_name = 'Ипотечное предложение' verbose_name_plural = 'Ипотечные предложения' My serializer class MortgageOfferFilteredSerializer(serializers.ModelSerializer): payment = serializers.SerializerMethodField() class Meta: model = MortgageOffer fields = '__all__' def get_payment(self, obj): return calculate_payment( int(self.context['request'].query_params['price']), int(self.context['request'].query_params['deposit']), int(self.context['request'].query_params['term']), float(obj.rate_max), ) My viewset class MortgageOfferViewSet(viewsets.ModelViewSet): http_method_names = ['post', 'patch', 'get', 'delete'] filter_backends = (DjangoFilterBackend,) filterset_class = MortgageOfferFilter def get_queryset(self): return MortgageOffer.objects.all() def get_serializer_class(self): if self.action in ('create', 'update', 'partial_update'): return MortgageOfferWriteSerializer elif self.action in ('retrieve', 'list'): if self.is_filter_request(): return MortgageOfferFilteredSerializer return MortgageOfferReadSerializer return super().get_serializer_class() def is_filter_request(self): return (self.request.query_params.get('price') and self.request.query_params.get('deposit') and self.request.query_params.get('term'))