Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I test an Assertion Error thrown from my actual code in Django? [duplicate]
I am testing a function in Django using testcases.TestCase. I this function it is calling another function which asserts the passed parameters, and may throw AssertionError with a message. def another_func(data): assert len(data) > 0, 'Data cannot be empty' assert isinstance(data, dict), 'Input data must be a dict' # other code How do I test the returned error string? -
Using select2 on custom django forms and model forms
While reading the documentation of https://github.com/applegrew/django-select2, there is a note: "Django's admin comes with builtin support for Select2 since version 2.0 via the autocomplete_fields feature." I was able to enable autocomplete_fields for my admin site forms. The question is, is there any built-in functionality for custom and model forms where I need not install any third-party libraries? Is there any way I can leverage already included select2 functionality (for admin site) for model forms? I tried searching the same on google but could not find any documentation. This code is irrelevant but I thought my question should have some code so. models.py from django.db import models class Market(models.Model): CHOICES = [ ('IN', 'India'), ('US', 'United States'), ('EP', 'Europe'), ('JP', 'Japan') ] name = models.CharField(max_length=3, choices=CHOICES, blank=True, unique=True) class Product(models.Model): markets = models.ManyToManyField(Market) admin.py from django.contrib import admin class MarketAdmin(admin.ModelAdmin): search_fields = ['name'] class ProductAdmin(MarkdownxModelAdmin): autocomplete_fields = ['market'] forms.py from django.forms import ModelForm class ProductForm(ModelForm): class Meta: model = Product fields = ['markets'] -
Django REST Framework : ManyToMany relationship
I'm currently working on a Django project, I'm new at this and it's difficult to find clear documentation about this. My issue is very simple, I want at the creation of my model, automatically associate another model through a ManyToMany relationship. Here goes the code : Serializer : class FavoriteSerializer(serializers.ModelSerializer): estates = EstateSerializer(read_only=True, many=True) class Meta: model = Favorite fields = ['uuid', 'title', 'estates'] def create(self, validated_data): instance = super(FavoriteSerializer, self).create(validated_data) instance.save() return instance ViewSet : class MyFavoriteEstatesListViewSet(viewsets.ModelViewSet): serializer_class = FavoriteSerializer def get_queryset(self): return Favorite.objects.filter(users__id=self.request.user.id) I'm currently sending something like this through a POST : {"title": "some title", "estate_uuid": "XXX"} I just wanted to instantiate my Estate model with the UUID I just sent and adding it with favorite.estates.add(estate) How can I achieve this ? Thanks for your help ! -
GeoDjango migrate giving the following error - ValueError: Cannot use object with type int for a spatial lookup parameter
I'm trying to create a model with Geospatial field. When I try to migrate I receive the following error: Apply all migrations: admin, auth, contenttypes, map, sessions Running migrations: Applying map.0008_territorio_geometry...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Marco\Envs\um\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Marco\Envs\um\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Marco\Envs\um\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Marco\Envs\um\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Marco\Envs\um\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Marco\Envs\um\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\migrations\operations\fields.py", line 110, in database_forwards schema_editor.add_field( File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\backends\base\schema.py", line 450, in add_field definition, params = self.column_sql(model, field, include_default=True) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\backends\base\schema.py", line 223, in column_sql default_value = self.effective_default(field) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\backends\base\schema.py", line 303, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "C:\Users\Marco\Envs\um\lib\site-packages\django\db\models\fields\__init__.py", line 821, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\Marco\Envs\um\lib\site-packages\django\contrib\gis\db\models\fields.py", line 147, in get_db_prep_value super().get_db_prep_value(value, connection, … -
nesting of serializer in django
I wanted to access the details of other models while using the serializers and sending the json data back. However, when I am using the different models related to each other. It is not populating the data when I hit the API in postman. The Models I have are as follows: class OPlAss(models.Model): occ = models.ForeignKey(Occas) play = models.ForeignKey(Playlist) s_order = models.IntegerField(blank=True,null=True) s_nb_songs = models.IntegerField(blank=True, null=True) class Occas(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True ) playlists = models.ManyToManyField("Playlist", through='OPlAss', blank=True) class Playlist(models.Model): songs = models.ManyToManyField('Song', through='PlSongAss') Now I am creating a serializer of Occas, wherein I need the id, playlist, songs(which are in the playlist). class PlaylistSongSerializer(serializers.ModelSerializer): songs = serializers.SerializerMethodField() class Meta: model = OccassionPlAssociation fields = ('id','sequence_order','sequence_nb_songs','songs') @staticmethod def setup_eager_loading(queryset): queryset = queryset.prefetch_related('songs') return queryset def get_songs(self, obj): return obj.songs.all() class OccasionSerializer(serializers.ModelSerializer): playlists = PlaylistSongSerializer(many = True) class Meta: model = Occasion fields = ('id','name','algo_type','description','playlists') I get the output as below: [ { "id": 2, "name": "Test Brunch Mix", "description": "for testing", "playlists": [ { "id": 72, "songs": [] } ] }, { "id": 1, "name": "Test Halloween Mix", "description": "Perfect mix to bring all ghouls to the club.", "playlists": [ { "id": 467, "songs": [] … -
How to write complex select query in Django ORM
This select query is giving the result of all the channels where I am the admin and its order is most recent chat channel is on top. I want to make such a query in Django.. can anyone help me how can I create such a query in Django ORM? select c.id, c.name, CASE WHEN cc.created is null THEN '1970-01-01' ELSE cc.created END AS created FROM channel as c LEFT JOIN channel_admin as m on m.channel_id=c.id LEFT JOIN channelchats as cc on cc.channel_id=c.id AND cc."created" = ( SELECT max("created") FROM xchat_channelchats r1 WHERE c.id = r1.channel_id ) WHERE m.user_id=12 GROUP BY c.id, m.channel_id, cc.created ORDER BY created DESC; -
How do I model a team registration system in Django once a user logs in and get it to show on the homepage?
I'm trying to create a hackathon management system using Django 3. I've created an app 'accounts' which takes care of normal user registration to my website (name,email etc). In the backend django interface, I add these registered users manually to a list of hackathons I've created. The homepage of my website shows the list of hackathons and the people registered for them. Now what I want is for this logged in user to click on say, a register button on the homepage's sidebar which allows him/her to add names of his/her teammates, select a hackathon thereby registering themselves. Similar to what happened previously, I'd like the team names and details to show up on the homepage. How do I do this? These are the contents of my models.py files from the 'accounts' app: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # social github = models.CharField(max_length=30, null=True, blank=True) linkedin = models.CharField(max_length=30, null=True, blank=True) #others = models.CharField(max_length=30, null=True, blank=True) # tags TAGS = [ ('New', 'Newbie'), ('Developer', 'Developer'), ('Business', 'Business'), ('Designer', 'Designer'), ] phone = models.CharField(max_length=10, blank=True, default='') skillset = models.CharField(max_length=200, blank=True, default='') tags = models.CharField(max_length=15, default='New', choices=TAGS) bio = models.TextField(max_length=900, blank=True, default='') def __str__(self): return self.user.username # signal - every time a … -
Django filter for all items which contain at least one null value
An answer elsewhere on SO provides the Postgresql NOT(<table> IS NOT NULL) query as an option to find all rows in a table containing one or more null values. How would one apply this query in the Django ORM without writing raw SQL? Or is this a case where raw SQL is required? I couldn't find an example of such as query in the latest Django docs. For reference, the example shown in the linked answer is as follows: SELECT * FROM t; ┌────────┬────────┐ │ f1 │ f2 │ ├────────┼────────┤ │ (null) │ 1 │ │ 2 │ (null) │ │ (null) │ (null) │ │ 3 │ 4 │ └────────┴────────┘ (4 rows) SELECT * FROM t WHERE NOT (t IS NOT NULL); ┌────────┬────────┐ │ f1 │ f2 │ ├────────┼────────┤ │ (null) │ 1 │ │ 2 │ (null) │ │ (null) │ (null) │ └────────┴────────┘ (3 rows) -
Django upload files with with AJAX
I am uploading multiply files on backend with AJAX. How can I select file object from input? And how can I create AJAX request? var files = $('#filefield').prop('files'); Is it right? My ajax request: $.ajax({ url: '/tracks/', data: JSON.stringify(files), headers: { 'X-CSRFToken': $.cookie("csrftoken"), 'Content-Type':'application/json' }, cache: false, contentType: false, processData: false, method: 'POST', success: function(data){ alert(data); } Thanks for answers! -
Does anyone give me an example of implementing chain of responsibilities patterns inside Django framework? [closed]
I need to implement event that triggers series of activities in a sequential manner inside Django framework. -
Django Form DateInput with widget in update: loosing the initial value
I need a DateInput field in a ModelForm with the default HTML datepicker (I'm not using 3rd party libraries). Since the DateInput is rendered with <input type = "text"> by default, the datepicker is missing (it comes for free with <input type = "date">) I've found some examples explaining how to change the input type by handling widget parameters (below the code I've done so far) The issue I have the datepicker working correctly but in "update mode" when passing initial date value to the form (see view part), the date remains empty in the HTML. I've tried to find the cause and it seems that the 'type': 'date' part in the widget customization is clearing the initial value is some way; in fact, removing it, the initial value date is displayed again, but I loose the datepicker of course. In the view the date is passed with a valid value I also found another similar unanswered question where the field was declared as class DateInput(forms.DateInput): input_type = 'date' date_effet = forms.DateField(widget=forms.DateInput(format='%d-%m-%Y'), label='Date effet') the problem still remains My code model.py class TimesheetItem(models.Model): date = models.DateField() description = models.CharField(max_length=100) # many other fields here form.py class TimesheetItemForm(forms.ModelForm): def __init__(self, *args, … -
loading css with block in Django
I'm trying to load block for CSS in Django. However for some reason it doesn't work. my template : {% extends 'main/base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'main/style.css' %}"> {% endblock %} {% block title %}Some Title{% endblock %} {% block content %} Some Content {% endblock %} And below is the upper part of base.html file {% load static %} <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- This line below is the base styling, whereas the css file I'm trying to load is a specific styling for a specific page. --> <link rel="stylesheet" href="{% static 'base.css' %}"> {% block css %} {% endblock %} <title>{% block title %}{% endblock %}</title> </head> I have the right css file at the right directory, but it is not reflected at all. I don't see what I've done wrong. I would very much appreciate your help. :) -
Jquery not sending correct item id in Django
I'm trying to send some form data in django via ajax. the data i'm sending is the item id of objects. But when i'm making the ajax call it is not sending the correct item id. sometimes it is sending the id of the first item only. views.py def contact(request): msg = Message.objects.all() if request.POST.get('action')=="post": idi = request.POST.get('id') print(idi) ms = Message.objects.get(id = idi) print(ms) return render(request, "dashboard/contact.html", {"msg": msg, "ms": ms}) return render(request, "dashboard/contact.html", {"msg": msg}) ajax $(function() { // Remove button click $(document).on( 'click', '.ida', function(e) { e.preventDefault(); var pk = $(this).attr('value') $.ajax({ type: "POST", url: '{% url "contact" %}', data: { id: pk, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: "post", }, success:function(){ console.log(pk) } }); }); }); form <form> {% csrf_token %} <input type="hidden" name="id" value="{{m.id}}" id="id"> <button type="button" class="btn btn-success ida" data-toggle="modal" data-target="#exampleModal">View</button> </form> Thanks in advance. -
With Django, can I reset primary key of all existing records?
Say I have a model Client: class Client(models.Model): name = ... address = ... And I imported a list of 1000+ clients to the model, with django-import-export. It worked like a charm. However, the ids (primary key) of the records aren't start from 1. It seems that by importing the clients, ids from 1 to 1000+ are used by django-import-export, and the imported client instances using id from 1000+. No harm but not beautiful. So is it possible to reset all the records' ids from 1? Does sqlsequencereset work in this situation? -
Django Rest Framework + Django CAS
I've been tasked with adding CAS authentication to an existing Django app which uses the Django Rest Framework. Using django-cas library I'm able to authenticate via CAS to the admin features of the Django framework, but I'm not sure how to go about authenticating the Django rest framework app via CAS; it's still authenticating via some custom authentication logic that the original developers added. If anyone has any insight or experience with this it would be much appreciated. -
Django model React
I'm trying some Django + React stuff and I'm a bit confused with the particular role of Django model in this scheme. As I can understand Django model provide smooth way to create some typical forms by users of the site (please correct me). And I can't feel the edge of what should be hardcoded and what I need to store in model. In case of React (I'm trying to connect react with django through api via djangorestframework) should I create a model for Header? And store bg image with it and my slogans. I feel it's should be purely in frontend. But next section with 3 typical screens (they will be listed horizontally and swap each other). They are just copy of each other with different data (title, bg, fg, text, link), for me it seems closer to model usage. But model initially empty and if I want to get this data from model I firstly need to somehow store this data to model. ofc I searched this info widely but so far can't create clear understanding by myself. Thanks ) -
Delete files and directories that are older than 30 days in specific path [closed]
How can I delete all the files and directories in a specific directory that are older than 30 days? -
Refresh displayed data on click in Django app
I am using Ajax to get the appropriate url that displays orders based on the date that was clicked in a calendar. This works, but every time user clicks on a date, the content duplicates, not removing the previous display. https://i.stack.imgur.com/nEdWg.png I would like the content to refresh, when the user clicks on a date again. How would I do that? I was searching for a "Jquery refresh DIV", and stumbled upon location.reload(), ajax.reload(), jquery load method, and similar solutions. I tried implementing these, but not sure if they are the right solution for my case. Here is my code. Please let me know if I should post anything else. Help appreciated. .js $(function () { var $archive = $('#orders-per-day'); $(".day-click").click(function (event) { event.preventDefault(); var day = $(this)[0].innerText; var month = $(".month")[0].innerText.substring(0, 3); var year = $(".month")[0].innerText.substr(-4); console.log(year); $.ajax({ type: 'GET', url: `/ocal/date/${year}/${month}/${day}/`, success: function (data) { $archive.append(data); } }) }); }); html template for showing the orders of one day {% extends 'ocal/base.html' %} {% block content %} <h1>Orders for {{ day }}</h1> <ul> {% if object_list %} {% for order in object_list %} <li> <a href="/ocal/{{ order.id }}/detail">Order {{ order.id }} </a> {{ order.status_str }} </li> {% endfor … -
Django Dynamic form for manytomany relationship
I am trying to make a form which includes the functionality of Add/Delete Row. This question needs a detailed answer and it's quite important Models.py class Inserts(models.Model): no_of_inserts_perit = models.IntegerField(default=0, blank=True, null=True) insert_length = models.IntegerField(default=0, blank=True, null=True) insert_breadth = models.IntegerField(default=0, blank=True, null=True) insert_height = models.IntegerField(default=0, blank=True, null=True) class Pfep(models.Model): created_by = models.ForeignKey("packsapp.Employee", on_delete=models.CASCADE, related_name='ffco_createdby') receiver = models.CharField(max_length=250, default=0 ,blank=True, null=True) receiver_location = models.CharField(max_length=250, default=0 ,blank=True, null=True) inserts = models.ManyToManyField(Inserts) In my form I need a Add Row and Delete Row button for inserts fields. I have never worked with a manytomany relationship but upon googling I ended up with the conclusion that inline_formset is used for this, is it ? This is how I am creating the rest of form: Views.py @method_decorator([login_required, employee_required], name='dispatch') class PfepFormView(CreateView): model = Pfep form_class = Pfepform template_name = 'pfep/PfepForm.html' def form_valid (self, form): if self.request.user.employee.employee_role == 'admin': product = form.save(commit=False) product.created_by = Employee.objects.filter(user=self.request.user.id)[0] product.save() messages.success(self.request, 'The PFEP was created with success!') return redirect('emp:pfep_table') else: messages.success(self.request, "You don't have permission to create PFEP!") return redirect('emp:pfep_table') return redirect('emp:pfep_table') Forms.py class Pfepform(forms.ModelForm): class Meta: model = Pfep fields = '__all__' exclude = ["created_by"] HTML <h2 class="mb-3">Add a new PFEP</h2> <div class="row product-form-row"> <form method="post" class="col-md-12 proct-form" novalidate> … -
Django button to run script (to populate a database)
I have a pre-built python script that collects Google Analytics data, I am using this script to populate a database. I have been given the instruction to write a web app where all of this data can be displayed in the form of a dashboard.. I want the user of the web app to be able to click on a button and then all the latest Google Analytics data will be pulled and added to the database in the backend and then the dashboard will display updated values.. But it seems like I can only add data to the db via the python shell? I have a script that can do that.. But I am confused as to where in django should I have this script and how to implement it Should I put it in views, models or a separate file PS: I would post the script but it is 400 lines of code to get that data -
Problem with dynamic image path in Django
I'm trying to pass a dynamic url of an image, to be displayed in a template. This is my view function: def success(request): id_image = request.session.get('image_id') obj = EvalImage.objects.get(id=id_image) url = obj.Patient_Main_Img.url return render(request, 'myapp/success.html',{'image_url': url}) If I call {{image_url}} in the template, I get the correct path: myapp/media/images/15_LgiRvs6.jpeg But, if I use it into a img tag, like the following: <img src="{{image_url}}" class="rounded mx-auto d-block" alt="RX" width="300" height="300"> I get an error because the template is unable to find the file. The problem is that the template is looking for the file at: /myapp/eval/myapp/media/images/15_LgiRvs6.jpeg I don't understand why is the tag changing the path to the file. From settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'myapp/media') MEDIA_URL = 'myapp/media/' Thank you -
How do i show the list of items which belong to the same category using Django Python?
I have Shop page and it displays list of shops when i click on one shop i want the other page to display the related list of products for that page only. def shop_products(request, id): shops = Product.objects.all() return render(request, 'products/shop_products.html', {'shops': shops}) path path('products/<int:id>', views.shop_products, name='shop-products'), <a href="{% url 'shop-products' product.id %}" class="grey-text"> The clickable link Using the above code it is displaying all the products of every shop -
How to delete multiple objects in django?
I am trying to delete django model multiple objects using html checkboxes but i can't. Kindly guide me what I need to do complete my this task. I try the following code for this purpose but i failed. views.py class DeleteProducts(SuccessMessageMixin, View): success_url = reverse_lazy('stock:stock') success_message = "Products are deleted successfully." def post(self, request, *args, **kwargs): products = self.request.POST.getlist('product') Product.objects.filter(pk__in=products).delete() messages.success(self.request, self.success_message, extra_tags='alert-danger') return redirect('stock:stock') In template i used checkboxes prefectly or not?? template.html <form method="POST" action="{% url 'stock:deleteproducts' %}"> {% csrf_token %} {% for product in page_obj %} <div class="row" > <input type="checkbox" value="{{ product.id }}"> <div class="col-sm-2" > <h5>{{ product.id }}</h5> <img src="{{ product.Picture.url }}" height="120px" /> </div> <div class="col-sm-4" > <h5><u>Product Name</u>: {{ product.pro_name }}</h5> <h6><u>Company Name</u>: {{product.companyName}}</h6> <div class="row" > <div class="col-sm" > <p>Purchase Price: <b>{{product.Purchase_Price}}</b></p> </div> <div class="col-sm" > <p class="pt-0">Sale Price: <b>{{product.Sale_Price}}</b> </p> </div> </div> <div class="row" > <div class="col-sm" > <p>Quantity <b>{{product.Quantity}}</b></p> </div> <div class="col-sm" > <p> Added By: <b>{{product.saler}}</b> </p> </div> </div> </div> <div class="col-sm-4" > <p><b>Added Date</b>:{{ product.pub_date }}</p> <hr/> <center> <a href="{% url 'stock:editproduct' product.id %}" class="btn btn-success" >Edit</a> </center> </div> </div> <hr/> {% endfor %} <input type="submit" class="btn btn-danger" value="Delete" > </form> urls.py path('delete/', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'), -
self.scope['user'] in Django channels keeps showing up as AnonymousUser
When I log in to my front end, my self.scope['user'] call in my friends.consumer.py in django channels returns AnonymousUser but when login and call self.scope['user'] in my chat.consumer.py it shows up as the logged in user. For some reason the scope['user'] in one of my apps work and the other one does not. I do not understand what the problem is. I have the routing set up in my django project as this routing.py from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import chat.routing import friends.routing application = ProtocolTypeRouter ({ 'websocket': AuthMiddlewareStack( URLRouter( friends.routing.websocket_urlpatterns + chat.routing.websocket_urlpatterns ) ) }) I structure my second consumer.py similarly to my first consumer.py. This is my consumer.py where the scope['user'] works (I didn't need the scope['user'] in the first consumer but I just wanted to test to see if it works chat.consumer.py class ChatConsumer(WebsocketConsumer): ... def connect(self): print(self.scope['user']) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() This code is the consumer where my scope['user'] shows up as anonymous user even after I have logged in. friends.consumers.py class FriendRequestConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope['user'] grp = 'notifications_{}'.format(user.username) self.accept() async_to_sync(self.channel_layer.group_add(grp, self.channel_name)) Here are also my … -
How to use dynamic tabs in django?
I am trying to implement dynamic tabs in my project that gives multiple tabs based on the values stored in the database. In my case, I have two values stored in database so it's displaying just two, If I will increase more, it will show accordingly. Category.objects.filter(category='MEDICINES') Out[14]: <QuerySet [<Category: FRUITS>, <Category: GRAINS>]> Here is my models.py file, from django.db import models from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Publish")) class Category(models.Model): category_names = ( ('DISEASES','DISEASES'), ('MEDICINES','MEDICINES'), ('ENCYCLOPEDIA','ENCYCLOPEDIA'), ) category = models.CharField(max_length=100, choices=category_names) sub_category = models.CharField(max_length=100, unique=True) def __str__(self): return self.sub_category class Medicine(models.Model): title = models.CharField(max_length=200, unique=True) display_name = models.CharField(max_length=17, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='medicine_posts') category = models.ForeignKey(Category, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("medicine_detail", kwargs={"slug": str(self.slug)}) Here it my views.py file, from django.views import generic from .models import Medicine, Category from django.shortcuts import render, get_object_or_404 class MedicineList(generic.ListView): queryset = {'medicine' : Medicine.objects.filter(status=1).order_by("-created_on"), 'category' : Category.objects.all() } #queryset = Medicine.objects.filter(status=1).order_by("-created_on") print(queryset) template_name = "medicine.html" context_object_name = 'element' #paginate_by = 10 Here is my medicine.html file, <div class="container"> <div class="row"> …