Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Logging annotate all downstream logs
I am currently working on a Django app and I am creating roll_back functionality, so that I can run functions without persisting changes to my database. I can undo the database changes with Django's transaction class, but I would also like to annotate the logs that are created so that it's clear that these operations were performed without making DB changes. Let's say I have a file with a logger defined for that module like so: logger = logging.getLogger(__name__) class A: def make_changes(dry_run=False): if dry_run: save_point = transaction.savepoint() # Make logger changes? # Call functions in other classes that make changes # and do logging with other loggers, similarly defined # with logging.getLogger(__name__) if dry_run: transaction.savepoint_rollback(save_point) # Undo logger changes. Is there any way for me to annotate all of the logs? I know that I can format the logs for my given logger within this class using a logging formatter, but is there any way for me to update the loggers that are defined downstream of this operation without explicitly getting the names of all of the loggers that this make_changes function will call? I would like to have the normal output from all of the loggers, but annotated … -
Django 1.9 Forms and adding CSS
I have two goals: 1. I have two forms on a page, which I would like to be side by side when the screen is large enough, and stacked one on top of the other when the screen shrinks. I have no idea how to target the two forms separately. I've tried putting them into separate s, but that doesn't do the trick. I want two fields in my forms.py file shown in the html side by side. How do I target them with css? I have created classes in my forms.py file by changing the init function, but that only allows me to target the , not the , and definitely not both together to do anything meaningful. Here is the html I'm working with: {% block body_block %} <div class="container"> <div class="row"> <div class="col-md-12 col-md-offset-4 second-page"> <h3>Register Here</h3> <form id="user_form" class ="form-horizontal" method="post" action="." enctype="multipart/form-data" novalidate> <fieldset> {% csrf_token %} <div id="form1"> {{ partners_form1.as_p }} </div> <div id="form2"> {{ partners_form2.as_p }} </div> <input class="btn btn-primary btn-lg btn-block" type="submit" name="submit" value="Register" /> </fieldset> </form> </div> </div> </div> {% endblock %} -
Capturing from a html POST form a model in Django
The truth i'm new to django and i would like to know how I can capture a value of an input type = hidden in a view of django, using request.POST [ 'address'] so that it can enter a value in my model in this case I want to fill my field direction but does not receive any data appears in the database as empty. This is the code I have so far: views.py def formularioLleno(request): form = InformationForm() if request.method == 'POST': form = InformationForm(request.POST or None) if form.is_valid(): form.direccion = request.POST['direccion'] form.save() #return redirect('formas.index') return HttpResponseRedirect(reverse('index')) else: form = InformationForm() data = { 'form': form, } return render_to_response('forma_form.html', data, context_instance=RequestContext(request)) forms.py from django import forms from .models import forma class InformationForm(forms.ModelForm): class Meta: model = forma fields = ('nombre', 'telefono') models.py class forma(models.Model): nombre = models.CharField(verbose_name='nombre', max_length=50, unique=False) telefono = models.CharField(verbose_name='telefono', max_length=10, unique=False) ubicacion = models.CharField(verbose_name='ubicacion', max_length=15, unique=False) forma_form.html <div id="formularios"> {% block form_content %} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <div id="ubicacion"></div> <input type="hidden" id="direccion" name="direccion" value="hello"> <button type="submit" onclick="alerta()">Contactar</button> </form> {% endblock form_content %} -
Django select_related query
I have the following two models: class StraightredFixture(models.Model): fixtureid = models.IntegerField(primary_key=True) home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures') away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures') fixturedate = models.DateTimeField(null=True) fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday') hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season') def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixture' class UserSelection(models.Model): userselectionid = models.AutoField(primary_key=True) campaignno = models.CharField(max_length=36,unique=False) user = models.ForeignKey(User, related_name='selectionUser') teamselection1or2 = models.PositiveSmallIntegerField() teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID') fixtureid = models.ForeignKey('straightred.StraightredFixture', db_column='fixtureid') class Meta: managed = True db_table = 'straightred_userselection' I am using the following query: prevWeekTeams = UserSelection.objects.select_related().filter(soccerseason=1025,fixturematchday=5,user=currentUserID).order_by('teamselection1or2') When it is run I get the following error: Cannot resolve keyword 'soccerseason' into field. Choices are: campaignno, fixtureid, fixtureid_id, teamselection1or2, teamselectionid, teamselectionid_id, user, user_id, userselectionid I knew it would not work but I can't quite understand how to refer to the soccerseason within the fixture table. Any help would be appreciated. Many thanks, Alan. PS If you require the other two models that are linked to just let me know. -
Models aren't loaded yet. FK issue (seems to be)
Read all topics at StackOverflow and internet - no luck. # admindivisions.models class Countries(models.Model): osm_id = models.IntegerField(db_index=True, null=True) status = models.IntegerField() population = models.IntegerField(null=True) iso3166_1 = models.CharField(max_length=2, blank=True) iso3166_1_a2 = models.CharField(max_length=2, blank=True) iso3166_1_a3 = models.CharField(max_length=3, blank=True) class Meta: db_table = 'admindivisions_countries' verbose_name = 'Country' verbose_name_plural = 'Countries' class CountriesTranslations(models.Model): common_name = models.CharField(max_length=81, blank=True, db_index=True) formal_name = models.CharField(max_length=100, blank=True) country = models.ForeignKey(Countries, on_delete=models.CASCADE, verbose_name='Details of Country') lang_group = models.ForeignKey(LanguagesGroups, on_delete=models.CASCADE, verbose_name='Language of Country', null=True) class Meta: db_table = 'admindivisions_countries_translations' verbose_name = 'Country Translation' verbose_name_plural = 'Countries Translations' # profiles.models from admindivisions.models import CountriesTranslations, Countries class AbstractProfile(models.Model): if (Languages.objects.model._meta.db_table in connection.introspection.table_names()): # Just for test - This executes without any errors CountriesTranslations.objects.get(common_name="USA") CountriesTranslations.objects.filter(common_name="USA") for country in Countries.objects.filter(status=1).exclude(iso3166_1='', iso3166_1_a2=''): # Just for test - Also executes ok CountriesTranslations.objects.get(common_name="USA") CountriesTranslations.objects.filter(common_name="USA") # Makes problem (seems to be because of FK) country_name = CountriesTranslations.objects.get(country=country) title = models.CharField(_('title'), max_length=30) info = models.TextField(_('information'), max_length=500, blank=True) class Meta: abstract = True Traceback: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module … -
Django streaming CSV stops prematurely
I'm using the following code to stream a table and all its fields to a csv and then back to the user. It's more or less just the example from django's website. # CSV header header = [field.name for field in model._meta.fields] results = model.objects.all() # Generate a streaming output in case the file is large h = [] h.append(header) rows = ([getattr(item, field) for field in header] for item in results) # Need to add the header to the front chained = itertools.chain(h, rows) pseduo_buffer = Echo() # File like object that just returns value when write is called writer = csv.writer(pseduo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in chained), content_type="text/csv") filename = "{}_{}_{}.csv".format(app_name, model_name, date_str) response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) return response The issue seems to be that for larger datasets, it will randomly stop the stream prior to actually finishing getting all the data from the table. The total file size is about 12MB or so, but it will stop streaming randomly from 500k to about 8MB. I have only seen this in our production environment. I get the whole file when I do it in my development setup. It's all running in docker containers, so in theory it's … -
How to recursively get absolute url from parent instance(s)?
I have a page model that contains instance of itself as possible parent page. So every page can be child of another page. What I would like to do is get the absolute url to give me link that is structured according to its parent architecture. So let's say I have a Page AAA with child BBB, which itself has a child CCC. The url of last child would be mysite.com/AAA/BBB/CCC. I've played around and figured a recursive method that would work for me, however I hit a brick wall on resolving the urls. models.py class Page { ... parent = models.ForeignKey('self', null=True, blank=True, unique=False) .... def get_parent_path(self, list=None): parenturl = [] if list is not None: parenturl = list if self.parent is not None: parenturl.insert(0,self.parent.slug) return self.parent.get_parent_path(parenturl) return parenturl def get_absolute_url(self): path = '' if self.parent is not None: parentlisting = self.get_parent_path() for parent in parentlisting: path = path + parent + '/' path = path + self.slug; return reverse("pages:details", kwargs={"path": path, "slug": self.slug}) urls.py url(r'^(?P<path>.+)(?P<slug>[\w-]+)/$', views.page, name='details'), Testing it, showed me that path I get gives the correct parental part of the path. But resolving urls doesn't seem to work and I'm thinking it has something to do … -
Django's full_clean swallows the code kwarg to ValidationError. What to do about this?
For a long time I've called full_clean in save when I need to do some cross-field validation in clean: class SomeModel(models.Model): a_field = models.TextField() another_field = models.TextField() def clean(self): if 'condition one' in self.another_field: if 'condition two' in self.a_field: raise ValidationError('oops', code='condition_one_two_err') def save(self, *args, **kwargs): self.full_clean() super(SomeModel, self).save(*args, **kwargs) What I noticed today is that this causes the code kwarg on ValidationError to get swallowed. This is because in Django's full_clean method my ValidationError is caught and then the method raises its own instance without passing along the code attribute. Is this a bug or is it intended behavior? -
Cannot retrieve foreign key ID
I am building an application that allows a user to create a scenario, then create associated emails, t, calls and trades to the scenario. There is a 1:many relationship with the scenario and the communications. The issue I am having is I want the user to be able to click the scenario, it then shows the filtered list of communications, each communication source is a tab. The way I am filtering the communication is based on the id of the foreign key on the object. However if there is no entry for the datasource I receive a "no reverse match" because I am using the scenario id from the first object and that doesnt exist if there is no communication for that scenario. I am stumped on what the best way to do this, besides removing tabs which I like. Please let me know if I am missing anything, I am relatively new to programming and very new to Django. views.py class IMScenarioList(generic.ListView): model = InstantMessage template_name = 'scenarios/im_filtered.html' context_object_name = 'scenario_ims' def get_queryset(self): return InstantMessage.objects.filter(scenario=self.kwargs['pk']) class CallScenario(generic.ListView): model = VoiceCall template_name = 'scenarios/call_filtered.html' context_object_name = 'scenario_calls' def get_queryset(self): return VoiceCall.objects.filter(scenario=self.kwargs['pk']) class MobileScenario(generic.ListView): model = Mobile template_name = 'scenarios/mobile_filtered.html' context_object_name … -
Django View always returns base.html
so i have this code: views.py class NewPost(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello world') urls.py app_name = 'blog' urlpatterns = [ url(r'^$', views.PostListView.as_view(), name='post-list'), url(r'^loginto/$', views.loginto, name='loginto'), url(r'^logoutof/$', views.logoutof, name='logoutof'), url(r'^(?P<category>.+)/$', views.CategoryView, name='category-view'), url(r'^create/$', views.NewPost.as_view(), name='create'), ] and everything is working fine, except the last create bit. everytime i try to load create from from the address bar, it returns the base.html no matter what i put in the return. Any ideas why that is happening? -
Why is the Django database cache not shared across multiple threads?
It seems each thread maintains its separate cache. Should I just use my own Django object to have a Database cache shared by multiple threads? What are the negatives to doing this? -
How to upload multiple files in django rest framework
In django rest framework, I am able to upload single file using danialfarid/ng-file-upload views.py: class PhotoViewSet(viewsets.ModelViewSet): serializer_class = PhotoSerializer parser_classes = (MultiPartParser, FormParser,) queryset=Photo.objects.all() def perform_create(self, serializer): serializer.save(blogs=Blogs.objects.latest('created_at'), image=self.request.data.get('image')) serializers.py: class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo models.py: class Photo(models.Model): blogs = models.ForeignKey(Blogs, related_name='blogs_img') image = models.ImageField(upload_to=content_file_name) When I try to upload multiple file. I get in chrome developer tools: Request Payload ------WebKitFormBoundaryjOsYUxPLKB1N69Zn Content-Disposition: form-data; name="image[0]"; filename="datacable.jpg" Content-Type: image/jpeg ------WebKitFormBoundaryjOsYUxPLKB1N69Zn Content-Disposition: form-data; name="image[1]"; filename="datacable2.jpg" Content-Type: image/jpeg Response: {"image":["No file was submitted."]} I don't know how to write serializer for uploading multiple file. Any body please help. Thanks in Advance -
Dynamic database selection based on URL in Django
Let's say the first page of the app has two links. Is it possible to pick the database depending on which link is clicked? The databases both have the same models, but different data. For example, let's say the application contains students for different colleges A and B. If link for A is clicked, then database for A is used which contains the students for college A. The entire application after this point should use database for college A. I understand there are ways to work around this problem by just designing the databases differently, i.e. having a college field, and just filtering out students with the particular college affiliation. But I am hoping to find a solution using Django to just use two different databases. -
django validation error message get displayed twice
I tried to authenticate user through overriding form.Form clean method, and raise a validation error if a user can't be authenticate. The error does get raised, but it seems to me it get raised twice. I found an answer here https://github.com/ubernostrum/django-registration/issues/25 it said he/she has to override the form_invalid method, but i dont know where to override those method. Here is the print screen validation error message get displayed twice forms.py class AuthorLogin(forms.Form): username = forms.CharField(label='Your name', max_length=100) password = forms.CharField( label='Your password', max_length=100, widget=forms.PasswordInput) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if not user or not user.is_active: raise forms.ValidationError('Invalid username or password', code='invalid') return self.cleaned_data def login(self, request): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) return user view.py def author_login(request): form = AuthorLogin(request.POST or None) if request.POST and form.is_valid(): user = form.login(request) if user is not None: login(request, user) return redirect('microblog:index') return render(request, 'microblog/author_login.html', {'form': form}) urls.py app_name = 'microblog' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login/', views.author_login, name='author_login'), url(r'^logout/', views.author_logout, name='author_logout'), ] author_login.html {% extends "base.html" %} {% block content %} {% if form.non_field_errors %} <ul> {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% … -
Django 1.9 adding a class to form label
In my forms.py file I reconfigured the class UserForm's __init__ function to include a css class. Unfortunately doing this only allowed me to add a class to the <input> and not the <label>. How can I add a class to the label as well? Here is my forms.py file: class UserForm(forms.ModelForm): # password = forms.CharField(widget=forms.PasswordInput()) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs = { 'class': 'form-control' } class Meta: model = User fields = ('email',) def clean_email(self): email = self.cleaned_data['email'] if not email: raise forms.ValidationError(u'Please enter an email address.') if User.objects.exclude(pk=self.instance.pk).filter(email=email).exists(): raise forms.ValidationError(u'Email "%s" is already in use.' % email) return email Thanks! -
Wagtail Index page not displaying objects of children
I am at my wits-end and feel I am missing something simple but I've looked at it over and over and can't figure it out. I have a simple person_index_page that I want to show the child person_page objects, but no matter what I try...nothing. I have several sites with a similar setup and they work. Can you please look at my code below and see if you notice something I am missing? Thank you. home_tags.py # Person feed for home page and staff page @register.inclusion_tag( 'home/tags/person_listing_homepage.html', takes_context=True ) def person_listing_homepage(context, count=3): people = PersonPage.objects.live().order_by('?') return { 'people': people[:count].select_related('feed_image'), 'request': context['request'], } person_index_page.html {% extends 'base.html' %} {% load wagtailcore_tags wagtailimages_tags home_tags %} {% block content %} ... {% include "home/tags/person_listing_homepage.html" %} ... {% endblock %} person_listing_homepage.html probably should name this at some point {% for person in people %} {% include "home/includes/person_list_item.html" %} {% endfor %} person_list_item.html {% load wagtailcore_tags wagtailimages_tags %} {# Individual person item in a list - used on people index and home page #} <a class="list-group-item" href="{% pageurl person %}"> <div class="media"> {% if person.feed_image %} <div class="media-left"> {% image person.feed_image width-200 as img %} <img class="media-object" src="{{ img.url }}"/> </div> {% endif %} <div … -
Django Template Tags Creating Spaces
I am working on a Django site which is live at this site. I am getting unwanted spaces in my output caused by unwanted whitespace in the HTML. For instance, "01-1737 , Civilian Review Authority , INAPPROPRIATE LANGUAGE, SUSTAINED," has extra spaces before most of the commas. I have found other posts with similar problems, but no solution has worked for me. I tried the {% spaceless %} tag, but that didn't work. The only thing that did work for me was putting all of the template tags in the for loop on a single line, but I'd really like to find a more readable solution than this. Here is the code for the Django template: {% extends 'police_archive/base.html' %} {% block content %} <h2> {{officer.first_name}} {{officer.last_name}}, badge #{{officer.badge}} </h2> <p><strong>Department:</strong> {{officer.department}}</p> <h2>Complaints</h2> <ul> {% for details in details_list %} <li> {% if details.incident.case_number %} <a href='/police_archive/complaint/{{details.incident.case_number}}'> {{details.incident.case_number}} </a> {% else %} No Case Number Found {% endif %} {% if details.incident.office %} , {{details.incident.get_office_display}} {% else %} , No office found {% endif %} {% if details.allegation %} , {{details.allegation}} {% endif %} {% if details.finding %} , {{details.finding}} {% endif %} {% if details.action %} , {{details.action}} {% … -
Django: Link a field of one model to a field of another
I'm working through the Tango with Django book and have decided to add some of my own functionality but have an issue. I have two models, Category and Page class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) class Page(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) Now what I'm trying to do is make the Category "views" field a sum of the views of all of the pages within that category In my test database population script I am doing it this way: cats = {"Python": {"pages": python_pages, "views": sum(page["views"] for page in python_pages), }, "Django": {"pages": django_pages, "views": sum(page["views"] for page in django_pages), }, "Other Frameworks": {"pages": other_pages, "views": sum(page["views"] for page in other_pages), } } This works for the populating the database, but how would I make it so that the category "views" updates whenever a page "views" field is changed? For example if two different pages in the same category's "views" go up by one, category's "views" would go up by two? -
invalid model identifier: 'sites.site'
When I try to run manage.py syncdb, I get this error: django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/cbplusd/repos/wibo1/fixtures/initial_data.json': Invalid model identifier: 'sites.site' my installed_apps in my settings.py no longer contains django.contrib.sites, and my .json file looks like this: [ { "pk": 1, "model": "sites.site", "fields": { "domain": "localhost:8000", "name": "wibo" } }, { "pk": 2, "model": "sites.site", "fields": { "domain": "example.com", "name": "wibo" } } ] Does anyone know what I'm doing wrong? -
Django AdminEmailHandler hangs when DB is not accesible
I noticed that when my database goes down, the queries to my Django app gives timeout instead of returning 500 to the client instantaneously. Tracing the problem I set database connect_timeout in config to 5s (explained here) and the exception appears faster on the logs but after printing the exception the client does not receive the result until 30s more. OperationalError: (2003, "Can't connect to MySQL server on 'db.example.com' (4)") Debugging what is happening with PDB I found that the problem is in the django.utils.log AdminEmailHandler, when it tries to generate the mail of the exception. To generate the mail it calls django.views.debug ExceptionReporter.get_traceback_text() that looks for all frames on the traceback and then for all variables on each frame, and one of these variables is the queryset that triggered the exception. Generating the error email makes multiple accesses to the queryset that generated the DB connection timeout, generating more DB timeouts and thus the error response to the client takes so long. What is the best approach to avoid this problem? -
How do i set django setting to a file which is outside the django tree?
I have this python file tasks.py from django.contrib.auth.models import User from logreg.models import ActivationCode import datetime import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings') def remove_users(): print 'hello worldddddddddddddddddddddddddddddddddd' inactive_users = [] activation_codes = ActivationCode.objects.all() for activation_code in activation_codes: if datetime.datetime.date(activation_code.key_expires) < datetime.datetime.date(datetime.datetime.now()): inactive_users.append(activation_code.user_id) for inactive_user in inactive_users: User.objects.filter(id=inactive_user).delete() But this is in the root folder and when i try to execute it, it gives me the following error % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. how do i run it by setting the environment variable ? where should i set it -
What's happening in queryset converting to list
I have some problem in using methods in mongoengine,just as follows (just show the key codes ): from mongoengine import * class AB(Document): ........ queryset=AB.objects(__raw__=rawquery) num1=queryset.count() querylist=list(queryset) num2=len(querylist) The problem is that in my project num1=111 ,however num2=55 my question is why num1 < num2 ? what is happening in the code "querylist=list(queryset)"? thank u! -
Django.In admin get values from inline
I have model "test1" and other model "test2" with fk on the first one. And i register them in admin like "test1admin" and tabular inline for "test2inline". I wanna to get access in test1admin to values of fields from inlines. I can't get values in "test1" model because instances of "test2" wasn't created yet. I can't figure out how can i do this? -
module not found error in migration files after renaming model files in django
I renamed my model files from Users.py to users.py. Makemigrations and migration worked fine but when I tried to run the command manage.py runserver, it is throwing error. No module named 'accounts.models.Users' in migration file. # -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-09-12 16:37 from __future__ import unicode_literals import accounts.models.Users from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0004_usermodel_is_active'), ] operations = [ migrations.AlterModelManagers( name='usermodel', managers=[ ('objects', accounts.models.Users.MyUserManager()), ], ), ] How to resolve this error? Should we not change the model file names? -
Django REST API returning 200 for a GET but not returning the requested data
I am making a GET http call to my Django REST API. Django is returning the 200 OK code as follows: "GET /api/items/?categories=ALL&num=50&user=0&format=json HTTP/1.1" 200 32198 I am trying to discover why no data is being returned by adding breakpoints to my viewset and the associated serializer. None of the breakpoints I set seem to get reached. It looks like the viewset code is not getting called even though it is returning a 200 OK code. My viewset looks like this: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all().order_by('-date_added') serializer_class = ItemSerializer def list(self, request, *args, **kwargs): # Get count of views this user has made this_userID = self.request.query_params.get('user', None) if this_userID == 'null': this_userID = None custom_data = { 'results': ItemSerializer(self.get_queryset(), many=True).data # this is the default result } custom_data.update({ 'test': 'testtext' }) return Response(custom_data) def get_queryset(self): this_user = self.request.query_params.get('user', None) if this_user == 'null': this_user = None restrict_to_items_from_user_id = self.request.query_params.get('from', None) bookmarked = self.request.query_params.get('bookmarked', False) quantity = self.request.query_params.get('num', 20) item_categories = self.request.query_params.get('categories', None) if item_categories is None or item_categories == 'ALL': get_all_categories = True else: get_all_categories = False item_categories = item_categories.split(",") order_of_items = 'date_added' if bookmarked is not False: if get_all_categories: queryset = Item.objects.filter(pk__in=Bookmark.objects.filter(user=this_user).values_list('item', flat=True), active=True, approved=True).order_by(order_of_items)[0:int(quantity)] else: queryset = Item.objects.filter(pk__in=Bookmark.objects.filter(user=this_user).values_list('item', …