Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django python3 manage.py runserver won't run via VSC terminal (Mac)
Trying to run this command: python3 manage.py runserver via VSC terminal and get this error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? But! when I run it via the Mac terminal, it works well. I have verified and: Virtual env is running (via Anaconda) Django is installed (as it is running on the Mac terminal) is it something with VCS setting I need to tweak? Thanks in advance! -
Fitlering errors in Sentry
I'm running sentry.io for my django project. I'd like to prevent some errors from being reported so as to not consume my quota. Unfortunately, I'm not able to find any code samples on how to do this. Sentry's documentation doesn't clearly outline how or where to do this. I was wondering if you'd be able to provide a simple example or point me in the right direction. I'm on the Developer plan, so I need to filter these errors server side before sending to Sentry in order to prevent my quota from being hit. Thanks! -
Displaying Panda Table from other python project in Django App
So I am looking to display a Pandas table on a Django website through a django app. I have found this thread: display django-pandas dataframe in a django template. This explains how to use bootstrap and JS to create the table and display it in Django. However where I am lost is how I import the panda table to the object in the django. Basically, I have python project that creates pandas based on information queried data from elsewhere. Now I am trying to display those pandas on my web app. So, where I am lost is how I can run that python code (from my python pandas project) to get most recent data in sync with running the website and thus assign the pandas to the product model object. Any information regarding this would be huge. Thanks in advance! I am trying to use bootstrap-tables, because it is interactive and can create many different tables, but if someone has an easier less complicated idea please let me know. -
Showing the line numbers in <pre> in Django project using Pygments
I'm using the Pygments package in my Django project. When I try to render the code snippet in my template, it renders the whole data as follows: Template: ... {% pygmentify %} <pre class="{{snippet.lang}}">{{snippet.body}}</pre> {% endpygmentify %} ... Final rendered HTML: <pre lang="python"> ... <span class="kn">import</span> <span class="nn">hello</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'hey'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'in the function'</span><span class="p">)</span> ... </pre> It actually works with no pain. The entire code block is being highlighted properly. The thing is that I want to show the line number as well. Should I style them or there is only a simple Pygments configuration needed? Thanks. -
AssertionError:'token' not found in{'non_field_errors':[ErrorDetail(string='Unable to authenticate with provided credentials.',code='authorization')]}
I've been made a django rest api app and i have this error in my test: image I'm going to leave the code here The test: def test_create_user_token(self): payload = { 'email': 'test@gmail.com', 'password': 'test123', 'name': 'Test' } create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) The serializer class: class AuthTokenSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) if not user: msg = _('Unable to authenticate with provided email and password.') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs From already thank you very much -
Is every API created with Django Rest Framework an REST API?
I just wonder if the fact that the API is created with DRF means it is really an Rest Api? Or is there something important to remember in order to make it truly REST? When I communicate with endpoints, I send JWT in requests, so I believe it makes it Stateless. Naming conventions for rest endpoints are probably important too. But is there anything else to remember so I could call my Api a Rest Api? -
Django: Where to store a main object and reference it from views.py + run repeating code?
I am building an app with Django to automate a reservation which I need to make every day. Django is used to provide a web interface to monitor and control this. However, I cannot figure out where to put my code within the Django files. Before trying Django I just had a while True loop that made the reservation as soon as a condition was true. To do this in Django, I need to create a main object on startup and reference this from different views in the views.py file. And I need to run some kind of schedule that checks the condition if the reservation is to be made. All of this in parallel to the actual website code. Using celery seems complicated and overkill for this. Is there a main Django object that is created on startup and can be accessed from other files (such as views.py)? Then I could create a parent class of this class that holds my main code and allows for starting and managing parallel jobs. E.g., I looked at AppConfig, but don't know how to reference this object from other files... class ReservationAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'reservation_app' driver = None def … -
On which tablet from the following can I code on?
I understand tablets are not a good choice for developers, but out of the following which one can be used for coding? (I'm pretty new at coding, so just some basic languages working should be fine.): SAMSUNG GALAXY TAB A7, Lenevo M10, or Lenevo Tab 4 tablet. Does any of these support mostly used languages and software? -
Django updating One-To-One Relationship is causing UNIQUE Constraint Failure
I cannot wrap my head around why I'm getting an error here - when the update query is run with this django ORM save() code, I get a UNIQUE Constraint Error: django.db.utils.IntegrityError: UNIQUE constraint failed: tasks_recurringtask.id From my understanding, update is executed immediately and only called on the same scheduler job that has the ID referencing the given RecurringTask. Maybe I'm missing something or there is a safe way to do this? Any explanations would be helpful, thanks! class RecurringTask(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='tasks') start_time = models.DateTimeField(default=now) scheduler_job = models.OneToOneField( Schedule, on_delete=models.CASCADE, blank=True, null=True, default=None ) def save(self, *args, **kwargs): # set all other dependencies for Task # update Scheduler Job if self.scheduler_job is None: self.scheduler_job = Schedule.objects.create(func='tasks.jobs.do_task', args=f'{self.pk}', next_run=self.start_time ) else: Schedule.objects.filter(id=self.scheduler_job_id).update( next_run=self.start_time ) super(RecurringTask, self).save(self) -
How to return last post?
I have probably a small problem. Namely how can i extract a last post when i use 'post.comments.all' class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.content1) Views tag = request.GET.get('tag') if tag == None: my_tag = Posty.objects.all print(my_tag) else: my_tag = Posty.objects.filter(created_tags__tag=tag) print(my_tag) If i tried use '[:1]' or last, this dont work. -
How can I get and display ForeignKey data in a Django template
I'm attempting to only display cards based on their category_name. for eg. I have 2 simple models, Product and Category: class Category(models.Model): category_name = models.CharField(max_length=254, blank=False, null=False) url_name = models.SlugField(max_length=254, unique=True) category_image = models.ImageField( null=False, blank=False, default='', upload_to='category_images', help_text='This will be the category image') category_description = RichTextField(default='') class Meta: verbose_name = 'Categories' def __str__(self): return self.category_name def get_category_name(self): return self.category_name class Product(models.Model): main_product_image = models.ImageField( null=False, blank=False, default='', upload_to='product_images', help_text='This will be the main image in the carousel.') alternative_image_1 = models.ImageField( null=True, blank=True, upload_to='product_images', help_text='This will be the first image in the carousel.') alternative_image_2 = models.ImageField( null=True, blank=True, upload_to='product_images', help_text='This will be the second image in the carousel.') category = models.ForeignKey( 'Category', null=True, blank=True, help_text='Assign product to category', on_delete=models.CASCADE) created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='product_creator', null=True) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) product_display_description = RichTextField(default='') spice_rating = models.CharField(max_length=1, null=True, blank=True) has_sizes = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, default='0') add_to_carousel = models.BooleanField(default=False) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.name I would like to then display these product cards on the frontend based on their category names. Using something simple like … -
Make Column in Pandas Dataframe Clickable and pass text value to Django view
I have a column in a dataframe called State. I want it to be clickable and when clicked, go to a URL and pass the state name to a Django view. So far I have tried it this way: smalldf['state'] = smalldf['state'].apply(lambda x: f'<a href=".\?q={x}">{x}</a>') It creates a url like this: http://127.0.0.1:8000/mysite/?q=TN but I am unable to extract the value TN from inside the view. The Django code looks like this: print('state is : ') print(parm_state) search_form = DateRangeForm(request.POST or None) # if this is a POST request we need to process the form data if request.method == 'POST': date_from = request.POST.get('startDate') date_to = request.POST.get('endDate') I can find the TN state value at the top and can print it. But when I come back from the DateRangeForm the value is gone. I cannot find a way to access it from inside the if request.method == 'POST' code. Would appreciate some help. Thanks -
Created information box inside form, based on model fields
Greetings and Happy Christmas everyone! I'm trying to implement a simple information text based on my model field because it retains some data like: MyModel.information: { start_date: imaginary_date, end_date: imaginary_date, store_name: 'Foo bar' } Now I want to display inside my admin form that information as a text, like: 'Store Foo bar, start at imaginary_date and close at imaginary_date. That implementation is just to the client who is editing some information at the form, can see easily the information about the store. -
ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)
I get the error below when I add 'graphene_django' inside INSTALLED_APPS in the settings.py After running python3 manage.py runserver graphene_django is installed successfully using pip install django graphene_django This is full error that i get Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 223, in create import_module(entry) File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/graphene_django/__init__.py", line 1, in <module> from .fields import DjangoConnectionField, DjangoListField File "/usr/local/lib/python3.9/site-packages/graphene_django/fields.py", line 18, in <module> from .utils import maybe_queryset File … -
Fetching foreign key's tables data from primary key's table
These are my models: class Customer2(models.Model): Customer_Name=models.CharField(max_length=30) Customer_Address=models.CharField(max_length=100) Customer_Phone=models.IntegerField() Customer_Email=models.EmailField(max_length=50) class Meta: db_table="Customer_Table" class Product(models.Model): Product_Name=models.CharField(max_length=100) Quantity=models.FloatField(max_length=100) Comming_Date=models.DateField(max_length=15) Expire_Date=models.DateField(max_length=15) Comming_Price=models.FloatField(max_length=50) Picture=models.ImageField(upload_to='Images',blank=True, null=True) class Sale(models.Model): Customer=models.ForeignKey(Customer2, default=1, on_delete=models.CASCADE) Product=models.ForeignKey(Product, default=1, on_delete=models.CASCADE) Quantity=models.FloatField() Price=models.FloatField() Date=models.DateTimeField() Customer_Name1=models.CharField(max_length=20,default=0) Product_Name1=models.CharField(max_length=20,default=0) class Meta: db_table="Sale_Table" I want to get or fetch or show all Sale model( class Sale) data but instead of Customer and Product columns in Sale table(model),I want to show Customer_Name and Product_Name from their own tables what should I do? -
Custom format an inline formset
I'm create a template in Django, adding a form and formset to the template, but I don't like how it's formatting the formset by default. I've tried .as_table and .as_ul, but it's not formatting it to my liking. I'd like to see the following from the formset: Ingredient Percentage Delete ingredient1 .55 ingredient2 .22 ingredient3 .33 I've tried the code in "https://stackoverflow.com/questions/17492374/how-to-render-formset-in-template-django-and-create-vertical-table" but when I implement it, I'm getting two extra column, "ID" and "Recipe Name". I don't know where those columns are coming from and I don't know how to get rid of them. Example: models.py class Recipe(models.Model): name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Recipe_Ingredient(models.Model): recipe_name = models.ForeignKey(Recipe, null=True, on_delete = models.SET_NULL) ingredient = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True) views.py def recipeUpdate(request, recipe_id): RecipeIngredientFormSet2 = inlineformset_factory(Recipe, Recipe_Ingredient, extra=10, fields=('ingredient', 'recipe_percent')) recipe = Recipe.objects.get(pk=recipe_id) formset = RecipeIngredientFormSet2(instance=recipe) context = {'formset' : formset} return render(request, 'accounts/recipe_form.html', context) recipe_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md-6"> <div class="card card-body"> <form action="" method="POST"> {{ form }} <p></p> <!--{{ formset.as_table }}--> <p></p> {{ formset.management_form}} <!--{% for form in formset %} {{ form }} … -
500 Internal Server error FLASK in cs50 finance problem set
This is the error: 192.168.14.251 - - [29/Dec/2021 18:18:26] "GET / HTTP/1.0" 500 - Error on request: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 323, in run_wsgi execute(self.server.app) File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 312, in execute application_iter = app(environ, start_response) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 338, in call self._flush_bg_loading_exception() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception reraise(*exc_info) File "/usr/local/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise raise value File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 314, in _load_app self._load_unlocked() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 330, in _load_unlocked self._app = rv = self.loader() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 240, in locate_app import(module_name) File "/home/ubuntu/finance/application.py", line 145 if len(rows) = 0: ^ SyntaxError: invalid syntax 192.168.14.251 - - [29/Dec/2021 18:18:26] "GET /favicon.ico HTTP/1.0" 500 - Error on request: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 323, in run_wsgi execute(self.server.app) File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 312, in execute application_iter = app(environ, start_response) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 343, in call rv = self._load_unlocked() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 330, in _load_unlocked self._app = rv = self.loader() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 240, in locate_app import(module_name) File "/home/ubuntu/finance/application.py", line 145 if len(rows) = 0: ^ SyntaxError: invalid syntax This is my code: @app.route("/register", methods=["GET", … -
django-filters filter by Boolean field with DRF
I'm following the tutorial here: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend (specifically the django-filter-backend section) and I am unable to get this to work. My goal is to retrieve a list of "containers" that have the "in_use" field set to True, but it keeps returning all the records in the table. I can't really see what I am missing. I have added django-filters to my installed apps list and also added this to my REST_FRAMEWORK block: 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] This is the API endpoint I'm trying to hit in postman: http://127.0.0.1:8000/displaydata/containers?in_use=True I've tried passing both 'True' and 'true', as well as 0s and 1s. views.py class ContainerViews(APIView): def get(self, request, id=None): if id: container = Container.objects.get(id=id) serializer = ContainerSerializer(container) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: containers = Container.objects.all() serializer = ContainerSerializer(containers, many=True) filter_backends = [DjangoFilterBackend] filterset_fields = ['in_use'] return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) -
Can't reach local server while Django app is running
When I run python manage.py runserver I get Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 29, 2021 - 17:45:15 Django version 4.0, using settings 'webapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. but when I try to open it in Chrome I'm only getting ERR_CONNECTION_REFUSED. Only a few hours ago it worked, I changed nothing. -
i create two function for dispaly place and blog in my project(web site) but only one function displaying
views.py def fun(request): obj=place.objects.all( ) return render(request,"index.html",{'results':obj}) def func(request): obj=blog.objects.all( ) return render(request,"index.html",{'blogresults':obj}) urls.py urlpatterns = [ path('', views.fun, name='fun'), path('', views.func, name='func'), ] -
Django startproject fails: No module named zoneinfo
I am creating a new project in Django. My set up is Windows 10 Django 4.0 Python 3.8 On running django-admin startproject myproject, I recieve the following error: ... ModuleNotFoundError: No module named 'zoneinfo' During handling of the above exception, another exception occurred: ... ModuleNotFoundError: No module named 'backports' Any clues on how to resolve this issue? -
Django - How to register route with query parameters?
Im very new to Django, struggling to find the answer Im looking for. Please bear with me. In my app/urls.py file I have router = routers.DefaultRouter() router.register(r'drugs', views.DrugViewSet) In my views.py file I have class DrugViewSet(viewsets.ModelViewSet): queryset = Drug.objects.all().order_by('name') serializer_class = DrugSerializer And my DrugSerializer class looks like class DrugSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drug fields = ('id', 'name', 'description', 'recommended_dose_mg', 'count', 'create_date', 'update_date') So when I do a GET on /drugs, I correctly get the list of drugs. And when I take a UUID (primary key) on a specific drug and do a GET on /drugs/<primary_key>, it correctly pulls the specific drug. However, I want the GET on /drugs/<primary_key> to display different data. I want to join it with another model that I have and return a new json response. How exactly would I do this? -
my chat app doesn't work after deployement - heroku django
I did a chatting part in my web app with django it works perfectly in local but after I deployed it to heroku , it doesn't work: this is my consumers.py class: from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth.models import User from django.db.models import Q from asgiref.sync import sync_to_async import json from chat.models import Thread, Message from users.serializers import UserSerializer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): friend = None me = self.scope['user'] # logged in user friend_name = self.scope['url_route']['kwargs']['friend'] # get the username of that user, whoom you want to chat friend_instance = await sync_to_async(User.objects.get, thread_sensitive=True)(username=friend_name) # get user object of friend # create a new Thread object if thread of specific chat does not exists, otherwise return the thread thread = None try: thread = await sync_to_async(Thread.objects.get, thread_sensitive=True)((Q(user1=me) & Q(user2=friend_instance)) | (Q(user1=friend_instance) & Q(user2=me))) except: thread = await sync_to_async(Thread.objects.create, thread_sensitive=True)(user1=me, user2=friend_instance) self.room_name = thread.room_name # room name await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): ''' disconnect the websocket connection. ''' await self.channel_layer.group_discard ( self.room_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] from_user = text_data_json['user'] to_user = text_data_json['friend'] from_user_instanse = await sync_to_async(User.objects.get, thread_sensitive=True)(username=from_user['username']) # get user object of friend to_user_instanse = await sync_to_async(User.objects.get, … -
How to actually prove that the user consented to data processing while he submitted the form?
A user submits a form and opts in to receive a newsletter. What do I need to do to prove later that he actually did opt in? If I store submitted form data in a db table then I am able to manually create and modify entries, so I could just change his False to True and therefore db entries don't prove anything. I have a django website if it makes any difference. -
Django render_to_string Returns NoneType Error
Using Django Pagination I'm trying to do endless pagination using AJAX. I followed the example here: https://www.progerhub.com/tutorial/adding-pagination-with-infinite-scroll-in-django/ My view returns the first page of results just fine, but when I attempt to build the content for the additional pages and return it as JSON using render_to_string I get an error while appending data onto my content variable. error message web_1 | Traceback (most recent call last): ... web_1 | File "/usr/src/django/media/views.py", line 74, in get web_1 | content += render_to_string('media_item.html', {'media': media, }, request=request) ... web_1 | new_obj = func(obj, *arg_vals) web_1 | File "/usr/local/lib/python3.8/site-packages/django/template/defaultfilters.py", line 784, in divisibleby web_1 | return int(value) % int(arg) == 0 web_1 | TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' models.py class Media(Audit): title = models.CharField( max_length=255) description = models.CharField( max_length=500, blank=True, null=True) poster = ProcessedImageField( blank=True, null=True, format='JPEG', options={'quality': 100}, processors=[ResizeToFill(1000, 1500)], upload_to=get_poster_path) class Meta: ordering = ( 'title', 'year') def __str__(self): return self.title views.py class MediaView(LoginRequiredMixin, JsonMixin, View): def get(self, request, *args, **kwargs): context = self.get_context_data() media = models.Media.objects.filter() page = int(request.GET.get('page', 1)) p = paginator.Paginator(media, 24) # number of media per page # try to get media for the given page try: media_page …