Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - limit chooses based on the user
i need to limit the staff chooses base on the user who logged in because the staff created from the user my view is CreateView and i put the user on all models as ForignKey -
GeoDjango can't find gdal on docker python alpine based image
I am creating a geodjango container (based on Python alpine official image) with gdal. When starting the container, I get the following error: >>> from django.contrib.gis import gdal Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/li... django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. my image contains following gdal libs: # find / -name libgdal* /usr/lib/libgdal.so.20 /usr/lib/libgdal.so.20.5.0 /usr/lib/libgdal.a /usr/lib/libgdal.so Adding GDAL_LIBRARY_PATH='usr/lib/libgdal.so.20' to my django settings didn't solve this problem. My Dockerfile, based on official python3 alpine image. FROM python:alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /usr/src/dbchiro COPY requirements.txt /usr/src/dbchiro # GeoDjango Dependencies RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/testing" > /etc/apk/repositories \ && echo "http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories \ && echo "http://dl-cdn.alpinelinux.org/alpine/edge/main" >> /etc/apk/repositories \ && apk add --virtual .build-deps zlib-dev jpeg-dev gdal-dev musl-dev postgresql-dev\ alpine-sdk libffi-dev jpeg-dev python-dev zlib-dev libffi gcc \ && apk add --no-cache postgresql-libs geos gdal postgresql-client libpq proj nginx \ && python3 -m pip install --upgrade pip --no-cache-dir \ && python3 -m pip install -r requirements.txt --no-cache-dir \ && python3 -m pip install gunicorn --no-cache-dir \ && apk --purge del .build-deps COPY docker-entrypoint.sh /usr/bin/docker-entrypoint.sh COPY … -
Best practice for creating and maintaining multiple Python scripts on a server
I have a Ubuntu server with multiple Python scripts. They all run at different times of the days and access our Django database to store values they retrieve from other processes(file scraper for example to save row entries in our DB). Right now we run all our scripts using cron but I wanted to know what the best practice of method of implementing this would be? I was hoping on being able to set it up as a service and have it send out emails if any of the scripts crash and along with that, if they do then auto restart them. Is cron the best way or are there better methods? -
Django "NameError: name 'CarImageForm' is not defined" for self-referencing forms
I'm following this tutorial to create an object creation formset. The goal is to allow multiple images connected to a car object via Foreign object, to be uploaded in a single form. The images use a formset that has one image per field, with as many 'add another image' fields dynamically created. Running the server raises this error: "NameError: name 'CarImageForm' is not defined" when self-referencing the class which encloses the definition. I've looked through the code and found a few minor corrections, but none seem to solve this. forms.py from django.forms import ModelForm, ImageField, CharField, TextInput from .models import Car, Image, CustomUser from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UserChangeForm from django.forms.models import inlineformset_factory from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field, Fieldset, Div, HTML, ButtonHolder, Submit from .custom_layout_object import Formset class CarImageForm(ModelForm): class Meta: model = Image exclude = () CarImageFormSet = inlineformset_factory( Car, Image, form=CarImageForm, fields=['car', 'image'], extra=1, can_delete=True ) class CreateCarForm(ModelForm): class Meta: model = Car exclude = ['seller'] def __init__(self, *args, **kwargs): super(CarCreateForm, self).__init__(*args, **kwargs) ... ) ) Models.py (with irrelevant parts omitted) class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True) car_model = models.CharField('Model', max_length=50, null=True) description = models.TextField(max_length=4000) vin = models.CharField('VIN', max_length=17, help_text='Enter the 17 character … -
Integrating an existing Database in MongoDB with Django Using Djongo
I am new to the Djongo and MongoDB framework. I have an existing collection(collection1) which I am trying to integrate with a Django App (the Django app-app1 had model1 with the same attributes as collection1). I followed the instructions in the official Djongo documentation (Zero-Risk procedure). However, I am unable to view the contents of the "__schema__" collection, using the "db.__schema__.find()" command from the mongo shell. This is the error: E QUERY [js] uncaught exception: TypeError: db.__schema__ is undefined : Is there another way to view the contents of the schema? Also, I am trying to update the app1_model1 collection created automatically with the contents of collection1. Is there a clean way to do this? Alternatively, is there a better way to access the contents of an existing mongodb collection using Django+Djongo? -
"Could not load the image" from Django's media folder
I'm trying to display an image from a database (SQLite, Django3.7). These images are stored in root/media/pictures. models.py class News(models.Model): news_id = models.AutoField(primary_key=True, editable=False) news_img = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] ) urls.py urlpatterns = [...] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I've try to insert the path in the var in the following methods: template.html {% for news_f in news_f%} <div> <img src="{{ media }}{{news_f.news_img}}"> </div> {% endblock %} and {% for news_f in news_f%} <div> <img src="{{news_f.news_img.url}}"> </div> {% endblock %} When I inspect the element in the browser, I get the correct path to the file. <img src="/media/pictures/file.svg"> But it isn't displayed in the HTML: Could not load the image -
Django Model - how to tell Django to look for a customized ID instead of the default
I have two tables, Team and Voting. For my Team table, I'm using a customized ID called "id". In my Voting table, I have a foreign key named "team" to refer to the Team table. I'm also making that "team" attribute a primary key. The problem is that when I go to the registered route for the Voting table, it gives me an attribute error "Team' object has no attribute 'team_id" I assume it's because by default Django is looking for an ID called "team_id" in my Team table instead of my customized ID called "id". How do I solve this? model.py from django.db import models class Team(models.Model): id = models.CharField(max_length=15, default="", primary_key=True) name = models.CharField(max_length=30) class Voting(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, primary_key=True) thumbUp = models.IntegerField(default=0) thumbDown = models.IntegerField(default=0) -
Django forms - How to change form data with HTML DOM?
I am trying to change a Django form's data by using document.getElementById("id_role").innerHTML = "developer". The CustomUser model has a "role" field that is referenced in the function. By testing the output (with the displayField() function, it appears that document.getElementById("id_role").innerHTML actually references all of the available fields ("choices" given in the models.py). The goal is for the second function, changeField(), to change the selected data on the form (my goal isn't to change the database's stored data at this point, just the selected form's input). My question: How do I use document.getElementById().innerHTML to access the specific value that is shown in the form, instead of all of the options for the field? models.py TECH_OPTIONS = ( ('developer','DEVELOPER'), ('manager','MANAGER'), ('testing','TESTING'), ) class CustomUser(AbstractUser): career = models.CharField(max_length=30) role = models.CharField(choices=TECH_OPTIONS,blank = True, max_length=30) def __str__(self): return self.username html page {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <h1 id="testTag">{{user.username}}'s Info</h1> <input onclick="displayField(); changeField();" type="submit" name="" value="TESTING"> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Save" /> </form> <script type="text/javascript"> function displayField(){ var myFormFields = document.getElementById("id_role").innerHTML document.getElementById("testTag").innerHTML = myFormFields; } function changeField(){ document.getElementById("id_role").innerHTML = "developer" } </script> {% endblock %} -
How to create PDF from HTML if the elements are dragged in Django
I am creating PDF documents from html using Django framework. Library I use for this is WeasyPrint. The problem arises when I need to create a PDF from HTML where elements have been dragged from places which they have in the template. The PDF that is created always remains the same, as if the elements were never moved. I tried scraping using Beautifulsoup. But I quickly realized that this was not the solution. Does anyone have an idea which technique to use. Just a suggestion in which direction to look. -
Every field in Django modelform shows "Select a valid choice. That choice is not one of the available choices."
I've already read many other threads complaining about this error message but I still can't figure this out. I try removing the fields that give the error, and the error message just moves to another field the next time I try to submit. They are CharField, Foreign Key, and other types. forms.py class TemporaryresponseForm(forms.ModelForm): gender_custom = forms.CharField( required=False, label="", ) ethnicity = forms.ModelChoiceField( queryset=Ethnicity.objects.all(), widget=forms.RadioSelect(), empty_label=None, required=True, label="Which of the following best describes your ethnicity?" ) ... class Meta: model = Temporaryresponse fields = [...'gender_custom', 'ethnicity',...] views.py def tr(request): if request.method == "POST": form = TemporaryresponseForm(request.POST) if form.is_valid(): tempresponse = form.save(commit=False) tempresponse.ip = "123456" tempresponse.save() return redirect('politicalpollingapp/index.html') else: form = TemporaryresponseForm() return render(request, 'politicalexperimentpollapp/tr.html', {'form': form}) def nr(request, pk): return render(request, 'politicalexperimentpollapp/nr.html', {'tempresponse': tempresponse}) tr.html template {% extends 'politicalexperimentpollapp/base.html' %} {% block extrahead %} {% load crispy_forms_tags %} {{ form.media }} {% endblock extrahead%} ... <form method="POST"> {% csrf_token %} {{ form.as_p }} <div><br></div> <div class="text-center"><button type="submit" class="save btn btn-primary">CONTINUE</button></div> </form> .. models.py class Ethnicity(models.Model): ethnicity = models.CharField(max_length=200) def __str__(self): return '%s' % (self.ethnicity) ... class Temporaryresponse(models.Model): birth_year = models.PositiveIntegerField() voting_registration = models.ForeignKey(Voting_registration, models.SET_NULL, null=True) party_identification = models.ForeignKey(Party_identification, models.SET_NULL, null=True) gender = models.ForeignKey(Gender, models.SET_NULL, null=True) gender_custom = models.CharField(max_length=200, blank=True) ethnicity … -
How to get list of checked checkboxes in django?
Here, 'arr' is a list passed from a previous view. The values(string type) of this list along with the check boxes are successfully being displayed. <form action="{% url 'prec' %}" method="post"> {% for link in arr %} <input type="checkbox" name="checks[]" value="{{link}}" />{{link}}<br> {% endfor %} <input type="submit" value="Submit"> </form> In views function, I create a list of the fields/boxes checked by the user. (views.py): def prec(request): if request.method == 'POST': var = request.POST.getlist('checks[]') return render(request, 'Link5_prec.html', {'variables':var}) Then, in another template, I want to display the values checked by the user(along with the index of that checkbox like [0,2,3]). But nothing is being displayed. (Link5_prec.html): {% for v in variables %} <h1>{{v}}</h1> {% endfor %} Also, if possible, in the first template, I want to make a checkbox of all the elements in the 'arr' list except the last element. -
How to call specific fields from models.py in the views.py in Django
I want to add a message after a successful form submission, with parts of the message involving parameter values from the apps model. I have tried using method as follows: views.py: class ApplyView(FormView): template_name = 'vouchers/apply.html' model = Voucher form_class = VoucherApplyForm def form_valid(self, form): self.code = form.cleaned_data['code'] now = timezone.now() Voucher.objects.filter(code__iexact=self.code, valid_from__lte=now, valid_to__gte=now, usage_limit=3, active=True) form.apply_voucher() return super(ApplyView, self).form_valid(form) def get_success_url(self, voucher_id): voucher = Voucher.objects.filter(pk=voucher_id) discount_value = voucher.value discount_type = voucher.get_type_display messages.add_message(self.request, messages.INFO, "Congratulations! You've successfully redeemed %s" " %s off the selected item(s)." % ( discount_value, discount_type, )) return reverse('vouchers:apply', kwargs={'voucher_id': self.kwargs['voucher_id']}) urls.py: urlpatterns = [ path('<int:pk>/', views.VoucherDetailView.as_view(), name='detail'), path('<int:voucher_id>/apply/', views.ApplyView.as_view(), name='apply'), ] However, I received a TypeError: return HttpResponseRedirect(self.get_success_url()) TypeError: get_success_url() missing 1 required positional argument: 'voucher_id' Your help is much appreciated. Cheers! -
How can I get the absolute url in save model method DJANGO?
i have this model and I need to get the absolute url in the save() method to perform some http requests, how can I get it ? now I'm using the local address. def save(self, *args, **kwargs): super(Annotation, self).save(*args, **kwargs) id = self.shot.id #FIX THIS url = "http://0.0.0.0:8000/api/annotation?shot_id="+str(id) response = urllib.request.urlopen(url) str_response = response.read().decode('utf-8') obj = json.loads(str_response) -
Using Django with React
Does it matter if i do React in its own “frontend” Django app: load a single HTML template and let React manage the frontend or Django REST as a standalone API + React as a standalone SPA? planning to deploy a web app in the future -
How to Create Multiple Modal Dynamically in a Single Page
I am doing a Django Blog Project and it fetch all Blogs from the Database and show Blog Title in User Profile only. I want to create Bootstrap Modal for each Blog that is shown in the profile. Whenever a User click on a Title, the Modal will appear with Details. {% for blog in blogs.all %} <div class="card mb-4 shadow-sm "> <p class="card-text "><h2>{{ blog.title }}</h2></p> <div class="card-body"> <div class="btn-group"> <!-- Open a Modal for the blog --> <!-- Button To Implement the Modal--> <button id = "modalToggle" type="button" class="btn btn-sm btn-outline-secondary" data-toggle="modal" data-target="#modal">View More</button> <!-- Modal --> <div class="modal fade" id="modal" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{ blog.title }}</h4> </div> <div class="modal-body"> <p>{{ blog.body }}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div> </div> Here all Blogs are showing the Modal of the first one. I cannot create multiple modals for each Blog. -
Django ModelChoiceField auto select views passed value
I have a simple problem with ModelChoiceField , I have a Classification class with four fields (name, price1, price2, price3) , I added an edit button and its working perfectly , i added the name on edit page as a ModelChoiceField , My problem is that am trying to force select the name value when edited so the user will only be able to change prices values . I read the doc about ModelForm which led me to this https://docs.djangoproject.com/en/2.2/ref/forms/api/#django.forms.Form.initial I tried initial= but it did not worked as i though it would. Any idea of either dynamically select the value or just print the name without allowing the user to change it would be great . here is my code , views.py def edit_class(request, name): classifications = Classification.objects.all() devices = Devices.objects.all() inst = Classification.objects.get(name=name) if request.method == 'POST': classification = EditClassForm(request.POST, instance=inst) if classification.is_valid(): classification.save() return redirect("/classifications.html") else: classification = EditClassForm() return render(request, 'classifications.html', {"form": classification, "classifications": classifications, "devices": devices}) forms.py class EditClassForm(forms.ModelForm): class Meta(object): model = Classification fields = ("name", "price1", "price2", "price3") def __init__(self, *args, **kwargs): super(EditClassForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.ModelChoiceField(queryset=Classification.objects.all(), initial=0) self.fields['name'].widget.attrs.update({'class': "form-control"}) self.fields['price1'].widget.attrs.update({'class': "form-control", 'value': 0}) self.fields['price2'].widget.attrs.update({'class': "form-control", 'value': 0}) self.fields['price3'].widget.attrs.update({'class': "form-control", 'value': 0}) … -
Django Query Models Based Time and ForeignKey Value
I need help with querying Django objects. I have 3 models: Building, Map, and Report. A single building can have many maps. A single map can have many reports. Given the name of a building I would like to find the most recent report for each floor. That is, I want a list of Reports where each report has a different floor and each report is the most recent report for that floor. class Building(models.Model): building_id = models.AutoField('BID', auto_created=True, primary_key=True) name = models.CharField('Name', max_length=128) class Map(models.Model): map_id = models.AutoField('MID', auto_created=True, primary_key=True) building_id = models.ForeignKey(Building, on_delete=models.CASCADE, default=1) floor = models.CharField('Floor Number', max_length=128) class Report(models.Model): report_id = models.AutoField('RID', auto_created=True, primary_key=True) map_id = models.ForeignKey(Map, on_delete=models.CASCADE, default=1) building_id = models.ForeignKey(Building, on_delete=models.CASCADE, default=1) created_date = models.DateTimeField(auto_now_add=True) I have some pseudo-code below, but there must be an easier way using Django filters. Any ideas? name = "Mall" # All of the buildings reports reports = Reports.filter(building_id__name= name) floors_seen = [] latest_reports = [] for report in reports: floorNumber = report.map_id.floor_num if floorNumber not in floors_seen: floors_seen.append(floorNumber) latest_reports.append(report) else: for latest_report in latest_reports: if latest_report.map_id.floor_num == floorNumber: if report.created_date > latest_report.created_date: latest_reports.remove(latest_report) latest_reports.append(report) -
Direct assignment to the forward side of a many-to-many
I am trying to assign value to a ManyToManyField, however, any attempt I make to set a value on the db fails. Below is my simplified models.py class AppointmentRequest(models.Model): my_name = models.TextField(default='') requester_name = models.TextField(default='') meeting_date = models.TextField(default='') class CustomUser(AbstractUser): firstname = models.TextField(default='') appointments = models.ManyToManyField(AppointmentRequest) Below is the function in views.py that handles some functionality: from .models import AppointmentRequest def book_appointment(request, template_name) apt_request = AppointmentRequest() apt_request.requester_name = requesting_user apt_request.meeting_date = date apt_request.save() update_user.appointments = apt_request update_user.save() With the above I get the following error Direct assignment to the forward side of a many-to-many set is prohibited. Use appointments.set() instead. However, if I use set instead of =, I get the following error django manytomany 'str' object has no attribute 'set'. I am not sure what the problem is. Please help. -
Is it possible to create multiple model instances from a list of lists derived from another model?
I have two models, RecurringEvent and Event. The RecurringEvent models basic purpose is to create a list of datetimes, that is then to be used to create multiple events in the Event model. I have tried the save method with a for loop. However, no new Events are created, nor are any errors given. I’m not sure if its related to my loop (probably is). I’ve tried it a few different ways (using a list of named tuples, plain list of lists, rewriting the for loop in different ways) and have been unsuccessful. Is a model.manager needed to do this? I appreciate any help and would definitely like to know of any better ways to go about this. models.py class ReccuringEvent(models.Model): semester_start = models.DateField(null=True, blank=True) semester_end = models.DateField(null=True, blank=True) lesson_start = models.TimeField(null=True, blank=True) lesson_end = models.TimeField(null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) … recurring_event_list = […] recurring_event_list_namedtuple = namedtuple('event', ['title', 'start', 'end']) recurring_event_list_named = [recurring_event_list_namedtuple(*d) for d in recurring_event_list] def save(self, *args, **kwargs): for d in range(len(recurring_event_list_named)): Event.objects.create(recurring_event_list_named) super().save(*args, **kwargs) # have tried including super(Event, self)… class Event(models.Model): title = models.CharField(max_length=200, null=True) description = models.TextField(max_length=255, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) -
Python save/reload cache upon de-deployment
I have the following function in my django project which calls an external api with caching setup hourly as follows: @cached(cache=TTLCache(maxsize=1000, ttl=settings.CACHE_EXPIRATION_HOURLY)) def get_external_data(zip_code): my_url = MY_API.format(zip_code) my_response = requests.request( 'GET', url=my_url, headers={ 'zip-code': zip_code } ) return my_response As far as i know, local caches will likely be cleared when the web servers are re-deployed or when the runserver restarts. How do you prime or save/reload the cache to avoid a spike in backend traffic each deployment? -
Django: Clone instance, Multiple Model Forms
I would like to clone an instance of my object. I am aware of the solution to: obj = ProductModel.objects.get(pk=self.object.id) obj.pk = None as described in many references, such as Link However, I struggle to implement this solution when I need to refer to a super. How can I modify the object already at start so super refers to the modified obj.pk = None ? My View.py looks like below but the super refers to the original object and not the modified object: class ProductUpdateView(UpdateView): model = Product slug_field = 'product_uid' obj = Product.objects.get(pk=self.object.id) obj.pk = None def get_context_data(self, **kwargs): context = super(ProductUpdateView, self).get_context_data(**kwargs) context['form_1'] = ModelForm_1(instance=self.obj) context['form_2'] = ModelForm_2(instance=self.obj) return context def form_valid(self, form): self.object = form.save() return super().form_valid(form) def get_success_url(self): return reverse('product-list') -
ModuleNotFoundError: No module named 'payment_info'
I am trying to run my experiment again but I get an error message when I try to execute it. However, I don't know why since I didn't change anything. This is what the Traceback says Traceback (most recent call last): File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\otree_startup\__init__.py", line 214, in do_django_setup django.setup() File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'payment_info' PS C:\Users\Wiwi-Admin\Desktop\Master thesis code\__pycache__\oTree> -
How can I access django admin when my app is live it give me server error 500?
I have an app made on django 2.2.5. I was trying to access the django admin so that I can add some data for the app using admin. When I was accessing the admin on the development server by calling 127.0.0.1:8000/admin everything is going fine and I can add more data to the database using admin page. But I am unable to access my admin page when I am fetching the admin by using(my deployed website ip say(10.2.2.5)/admin. My admin page is opening but as soon as I am trying to login into it using my id and password it is giving me error(server error 500). Can someone help me so that I can add data to my website from the admin. Thanks in advance. -
Django Admin - Disable field by choice
I had a model like this class Content(models.Model): name = Model.CharField(max_length=255, blank=False, null=False) type = Model.CharField(max_length=1, blank=False, null=False, choices=CONTENT_CHOICE) lesson = Model.CharField(max_length=255, blank=False, null=False) exam = Model.CharField(max_length=255, blank=False, null=False) and CONTENT_CHOICE likes CONTENT_CHOICE = (("1", "Lesson"), ("2", "Exam")) My goal is, when the inputer insert a new record for this model from Admin, if the inputer select "Lesson", the field exam would be disable and vice versa. May you please advise me how to do it? I search some tutorial but all seem do not have any clue. Thanks. -
Django REST api and django_filter problem
I have problem with rest_framework.viewsets.ReadOnlyModelViewSet. class ProductFilter(filters.FilterSet): meat_type = filters.CharFilter(lookup_expr='slug__iexact') category = filters.CharFilter(lookup_expr='slug__iexact') class Meta: model = Product fields = { 'price': ['gte', 'lte'], } ordering_fields = ['price', ] class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter @action(methods=['get'], detail=False) def get_products(self, request): products = self.get_queryset().order_by('-created') serializer = self.get_serializer_class()(products, many=True) print('SHOW IT') if len(products) == 0: return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.data, status=status.HTTP_200_OK) My problem is that print in get_products not work, but code give good result with filters objects. My urls: router = routers.DefaultRouter() router.register('', views.ProductViewSet) urlpatterns = [ path('shop/', include(router.urls)) ] Tests: class TestViews(TestCase): def setUp(self): self.client = Client() self.url = "/api/shop/" self.search_url = "/api/shop/?price__lte={}&price__gte={}&meat_type={}&category={}" self.category1 = Category.objects.create(name='cattest1', slug='cattest1') self.category2 = Category.objects.create(name='cattest2', slug='cattest2') self.meat_type1 = MeatType.objects.create(name='meattest1', slug='meattest1') self.meat_type2 = MeatType.objects.create(name='meattest2', slug='meattest2') self.product1 = Product.objects.create(category=self.category1, meat_type=self.meat_type2, name='prodtest1', slug='prodtest1', price=50) self.product2 = Product.objects.create(category=self.category1, meat_type=self.meat_type1, name='prodtest2', slug='prodtest2', price=75) self.product3 = Product.objects.create(category=self.category2, meat_type=self.meat_type2, name='prodtest3', slug='prodtest3', price=20) self.product4 = Product.objects.create(category=self.category2, meat_type=self.meat_type1, name='prodtest4', slug='prodtest4', price=150) def test_get_products_all(self): response = self.client.get(self.url) self.assertEqual(200, response.status_code) self.assertEqual(4, len(response.data)) def test_get_products_no_content(self): Product.objects.all().delete() response = self.client.get(self.url) self.assertEqual(204, response.status_code) def test_product_greater_than(self): response = self.client.get(self.search_url.format( "", "55", "", "" )) self.assertEqual(200, response.status_code) self.assertEqual(2, len(response.data)) Test test_get_products_no_content fail with error: assertionError: 204 != 200. Somebody have any idea? Thanks for any answer Magnus