Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot delete an item from the Django admin interface
We used the Django admin interface to create some content (a 'Talk' model) and upload a file. The upload failed with a Server Timeout Error (500). Now, we cannot delete or even click on the talk in the admin interface. See screenshot: When we click on the item, we get a Server Error (500) message and Django outputs the following to our log files: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in None DEBUG 2021-10-23 07:29:00,382 base 128 140297891723008 Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'. Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'NoneType' object has no attribute 'non_field_errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'non_field_errors' When we try to delete the item, we receive a slightly different error: Traceback (most … -
Django, Can not import urls from django.conf.urls
I am working on django restframework project. I build it and it was working well but then I tried makemigrations and I got following error. Please help me. File "/code/eventful/manage.py", line 22, in <module> main() File "/code/eventful/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 412, in execute self.check() File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.10/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py", line 446, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py", line 625, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, … -
How to make some Django Inlines Read Only
I'm using django admin and adding a TabularInline to my ModelAdmin class. Think Author and the inline is Books. How do I make some of those inlines appear read only and some appear editable based on certain characteristics of the model instance for each specific inline? Say I wanted all the books written before 2001 to be read only. And all the books written after that to be editable. I've tried overriding has_change_permission() and using the obj param, but it is receiving the parent and not the instance of this specific inline. -
how to use request.GET.get() with JsonResponse view - django
i want to create a query base on two dates, i'm using one view for json response, and another view for the template def dateTimePrice(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)#print None if start and end: datetimes = ImeiInvoice.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) else: datetimes = ImeiInvoice.objects.all().annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) return JsonResponse(datetimes,safe=False) @login_required def dateTimePriceTemp(request): return render(request,'myapp/datetimes.html') and here is my template <form action="" method="GET"> <div class="col-11 p-1 mt-1 mx-auto text-center row rtl "> <p class="col-12 col-sm-6 mx-auto text-left row"> <img src="icons/date.svg" class="ml-1" alt=""> from <input type="date" class="form-control col-9 mr-1" name="from" id=""> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> <img src="icons/date.svg" class="ml-1" alt=""> to <input type="date" name="to" class="form-control col-9 mr-1" id=""> </p> <button class="btn btn-info col-8 col-sm-5 col-md-3 mx-auto">گەڕان</button> </div> </form> i returned the data with ajax call, it works fine, but i dont know to get from and to values from the template!? i much appreciate your helps .. -
How can I set the accepted content type in django view
I have some views made in Django. I have realised that the endpoints do not fail with an unsupported media type if I call them with, for instance, binary data instead of json (they only accept json). So, my doubt is: how can I specify the allowed content type of an endpoint in django to make it return a 415 error code? Do I need to implement that logic by hand with a middleware? -
Celery beat sends scheduled task only once and then doesn't send task when restarted
I am using Celery beat to perform a task that is supposed to be executed at on specific time. I was trying to excute it now by changing the time just to see if it works correctly. What I have noticed is it sends the task correctly when I run a fresh command that is celery -A jgs beat -l INFO but then suppose I change the time in the schedule section from two minutes or three minutes from now and then again run the above command, beat does not send the task. Then I noticed something strange. If I go to the admin area and delete all the other old tasks that were created in the crontab table, and then run the command again it sends the task again to the worker. The tasks are being traced by the worker correctly and also the celery worker is working correctly. Below are the codes that I wrote to perform the task. celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab from django.utils import timezone from datetime import timezone # Set the default Django settings module for the 'celery' program. … -
send_mail Django send as alias email
I'm solving problem, that of course I'm sending an email like sender email, which I authenticated in settings.py, but what if I want to send and email as request.user.email alias? send_mail("Hello", "hello", settings.EMAIL_HOST_USER, [settings.EMAIL_RECEIVER]) is this some reason how to do that? Thanks a lot -
How to pass a cognito generated token while using graphene snapshot testing in django?
i'm just trying to pass HTTP_AUTHORIZATION token to test all my queries and mutations and just getting an error token has not been passed since it needs to get the context of logged in user, i just want to pass hard coded token for now in the Graphene test client query, Any leads appreciated , Thanks :) heres is what i'm trying to achieve: class PostTest(TestCase): def getAllPosts(self): client = Client(schema) self.assertMatchSnapshot(client.execute( """ query{ getPost(first:10){ edges{ node{ title description isLiked } } } } """, context = {"HTTP_AUTHORIZATION:"**HERE IS THE COGNITO GENERATED TOKEN**" )) -
DRF serializer validation - discard failed items, keep successful ones?
I have an endpoint (POST, APIView) which expects larger chunks of data that needs to be validated using serializers. However, for many reasons there are times where I'd like to discard a few of them that fail validation. The rest, I still want to add. E.g I'd like to run : serializer = ListingSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() Lets say we have a table of listings which has a foreign key to a company table. Therefore I have a nested company serializer as a field. A company only has a name. In order to save some performance I fetch all companies in the init method so is_valid() only makes one query (similar to a select_related). The problem here is that if a single company did not exist, the entire is_valid() will fail and thus I cant run serializer.save(). Is there any elegant way to solve this by discarding the individual items that fail is_valid() so that I can run serializer.save()? class CompanyStringSerializer(serializers.ModelSerializer): class Meta: model = Company fields = ("name",) class ListingSerializer(): company = CompanyStringSerializer() def __init__(self, *args, **kwargs): """ This is executed when the serializer initializes (meaning the query will only run once) """ self.companies = Company.objects.filter(enabled=True) super().__init__(*args, **kwargs) … -
Get current Logged in User in django Rest Framework
I am trying to get current logged in user and upload/send information to frontend. I am new to Rest Framework so forgive my basic level question. I have tried fetching user with request.user and request.auth in my views but I am not able to simply get user. This is my views.py from rest_framework.authtoken.models import Token def get_User (request): # current_user = request.user # context = {"user": current_user} # print(request.user.username) user_id = Token.objects.get(key=request.auth.key).user_id print(request.auth) # Response(context) I am using a custom user model to store data. Every time I am running request.auth or request.user i can see in my django terminal that it keeps going to /verify-auth-token/ URL. How do I get user printed also sent to frontend in React to display in app as well. Any help is appreciated. -
Disable has_changed check in django form
When an entry is saved in results list in django admin site I need it to end up in save_model regardless of whether it has changes or not. With default behaviour it will just present the same page if there are no changes. What is the canonical way of disabling it? Currently I came up with this quick and dirty snippet. It works, but I suspect it's ugly:) def get_changelist_form(self, request, **kwargs): res=super().get_changelist_form(request, **kwargs) # Ugly? res.has_changed=lambda *args, **kwargs: True return res -
Celery beat not resuming scheduled tasks django
I have used celery & django celery beat to run a predefined scheduled task. When I first run celery worker & then celery beat worker, everything is fine, the task is added to database, and also sent to queue by celery beat worker continuously. But when I stop beat worker and start it again, it no longer works, even though the task is defined in database. What should I do? This is my code for django: # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task def test(arg): print(arg) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='say hello every 10 secs') app.conf.beat_schedule = { 'add-every-12-seconds': { 'task': 'tasks.test', 'schedule': 12.0, # 'args': () }, } and this is how I start celery worker & beat worker: celery -A proj worker -l info celery -A proj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler Would appreciate a … -
Access django database on postgresql from independent python script
I have a website built with django and postgresql. each user (user in django Auth system) on the website have many account models (and other models) . An app running on windows-python based need to access (read/write) data from the database. Each app is associated with a specific user. my questions: can an app access only specific user data? the account model have an attribute of user so it filter based on that, how can it restrict external app access? what is the proper way to read / write from database? can I somehow use the django models as the website do? -
Getting systemd to use user ENV configs
I am trying to create an LXC container to run a specific Django Application automatically at start. The issue I am having is that getting the Django side of things starting up with systemd was fairly easy, however the application checks ENV variables as well as relies on some Ruby Gems to function. The LXC Template is based on Debian 11. Due to the specific requirements, I run pyenv and rbenv to manage the installed versions for the specific user (django for the purposes of this example). I can get systemd to start the Gunicorn server well enough, but am having an issue that it seems to not pull ENV variables (Not sure yet), nor does it get access to the required Ruby Gems (Confirmed). My gunicorn.service file looks like this: [Unit] Description=Start Gunicorn to run Django App After=network.target [Service] Type=notify # the specific user that our service will run as User=django Group=django RuntimeDirectory=/home/django/.pyenv/shims WorkingDirectory=/home/django/application ExecStartPre=/home/django/.pyenv/shims/python /home/django/app/manage.py migrate ExecStart=/home/django/.pyenv/shims/gunicorn --chdir /home/django/app app.wsgi:application -k=gevent -t 600 --certfile=/home/django/app/server.crt --keyfile=/home/django/app/server.key -b=0.0.0.0:8000 -w=4 --forwarded-allow-ips=* --proxy-allow-from=* ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed TimeoutStopSec=5 PrivateTmp=true [Install] WantedBy=multi-user.target How can I get systemd to run the gunicorn.service wherein the ENV variables specified in home/django/.bashrc will be honored, and … -
get 2 objects in updateview django
I have have a template where i want to make update on 2 different models, the first one is the order model , and teh second is the customer model. In the template i've got the 2 forms, but the problem is that i cant get informations about the customer in the customer form models.py class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') def __str__(self): return 'Order n°: ' + str(self.id) views.py class OrderUpdateView(LoginRequiredMixin, RedirectToPreviousMixin, UpdateView): model = Order form_class = OrderManageForm second_form_class = CustomerForm template_name = 'dashboard/order_details.html' login_url = '/login/' def get_object(self): return Order.objects.get(id=self.kwargs['order_id']) def get_context_data(self, **kwargs): context = super(OrderUpdateView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class() if 'customer' not in context: context['customer'] = self.second_form_class() return context How could i get the customer object ? -
django-table2: get row primary key to access row extra details
I am trying to get list of products to be displayed as a django table and I am trying to create one column that would be a see more link to the details page for that one product. I cannot get the syntax correct for that one specific field and been banging my head off the wall for hours. here is what I got for tables.py class ProductsTable(tables.Table): Details = tables.TemplateColumn('<a href="{% url 'woppa_product_details' pk= record.pk %}">See more</a>') class Meta: model = Products fields = ( 'ProductCode', 'ProductName', 'ProductCategory', ) template_name = "django_tables2/bootstrap4.html" here is my views.py def ProductsView(request): table = ProductsTable(Products.objects.all()) return render(request, 'woppa_inventory_list.html',{'table':table}) and here is urls py urlpatterns = [ path('woppa_inventory_list', ProductsView, name='woppa_inventory_list'), path('woppa_product_details/<str:pk>', ProductDetailsView, name="woppa_product_details"), ] No clue what else to try at this point -
Confusion when importing Django' generic class based views
While exploring the reference documentation and some tutorials I have seen the import for Django's generic class based views used in multiple ways: from django.views.generic import TemplateView, ListView Or: from django.views.generic.base import TemplateView from django.views.generic.list.ListView I have tried experimenting with both tactis and they both seem to work, yet the first option seems less correct. Do all the generic CBVs also exist within the generic module a well as the submodules? Can Python import classes from submodules by only importing a higher module? What is actually happening here? Any help would be greatly appreciated! -
i need to uild reservation meeting rooms systems
i am fresh software developer at django reset framework and i want to develop a reservation meeting rooms web application and i create below model and form meeting room reservations (select meeting room with date and time if conflict with another date of reserve error message (this room is reserved by employee name) below my model : model.py: class MeetingRooms(models.Model): """Model representing a project.""" room_name = models.CharField(max_length=100) description = models.TextField(max_length=1000, help_text='Enter a brief description of the project') room_number = models.IntegerField() def __str__(self): """String for representing the Model object.""" return f'{self.room_name}' def get_absolute_url(self): """Returns the url to access a detail record for this project.""" return reverse('meetingrooms-detail', args=[str(self.id)]) from django.core.exceptions import ValidationError class ReservationMeetingRooms(models.Model): """Model representing a project.""" meeting_room = models.ForeignKey(MeetingRooms, on_delete=models.SET_NULL, null=True, blank=False) reservation_date = models.DateField(null=True, blank=False) reservation_from_time = models.TimeField(auto_now=False, auto_now_add=False) reservation_to_time = models.TimeField(auto_now=False, auto_now_add=False) teams = models.ManyToManyField(Employee) #models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=False) def clean_reservation_date(self): date = self.cleaned_date['reservation_date'] # Check if a date is not in the past. if date < datetime.date.today(): raise ValidationError(_('Invalid date - Date cannot be in the past')) return date def __str__(self): """String for representing the Model object.""" return f'{self.meeting_room}' return f'{self.teams}' def get_absolute_url(self): """Returns the url to access a detail record for this project.""" return reverse('reservationmeetingrooms-detail', args=[str(self.id)]) … -
Conditional rendering (of different sections) in Django Template
I wrote this code (inside a view) to generate some flags # when to show bidding form? # - current user is logged in # - listing is active # - listing isn't created by current user show_bidding_form = ( request.user.is_authenticated and listing.is_active and listing.owner != request.user ) # when to show #bids and close listing form? # - current user is logged in # - listing is active # - current user is listing owner show_bids_count = ( request.user.is_authenticated and listing.is_active and listing.owner == request.user ) that control showing different sections (inside a template) {% if show_bidding_form %} <!-- some div ->> {% elif can_close_listing %} <!-- some other div --> {% endif %} my question is: is this the best way to do such filtering? or there's some other "official" way. I am thinking of moving both code and markup into a inclusion tag instead. But then the view the originally contained code would be empty and I will have no clue of what's going on inside template it renders.. -
Django, HttpResponse, HTML
I have checkboxes after selecting several queries and the page is generated according to the selected checkboxes. question: to use HttpResponse and to make the page in parts, whether it is possible to use a template? -
Getting database error while using django-paypal
Im using Mongodb (djongo engine) for the database for my django project, I can't work out I always get this error when paypal posts to my website: [13/Dec/2021 15:59:44] "POST /paypal/ HTTP/1.1" 500 28196 Internal Server Error: /paypal/ Traceback (most recent call last): File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__ super().__init__(*args) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse self.where = WhereConverter(self, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__ self.parse() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse self.op = WhereOp( File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 475, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op op = ParenthesisOp(SQLStatement(tok), self.query) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op op = ParenthesisOp(SQLStatement(tok), self.query) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 438, in _statement2ops if prev_op.lhs is None: AttributeError: 'NoneType' object has no attribute 'lhs' The above exception was … -
Generator expression must be parenthesized if not sole argument: using join
I'm getting following exception while run the server:- SyntaxError: Generator expression must be parenthesized if not sole argument to the following line: return '\n'.join(' | '.join(value.rjust(width) for value, width in row, widths) for row in table I'm using a Python 3 version. I also tried to upgrade the django but still it returns same exception. Can anyone help me to solve this problem? Thanks in advance. -
404 error : no comment matches the given query
I've searched enough about this problem, but haven't been able to find a solution. Please help me. View.py class comment_delete(DeleteView): model = Comment success_url = reverse_lazy('board_list.html') urls.py path('', views.home, name="home"), path('board/', views.board.as_view(), name="board"), path('board/<int:pk>/', views.board_detail.as_view(), name="board_detail"), path('board_write/', views.board_write, name="board_write"), path('board_insert', views.board_insert.as_view(), name="board_insert"), path('board_edit/', views.board_edit, name="board_edit"), path('board_update/', views.board_update, name="board_update"), path('board_delete/', views.board_delete, name="board_delete"), ####### comment ######### path('board/comment/update/', views.comment_update, name="comment_update"), path('board/<int:pk>/comment/<int:id>/delete/', views.comment_delete.as_view(), name="comment_delete") comment.html <form action="{% url 'comment_delete' pk=i.Board_id id=i.id %}" method='POST'> -
Django save request.POST to JSONField picks last item from list instead of saving the list
I have a view that receives a post request from client.post() data = { "token": create_hash(customer_name), "images": [image_1, image_2], "name": customer_name, "email": "test@email.com", "phone": "0612345678", "product": "product-sku0", "font_family": "Helvetica", "font_size": 12, "colors_used": ( "#AAAAAA|White D", "#FFFFFF|Black C" ) } I am trying to save the post request as a whole to a model.JSONfield(). The post request key-value pair looks like this: 'colors_used': ['#AAAAAA|White D', '#FFFFFF|Black C'] When I save and later retrieve the value it looks like this: 'colors_used': '#FFFFFF|Black C' Instead of saving the nested list in the JSONfield it only saved the last value. I am using SQLite. -
How to properly override get_queryset in a modelviewset without breaking the query by pk?
I have a ModelViewSet: class OrderViewSet(viewsets.ModelViewSet): serializer_class = OrderSerializer pagination_class = DefaultPagination queryset = Order.objects.all() def get_queryset(self): userId = self.request.query_params.get('userId') if userId is not None: query = Order.objects.filter(owner__id=userId).order_by('-createdAt') else: query = Order.objects.order_by('-createdAt') return query Here is the url registration router = routers.DefaultRouter() router.register('api/v1/order', OrderViewSet, basename='order') I found that after overriding the get_queryset, I can no longer query by one order id like the following anymore: /api/v1/order/1,it just returns detail: not found I do see django saying it supports: ^api/v1/order/$ [name='order-list'] ^api/v1/order\.(?P<format>[a-z0-9]+)/?$ [name='order-list'] ^api/v1/order/(?P<pk>[^/.]+)/$ [name='order-detail'] ^api/v1/order/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='order-detail'] what should be the correct way to do this? Thanks!