Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, DRF: How to get related posts with Tag(m2m)
Currently, we are able to get the following related articles by Tag. In the following method, scores are calculated in the order of the number of tags contained in the object. If more related objects of the object with the highest score are retrieved, only articles with more tags will be retrieved and articles with fewer tags will not be retrieved. Is there any other way? # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # views.py class RelatedListView(generics.ListAPIView): serializer_class = VideoSerializer def get_queryset(self): video_pk = self.kwargs["pk"] tags = Video.objects.get(pk=video_pk).tags.all() return ( Video.objects.annotate(score=Count("pk")) .exclude(pk=video_pk) .filter(tags__in=tags) .order_by("-score") ) -
How to cast parameter values based on their annotations in python functions?
Consider having a task worker, which executes tasks from a task queue. I am trying to built a web interface in django to trigger those tasks manually. So far, for some built-in data-types I go about something simple like this: # tasks.py @app.task def add(a: int, b: int) -> int: return a+b # views.py TYPE_TO_FIELD_MAPPING = { str: forms.CharField, int: forms.IntegerField, float: forms.FloatField, datetime: forms.DateTimeField, # ... } class TaskTriggerView(View): def get(self, request): tasks = {} for task in app.tasks: tasks[task.name] = self.make_task_parameter_form(task)() return render(request, 'template.html', context={'tasks': tasks} def make_task_parameter_form(self, task): # every task has a signature parameter which # is a inspect.Signature object. task_signature: inspect.Signature = task.signature # Initialize a django form with fields made out of # task's function signature, where the form field # is based on it's annotation if annotation is in # `TYPE_TO_FIELD_MAPPING` else forms.CharField. # initial value comes from parameter's default value # if it is not parameter.empty. parameter_form = type( 'ParameterForm', (forms.Form,), {param_name: TYPE_TO_FIELD_MAPPING.get(param.annotation, str)( initial=None if param.default is param.empty else param.default ) for param_name, param in signature.parameters.items()}) return parameter_form def post(self, request): task_name = request.POST.get('task_name') task = app.get_task_by_name(task_name) form_class = self.make_task_parameter_form(task) form = form_class(request.POST) if form.is_valid() # this sends the task to … -
How do I format django url so that AJAX call will get database data that is not dependent on the current page, but from a form value?
I have a page that details a post and comments on that post. The pk for this page is the post pk. I want to be able to construct comments using symbols only. I have a series of symbols saved to the database that are all associated with a category class. I have a form on my page that can select one of those categories, but how do I get an AJAX call to load all the symbols in that category? The user will need to be able to chop and change between categories so I wanted to do this with AJAX rather than reload the page each time. So far, all I get are 404 not founds. I want to do this so that I can drag or select symbols to add to comments. I've tried lots of different formats to get the urls to work (both in urls.py and in main.js) so I can't list off all the alternatives that I've tried as it's all a bit overwhelming. I've also read through a heap of questions on here and other sites but nothing seems to match what I am trying to do. Any help would be appreciated. Symbols … -
Django search bar implementation with multiple field filtering
I am trying to implement the functionality of a search bar. my models.py: class Question(models.Model): questionId = models.IntegerField(primary_key=True) groupId = models.IntegerField(default=0) questionTitle = models.TextField() groupName = models.CharField(max_length=500, null=True, blank=True) correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses") My database is huge, so I tried to skip Question.objects.all() to save time. my views.py: def questionList(request) # Searching Any Value if request.method == "POST" and request.POST['searchKey'] != '': searchKey = request.POST['searchKey'] questions = Question.objects.filter(questionId=searchKey) return render(request,'diagnosis/questionList.html', {'questions': questions}) This works perfectly but it can only filter by questionId. I wish to have such a search bar that will filter by matching all the fields(questionId, groupId, questionTitle... etc all) the Question model has. (note: request.GET already been used for pagination.) Please suggest how can I do this? -
How to return field name containing a given value in a django model?
I have a list of strings I want to search for in my database, and I want my function to return the name of the field that contains the string: for word in word_list: if word in MyModel.objects.all(): return ?? How do I complete the function so that it accomplishes this? -
Concatenate foreign key fields with delimiter Django
Lets say I have 2 models with a foreign key relation which are used to bundle books: class Bundle(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=20) isbn = models.CharField(max_length=13) bundle = models.ForeignKey(Bundle) we'll identify the bundles by concatenating the ISBN numbers with the delimiter like so: 123456788 & 123456789 To further export a list of available bundles for further processing we need that number. I'm aware I could use: for bundle in Bundle.objects.all(): complex_isbn = ' & '.join(bundle.book_set.all().values_list('isbn', flat=True)) But this would just be too slow for the real-world purpose. Is there a way I could use annotate to accomplish this? If so, how? I'm struggling to find my way through the docs on how to accomplish concatenating multiple foreign key entries. -
Django DRF get ForeignKey values in serializer
I'm trying to retrieve all Benchmarks related to a Node in my serializer, but i'm not too sure how to retrieve them. Would I need to do some sort of reverse foreignkey lookup? Maybe my models are not made correctly? class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Benchmarks(models.Model): benchmark_score = models.IntegerField(default=0) benchmarked_at = models.DateTimeField(null=True, blank=True) provider = models.ForeignKey(Node, on_delete=models.CASCADE) class NodeSerializer(serializers.ModelSerializer): class Meta: model = Node fields = ['earnings_total', 'node_id', 'data', 'online', 'version', 'updated_at', 'created_at', ] -
You may need an appropriate loader
I'm trying to implement a project using Django and React but I'm facing a problem when doing "npm run dev". It seems to be related with .jsx and some loader. I don't even know what else to do 😭 Module parse failed: Unexpected token (5:7) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | | const container = document.getElementById("root"); > render(<App/>, container); My .jsx file, webpack.config.js and package.json -
How to implement my own search filter - Django?
I have a Book model: class Book(models.Model): title = models.CharField() ... HTML form: <form type="get" action="."> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button type="submit" >Submit</button> </form> For example: User input some text in my form:"Some strange text" I wanna find all books, which contain at least one of these words in upper or lower case or some phrases in this text('Some', 'some', 'Strange', 'strange', 'Text', 'text' or 'some strange', 'Strange text' and so on). How can I do that? -
Django ImageKit change image dimension inside Admin site
I use ImageKit to display images inside Django Admin site and it works fine: @admin.register(Client) class ClientAdmin(admin.ModelAdmin): list_display = ['title', 'client_logo', ] client_logo = AdminThumbnail(image_field='logo') client_logo.short_description = 'Logo' readonly_fields = ['client_logo'] But I need to display the images as thumbnails not in the original dimension, but I can't figure out how to use processors there. -
rendering specific div tag from views.py in django
I am working in my final year project and i am stuck to render specific page. I have following code. in accounts.html i have a div tag which contains anchor tags and by clicking them it will load a other html page. here is my code for accounts.html <div class="row no-gutters row-bordered row-border-light"> <div class="col-md-3 pt-0"> <div class="list-group list-group-flush account-settings-links"> <a class="list-group-item list-group-item-action active" data-toggle="list" href="#account-general">General</a> <a class="list-group-item list-group-item-action" data-toggle="list" href="#account-connections">Connections</a> <a class="list-group-item list-group-item-action" data-toggle="list" href="#account-change-password">Change password</a> <a class="list-group-item list-group-item-action" data-toggle="list" href="#account-delete-user">Delete Account</a> </div> </div> <div class="col-md-9"> <div class="tab-content"> <div class="tab-pane fade active show" style="overflow-y:scroll; height:450px;" id="account-general"> {% include 'EditProfile.html' %} </div> <div class="tab-pane fade" id="account-connections"> {% include 'connections.html' %} </div> <div class="tab-pane fade" id="account-change-password"> {% include 'change_password.html' %} </div> <div class="tab-pane fade" id="account-delete-user"> {% include 'delete_user.html' %} </div> </div> now i am trying to render specific page from django views.py i tried this def fun(request): //logic return render(request, 'account.html','#account-connections') as by default it will always load #account-general in the page how can I! any help appreciated! -
Page not found (404) No comment found matching the query
views.py class CommentCreatView(LoginRequiredMixin, CreateView): model = Comment fields = ['text'] template_name = 'home/add-comment.html' success_url = 'homepage' def form_valid(self,form): form.instance.user = self.request.user post = self.get_object() form.instance.post = post return super().form_valid(form) urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from .views import PostCreateView, PostsListView, PostDetailView, CommentCreatView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-and-comments'), path('post/<int:pk>/comment', CommentCreatView.as_view(), name='add-comment'), path('creat', PostCreateView.as_view(), name='creat-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) add-comment.html {% extends "home/base.html" %} {% load crispy_forms_tags %} <!-- allow us to use crispy filter on any of our forms --> {% block content %} <div class="content-section"> <form method="POST"> <!--this method post is to protect our form fromcertain attacks --> {% csrf_token %} {{form|crispy}} <button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Add Comment</button> </div> </form> </div> {% endblock content %} So I opens it home/post/6/comment , I see the form and when I submit it. I get this error and the comment isnt saved error screenshot -
datetime_re.match(value) // TypeError: expected string or bytes-like object
I am running into this error when trying to run python manage.py migrate it seems that their could be a problem with the date fields in my models.py Please see the following code: Models.py from django.db import models class newCustomersClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) class jobCardsClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) jobNumber = models.CharField(max_length=50, blank=True ) dateRecieved = models.DateTimeField(auto_now=False, auto_now_add=False) dateToBeCompleted = models.DateTimeField(auto_now=False, auto_now_add=False) instructionBy = models.CharField(max_length=50, blank=True ) jobDoneBy = models.CharField(max_length=50, blank=True ) timeStarted = models.TimeField(auto_now=False, auto_now_add=False) timeCompleted = models.TimeField(auto_now=False, auto_now_add=False) Instructions = models.TextField(max_length=255) totalCostOfJob = models.CharField(max_length=50, blank=True) Forms.py: from django import forms from .models import newCustomersClass, jobCardsClass from django.forms import ModelForm class newCustomerForm(ModelForm): class Meta: model = newCustomersClass fields = 'customerName', 'addressStreetNo' ,'addressStreet', 'addressSuburb' ,'addressCity' , 'contact' , 'mail' , 'CellNo' class jobCardForm(forms.ModelForm): class Meta: … -
How to generate random unique id in django?
I am trying to generate random username based on user full name. Also here the phone is allowed null and blank but with create api view empty string is being passed to server if phone is not provided and with that integrity error occurs with phone. Here I think with the while condition i am getting 504 Gateway Time-out response. Is there any way without while statement since it is making request slower. class User(AbstractUser): phone = models.CharField(max_length=10, blank=True, null=True, unique=True) ... def save(self, *args, **kwargs): if not self.username: counter = 1 name = self.full_name unique_id = name.replace(" ", "") while User.objects.filter(username=unique_id): name = f"{unique_id}{counter+1}" self.username = unique_id return super().save(*args, **kwargs) -
How to wrap custom endpoints in Django Tastypie?
I want to add a dispatch method to some resource so I could use a wrapper decorator on it. The issue is that it only works on the CRUD operations and wont go into the dispatch method on 'original' endpoints: class SomeResource(SomeBaseResource): class Meta(...): ... def get_something_extra(self, request, **kwargs): ... def patch_detail(self, request, **kwargs): ... and the base resource: class SomeBaseResource(ModelResource): class Meta(...): ... # the wrapper @sheker_to_wrap_all_methods_with(...) def dispatch(self, request_type, request, **kwargs): logger.info('Enter') response = super(SomeBaseResource, self).dispatch(request_type, request, **kwargs) logger.info('Exit') return response So when I use patch request it is working as expected, but wont on calling the get_something_extra api. How do I wrap ALL methods in resource? -
How to mark a method as deprecated with swagger_auto_schema?
I'm using swagger-auto-schema to document my endpoints API using django-rest-framework, swagger, and drf-yasg. Is there a way to mark the API endpoints in the documentation as deprecated? -
Is there a way to run server with a session-persisted database connection in Django?
As I develop the backend side, I also develop the frontend. As you have probably guessed, I have to do some REST requests on my server. Well, there are a couple of solutions for that. I can use mocks on the frontend, or a fake JSON server. However, there are some cons to this approach: I have to remodel what I have on an already existing backend server. Dealing with authentication on a fake JSON server is not really comfortable. I have to write a lot of boilerplate if I want to go on mocking and unit testing approach. Again, all the logic I want already exists in my Django project, so what I want is: Run a dev server. Set up a fresh new database. Provide some initial data. Some fake users, posts, whatever. Do my testing on my frontend project while the server runs. Hit the kill signal. (CTRL+C) Gracefully drop the database that I have created on step 2. Shutdown the program. I use pytest and pytest-django. They do exactly these when they set up a test environment, I was wondering if I can manually do that. Thanks in advance. Environment Python 3.9 Django 2.2 -
__init__() got an unexpected keyword argument 'username'
Getting this error while making redis connection in django app. return self.connection_class(**self.connection_kwargs) Throwing error in this line. This looks like a dependency version issue, as it was working fine earlier -
Django FileNotFoundError when trying to add an item to a model
I am trying to create some models using Django and python. All my models are working and I can add items to the models, except for my User model. Can anyone suggest what could be wrong about it? models.py from django.db import models # Create your models here. class Item(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Name = models.CharField(max_length=30) Price = models.IntegerField() class User(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True) Nickname = models.CharField(max_length=50) Password = models.CharField(max_length=200) Mail = models.EmailField() Points = models.IntegerField() SaleItem = models.ForeignKey(Item, on_delete=models.CASCADE) ProfilePic = models.FilePathField() BannerPic = models.FilePathField() ZodiacSign = models.CharField(max_length=50) class Friendship(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) UserID = models.ManyToManyField(User, related_name="user") FriendID = models.ManyToManyField(User, related_name="befriended_user") class ThreadPrivate(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Text = models.TextField() Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Sender") Receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Receiver") Time = models.DateTimeField(auto_now_add=True) class Side(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator_of_page") Time = models.DateTimeField(auto_now_add=True) class ThreadPublic(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Text = models.TextField() Time = models.DateTimeField(auto_now_add=True) Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="thread_sender") SideID = models.ForeignKey(Side, on_delete=models.CASCADE, related_name="side_for_thread") and admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(Item) admin.site.register(User) admin.site.register(Friendship) admin.site.register(ThreadPrivate) admin.site.register(Side) admin.site.register(ThreadPublic) I have remembered to add to APPS in settings.py and such. … -
How can I redirect user twice - Django?
This is my files: urls.py path('add/<str:slug>/', views.addBookmark, name='addBookmark') views.py @login_required def addBookmark(request, slug): book = Book.objects.get(slug=slug) if BookMark.objects.filter(user=request.user, book=book).exists(): bookMark = BookMark.objects.get(user=request.user, book=book) bookMark.delete() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) newBookMark = BookMark.objects.create(user=request.user, book=book) newBookMark.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) Notice: my view just refresh the page Button <a class="addInBookmarks" href="{% url 'addBookmark' book.slug %}">In bookmarks</a> What do I have: When a non-authenticated user tries to add a book in bookmarks I have the next URL pattern: .../login/?next=/cart/add/harry-potter It does add an object to the database. However, after the action, it reloads the page and the page is the login page. I need to redirect back to the book page. My problem: For authenticated users, everything works well. However, If a user isn't authenticated, then I wanna have the next scheme: a non-authenticated user clicks on the button -> redirect on the login page -> log in -> add an object in the database(Bookmark model)(using the view above) -> redirect back to the book page. -
django admin return value.utcoffset() is None
I get this error when I try to enter the Django admin panel: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "D:\workspace\web\djangoProject\lib\site-packages\django\contrib\staticfiles\handlers.py", line 76, in __call__ return self.application(environ, start_response) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\wsgi.py", line 133, in __call__ response = self.get_response(request) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\base.py", line 130, in get_response response = self._middleware_chain(request) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\exception.py", line 49, in inner response = response_for_exception(request, exc) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\exception.py", line 138, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "D:\workspace\web\djangoProject\lib\site-packages\django\views\debug.py", line 52, in technical_500_response html = reporter.get_traceback_html() File "D:\workspace\web\djangoProject\lib\site-packages\django\views\debug.py", line 331, in get_traceback_html return t.render(c) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 988, in render output = self.filter_expression.resolve(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 698, in resolve new_obj = func(obj, *arg_vals) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\defaultfilters.py", line 702, in date return formats.date_format(value, arg) File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\formats.py", line 152, in date_format return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n)) File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\dateformat.py", line 342, in format df = DateFormat(value) File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\dateformat.py", line 57, in __init__ if is_naive(obj): File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\timezone.py", line 225, in is_naive return value.utcoffset() … -
Change the function based views to class based generic views(update view)
I need to change the function based views to class based generic view i have the html page which displays the ticket status and info along with the button ticket image with accept button if i click on accept button it goes into below function based view(accept_ticket_view()) i need that function based view to be written in cbv(updateview). model.py class Ticket(models.Model): ticket_title = models.CharField(unique=True,max_length=200) ticket_description = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( ('Opened','Opened'), ('Accepted','Accepted'), ('Completed','Completed'), ('Closed','Closed') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,blank=True,null=True) closed_date = models.DateTimeField(blank=True,null=True) completed_date = models.DateTimeField(blank=True,null=True) accepted_date = models.DateTimeField(blank=True,null=True) opened_date = models.DateTimeField(blank=True,null=True) accepted_by = models.ForeignKey(User,related_name='assigned_to',on_delete=models.CASCADE,blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) openticket.html <thead> <tr> <th>ID</th> <th>Status</th> <th>Created</th> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {% for ticket in tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status }}</td> <td>{{ ticket.created_by }}</td> <td>{{ ticket.ticket_title }}</td> <td>{{ ticket.ticket_description }}</td> <td><a href="{% url 'accept_tickets' pk=ticket.id %}"> Accept</a> views.py @login_required def open_tickets_view(request): tickets_open = Ticket.objects.filter(status = 'Opened') return render(request,'app/open_tickets.html',{"tickets": tickets_open}) @login_required def accept_tickets_view(request,pk): ticket = get_object_or_404(Ticket,id=pk) if ticket.status == 'Opened': ticket.status = 'Accepted' ticket.accepted_date = datetime.datetime.now() ticket.accepted_by = request.user ticket.save() return redirect(reverse('open_tickets')) @login_required def dev_accepted_ticket(request): ticket_complete = Ticket.objects.filter(status = 'Accepted',accepted_by = request.user) return render(request,'app/dev_accepted_ticket.html',{"tickets": ticket_complete}) @login_required def mark_complete_tickets_view(request,pk): ticket = get_object_or_404(Ticket,id=pk) … -
How to add a custom view to django admin similar to /change and /add?
How can I create an extended view to a instance of an object in Django. For example, in the changelist_view of a model's object, I would like to have a link to a custom view that will display some information. I would like to have that page sitting in something like: admin/my_app/my_model/<id>/custom-view urls.py urlpatterns = [ path('admin/', admin.site.urls), path('admin/my_app/my_model/<id>/customers-in-use', views.custom_view), admin.py class MyModelAdmin(VersionAdmin) list_display = [... custom_view, ...] def custom_view(self, obj): url = f"/admin/my_app/my_model/{obj.id}/custom-view/" return format_html(f"<a href='{url}'>{obj.id}</a>") And in views.py I have the method that just collects the data. But when I click on the link, it redirects me to admin's home page with a message my_model with ID <id>/custom-view" doesn't exist. Perhaps it was deleted? What is the proper way (if any) to do this? -
Django: use select_related / prefetch_related for 3 models in one query
I have few Django models: Domains, Kpis, Tests, TestsAndKpis TestsAndKpis is many-to-many model with test_id and kpi_id as keys. Kpis model has a ForiegnKey of domain_id. I want to efficiently get data from my DB (i use MySQL), meaning to have as less DB queries as possible. Currently, to get what i need i run this items = [{'kpi_type': t_k.type, 'kpi_name': t_k.kpi_id.name, 'kpi_display_name': t_k.kpi_id.display_name, 'domain_display_name':t_k.kpi_id.domain_id.display_name} for t_k in TestsAndKpis.objects.filter(test_id=test_id).select_related('kpi_id')] Which results my application to run LOTS of redundant queries [like SELECT ... FROM domains WHERE domains.id = 6 [total of 25 queries] When i remove the 'domain_display_name' key that extract from domains table: items = [{'kpi_type': t_k.type, 'kpi_name': t_k.kpi_id.name, 'kpi_display_name': t_k.kpi_id.display_name for t_k in TestsAndKpis.objects.filter(test_id=test_id).select_related('kpi_id')] The application runs only 15 queries in total and returns MUCH faster. My question: How can i extract the data efficiently, and avoid the redundant 10 queries? I tried to use chained select_related/prefetch_related but it did not work out for me. -
Django Server Side set-up for pagination with Datatable
I am using Django for backend, and I am using Datatable library to display a large number of records ( approx 1 million records ). I am trying to set up datatable in such a way that every time 25 records are being fetched from the backend and when the user clicks on the next page button, another ajax call gets the next 25 records and so on. But I am having a trouble setting these up. My DataTable initialisation : $("#company-table").DataTable({ "processing": true, "serverSide": true, "bDestroy": true, ajax: { type: "POST", url: "/get_results/", headers: { "X-CSRFToken": getCookie("csrftoken"), }, data: { ...other data params... page:$("#company-table").DataTable().page() }, }, columns: [ ...populating columns... ], }); And my views.py looks like this ( It is completely wrong as far as I know ) : #filtered_queryset contains all the records. paginator = Paginator(filtered_queryset, 25) # Show 25 contacts per page. page_number = request.POST.get('page') start = request.POST.get('start') length = request.POST.get('length') page_obj = paginator.get_page(page_number) data = list(page_obj.object_list.values()) return_data = {"data": data} json_data = json.dumps(return_data,indent=4, sort_keys=True, default=str) return HttpResponse (json_data, content_type = "application/json") Can anyone help me? Or just nudge me in the right direction?