Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create empty dictionaries from a list of strings
If I have a list of strings like variations = ['color','size','quantity'] Is it someway possible to convert the strings in a list to empty dictionaries? The result I want is color = {} size = {} quantity = {} -
How to hide a category without articles?
I have articles combined by categories. Here are data models: class Category(models.Model): name = models.CharField(max_length=200, verbose_name='Наименование') slug = models.SlugField(max_length=250, verbose_name='URL') created = models.DateTimeField(auto_now_add=True, verbose_name='Добавлено') objects = models.Manager() class Meta: ordering = ('name',) verbose_name = 'категорию' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('main:article_list_by_category', args=[self.slug]) class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Черновик'), ('published', 'Опубликовано'), ) TYPE_ARTICLE_CHOICES = ( ('Руководство', 'Руководство'), ('Инструкция', 'Инструкция'), ) title = models.CharField(max_length=250, verbose_name='Заголовок') slug = models.SlugField(max_length=250, unique_for_date='publish', verbose_name='URL') type_article = models.CharField(max_length=15, choices=TYPE_ARTICLE_CHOICES, default='Инструкция', verbose_name='Тип статьи') category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE, verbose_name='Категория') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts', verbose_name='Автор') body = RichTextUploadingField(verbose_name='Статья') publish = models.DateTimeField(default=timezone.now, verbose_name='Опубликовано') created = models.DateTimeField(auto_now_add=True, verbose_name='Добавлено') updated = models.DateTimeField(auto_now=True, verbose_name='Обновлено') status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='draft', verbose_name='Статус') tags = TaggableManager() private = models.BooleanField(default=False, verbose_name='Приватная статья') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) verbose_name = 'статью' verbose_name_plural = 'Статьи' index_together = (('id', 'slug'),) indexes = [GinIndex(fields=['title'])] def __str__(self): return self.title Here is the output template: <div class="container my-container-style"> <div class="row"> <div class="col-md-3"> <h4 class="mb-4 category">Категории</h4> <div id="sidebar"> <ul> <li {% if not category %} class="selected" {% endif %}> <a href="{% url 'main:articles_list' %}">Все</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %} class="selected" {% endif … -
How to add dynamic field in model or database using django
I want have created a table but I want to create fields from frontend by using HTML form. In that HTML form I am giving table name , field name, datatype, max length. If user add any field then it should update table and add that field to database. -
Angular map flower (celery+django) return to list of tasks
I want to map the return of the flower libary (/api/tasks) to a list of objects. Currently it returns multiple objects, but without the "list wrapper", so it's not possible to iterate that. API: https://flower.readthedocs.io/en/latest/api.html#get--api-tasks Return is for example: HTTP/1.1 200 OK Content-Length: 1109 Content-Type: application/json; charset=UTF-8 Etag: "b2478118015c8b825f7b88ce6b660e5449746c37" Server: TornadoServer/3.1.1 { "e42ceb2d-8730-47b5-8b4d-8e0d2a1ef7c9": { "args": "[3, 4]", "client": null, "clock": 1079, "eta": null, "exception": null, "exchange": null, "expires": null, "failed": null, "kwargs": "{}", "name": "tasks.add", "received": 1398505411.107885, "result": "'7'", "retried": null, "retries": 0, "revoked": null, "routing_key": null, "runtime": 0.01610181899741292, "sent": null, "started": 1398505411.108985, "state": "SUCCESS", "succeeded": 1398505411.124802, "timestamp": 1398505411.124802, "traceback": null, "uuid": "e42ceb2d-8730-47b5-8b4d-8e0d2a1ef7c9", "worker": "celery@worker1" }, "f67ea225-ae9e-42a8-90b0-5de0b24507e0": { "args": "[1, 2]", "client": null, "clock": 1042, "eta": null, "exception": null, "exchange": null, "expires": null, "failed": null, "kwargs": "{}", "name": "tasks.add", "received": 1398505395.327208, "result": "'3'", "retried": null, "retries": 0, "revoked": null, "routing_key": null, "runtime": 0.012884548006695695, "sent": null, "started": 1398505395.3289, "state": "SUCCESS", "succeeded": 1398505395.341089, "timestamp": 1398505395.341089, "traceback": null, "uuid": "f67ea225-ae9e-42a8-90b0-5de0b24507e0", "worker": "celery@worker1" } } Any ideas how to do that? I've tried the following thing: export interface Tasks { tasks: TaskWrapper[] } export interface TaskWrapper { [uuid: string]: Task } export interface Task { uuid: string, state: string, received: string, } -
Creating list of verbose field names to iterate through in Django template, but nothing rendering
I am creating a profile page for a web application. I am displaying a users profile, which is an instance of my profile model, matched based on the Users pk. Within the html, I want this to render as follows: verbose_field_name: field_value Or for example: First Name: John Surname: Lewis I had it so that it was rendering the actual field name, for example: first_name: John surname: Lewis Which worked, however as soon as I have tried to add in and iterate through the verbose field names, it is not working. My model is: class Profile(models.Model): # Get access to create profile by default MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True) # profile_image = models.ImageField(blank=True, null=True) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True) first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True) surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True) gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True) emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True) emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True) business = models.ForeignKey(BusinessProfile, null=True, blank=True, … -
Hello everybody, I'm learning django and creating the review system. I think someting with Html is wrong
I created the form and added it to view, how I must add it to html form? index.html <form action="." method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> <h1 style="margin:0 57%">Reviews</h1> <input type="hidden" name="parent" id="contactparent" value=""> <div class="dfv" style="display:flex; padding: 5%; justify-content: space-around; flex-wrap: wrap;align-items:center; box-shadow:4px 4px 16px gold;width: 80%;margin:8% 18% 0"> <div class="form-group editContent"> <label for="contactcomment" class="editContent" placeholder=" Message" > Your reviews * </label> I added action through url but it didn't worked -
Django REST Framework AttributeError: 'MCQ_Exam' object has no attribute 'questions'
I am trying to build a serializer for my database in django using the django rest framework but i want to add one model as a field to the serializer of another model and somehow it worked for one model serializer but not the other. so for the "Question" model, i was able to add the serializer of the "Answer" model as a field and it worked perfectly. the "MCQ_Exam" model on the other hand gives me an AttributeError: Serializer object has no attribute "questions" whenever i try to open the url. I added the "many=True" field to all the serializer variables as you can see and yet it still works for one model and not the other -
Django views are not rendering in template
Can someone tell me what I'm doing wrong here? The 1st function(all_products) renders in template perfectly, but the last 2 does not. models.py # TABLE BRAND class Brand(models.Model): name = models.CharField(max_length = 50) # TABLE PRODUCT class Product(models.Model): title = models.CharField(max_length = 100) brand = models.ForeignKey(Brand, on_delete = models.CASCADE) image = models.ImageField(null = False, blank = False, upload_to ="images/",) price = models.DecimalField(max_digits = 100, decimal_places = 2, ) created = models.DateTimeField(auto_now_add = True ) the functions in the views.py def all_products(request): products = Product.objects.all() return render(request, 'store/home.html', {'products': products}) def newest_products(request): sixNewestProduct = Product.objects.all().order_by('-created')[:6] return render(request, 'store/home.html', {'sixNewestProduct': sixNewestProduct}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name= 'all_products'), path('', views.newest_products, name= 'newest_products'), path('', views.newest_discount, name= 'newest_discount'), ] the template part look like this: {% for new in sixNewestProduct %} <a href="#" class=""> <div class="newProduct"> <img src="{{new.image.url}}" alt=""> </div> <h5>{{new.brand.name}}</h5> <h4>{{new.title}}</h4> <p>{{new.price}} GNF</p> </a> {% endfor %} -
How to write relation where first model is connected to exactly four instances of another in Django?
Let's say I have two very basic model classes - for simplicity let's name them a Plan and a Task. My goal is to force every plan to have exactly 4 distinct tasks (order doesn't matter). Is there some good practice for this "many-to-many with a fixed quantity of related instances" case? from django.db import models class Task(models.Model): name = models.CharField(max_length=20) class Plan(models.Model): name = models.CharField(max_length=20) # four_tasks = ? I searched through Django documentation but there's no answer there (or maybe I didn't know how to search for it). I thought of 4 separate foreign keys (which should be possible by setting related_name for those) in Plan, or maybe standard many-to-many many relations. Both solutions require additional checks to ensure that there are actually 4 different tasks and they look ugly to me. -
How can I print values from the data base
So I want to print values that was in the database repeatedly when ever it is updated. Like lets say a client payed 30$ from the total amount of his service which is 50$, he will be left With 20$. Something that looks like this: (service price = 50$ first payment= 30$ balance= 20$ Date = 11/12/2022) So the next time he comes to pay for the rest, its shown what he paid last time with the date. The 2nd payment: (service price = 50$ first payment= 30$ balance= 20$ Date = 11/12/2022 service price = 50$ Second payment= 20$ balance= 0$ Date = 11/22/2022) so on with his transactions regarding that service. I'm kind losing my mind because I don't know where to move with this, so help! this is the code : models.py class Appointment(models.Model): patient = models.ForeignKey(Patient, on_delete = models.CASCADE) doctor_of_appointment = models.ForeignKey(Doctor, on_delete = models.CASCADE, related_name='doctor_of_appointment') receptionist_of_appointment = models.ForeignKey(Doctor, on_delete = models.CASCADE, related_name='receptionist_of_appointment') appointment_date = models.DateField(null=False, blank=False) #appointment_timeslot = models.ForeignKey(TimeSlot, on_delete = models.CASCADE) appointment_timeslot = models.CharField(max_length=100, default='') appointment_description = models.CharField(max_length=1000, null=True, blank=True) examine_result = models.CharField(max_length=1000, default='', null=True, blank=True) drugs = models.CharField(max_length=1000, default='', null=True, blank=True) appointment_status = models.CharField(max_length=10, choices=(('Pending', 'Pending'), ('Completed', 'Completed'), ('Canceled', 'Canceled')), default='Pending') #Invoicing Section … -
OperationalError in Django while updating model
I am facing OperationalError while updating the model in an existing Django project. These are my installed apps in settings INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "admin1_app.apps.Admin1AppConfig", ] This is code in admin from django.contrib import admin from admin1_app.models import Product class Product_admin(admin.ModelAdmin): list_display=["product_name","product_price","product_qty","product_category"] admin.site.register(Product,Product_admin) models.py from django.db import models class Product(models.Model): product_name=models.CharField(max_length=30) product_price=models.IntegerField() product_qty=models.IntegerField() product_category=models.CharField(max_length=35) def __str__(self): return self.product_name Iniatially a program was created with only 3 columns i.e., product_name, product_price, product_qty, and everything was done correctly. Later, I added product_category to this existing project and I also ran makemigrations and migrate commands. But I'm experiencing an OperationalError. OperationalError at /admin/admin1_app/product/ (1054, "Unknown column 'admin1_app_product.product_category' in 'field list'") Request Method: GET Request URL: http://127.0.0.1:8080/admin/admin1_app/product/ Django Version: 4.1.2 Exception Type: OperationalError Exception Value: (1054, "Unknown column 'admin1_app_product.product_category' in 'field list'") Exception Location: C:\Users\narendra\anaconda3\lib\site-packages\pymysql\err.py, line 143, in raise_mysql_exception Raised during: django.contrib.admin.options.changelist_view Python Executable: C:\Users\narendra\anaconda3\python.exe Python Version: 3.9.12 I tried using the python manage.py migrate --fake command . I don't know how it works but just copied it from some other similar error solution in Stack Overflow, however there is no result I even tried deleting the 0001_initial.py file in the migrations folder and then repeated the makemigrations command, … -
Django admin button for fields to trigger action
In the Django admin change form of my model I would like to be able to add a button next to any field. Clicking this button should call some function with the current form data as input. Once the function returns, the Django admin form should be updated by the return values of the function. I know of one way to add a button at the very bottom of the admin model change pape, right below the save button, but this is not what I want. The button should be right next to the specific input field. Currently, I have no idea where to start and conceptionally how this is achieved. I googled a lot, but couldn't find a solution yet. I thought of creating a new form widget that I could assign to an inputfield, but buttons in forms are not available in django. -
Change Django theme based on logged in, profile, or toggle
I would like to allow the user to have the ability to change the theme based on the following factors: Anonymous Check localStorage and if empty use default else use localStorage Authenticated Check localStorage and if empty use user profile setting I have it all working except for Authenticated users, I don't know how to check localStorage. {% if user.is_authenticated %} <body class="theme-{{user.profile.theme}}"> // How can I check localStorage.getItem('theme') and if null use {{user.profile.theme}} {% else %} <body> <script> var theme = localStorage.getItem('theme') if(theme == 'light'){ document.body.classList.add("theme-light") } else if (theme == 'dark'){ document.body.classList.add("theme-dark") } else { document.body.classList.add("theme-light") } </script> {% endif %} -
run a script to fill in a model
I have a script that fills a model (a table) with data. To run the script I do python manage.py shell < script.py it worked correctly several times but there it no longer fills the table I don't know why. import names from app.models import Employee, Sector from random import randint s1 = Sector.objects.create(namesector="marketing", codesector="MKT"); s1.save() for i in range(10): n = names.get_full_name().split(" ") p = Employee.objects.create_user(firstname=n[0], name=n[1], regID=str(i).zfill(2), codesector="MKT", password=str(i).zfill(2)) p.save() Only s1 is added to the Sector table, the employee table remains empty. When i write line by line directly in the shell the data is added correctly for the employee table. -
Normalize string before saving it in third-party model field
I'm looking for a way to modify a string before saving it in a third-party model field. IMPORTANT: The field should be unique, eg. has unique=True Let's say I have a function that makes string lowercase and removes dashes. def normalize(string:str): return string.lower().replace('-','') I want to make sure that only strings that went through this function are stored in the field (I don't expect using Model.update()) This solution looks good but has a big disadvantage: @receiver(pre_save, sender=TheThirdPartyModel) def normalize_the_field(sender, instance, **kwargs): instance.the_field = utils.normalize_the_field(instance.the_field) this way I can be sure there are only normalized strings in the DB but as it's unique=True ModelForm and admin doesn't raise validation errors when saving it. If there is already "xxx" in a DB and I type "XXx" (different case) - Django admin doesn't raise validation error, rather it returns an exception which I don't want. Is there a way to make it work? I can't redefine the field dynamically as migrations would be created in the third-party directory in virtual environment. -
Display verbose name on profile page Django DetailView (specific model instance)
I am working on a page to display a users profile. I have successfully rendered an instance of the users profile, which looks as shown in the screenshot below. The thing I want to change, is to display the verbose name of the field names, rather than the actual field name. I have done some research but am not sure how to implement this with my current set up. My models.py: class Profile(models.Model): MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True) first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True) surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True) gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True) emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True) emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True) business = models.ForeignKey(BusinessProfile, null=True, blank=True, on_delete=models.SET_NULL) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) Views.py: class ShowProfileView(DetailView): model = Profile template_name = 'profiles/user_profile.html' def get_context_data(self, *args, **kwargs): context = super(ShowProfileView, self).get_context_data(*args, **kwargs) # super gives access to parent class methods user_profile = … -
KeyError: 'use_threading' not letting me runserver
I'm new to coding in Python so bear with my errors. I keep encountering this error even when I haven't added anything into the code yet. Any help is much appreciated! `` Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(self._args, self._kwargs) File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run threading = options["use_threading"] KeyError: 'use_threading' note: i did migrations and makemigrations just in case but i still get the same error. -
Authentication in microservice application that has different frameworks/ programming language
I am a bit confused on how to implement a authentication with a microservice architecture if my microservices use different FW such as node, django, go ... is there a common token type that can be interpreted by all the FW available? CRSF tokens are universal in different FW/programming languages, what about JWT, what is the most recommended approach? get a token store in the front end and for every microservice validate the token before actually doing something? remembering that every MS would be written in different FW and Programming language -
Django order by combination of direct and related fields
I have the following models: class Product(models.Model): name = models.CharField(max_length=50) stock_quantity = models.IntegerField() class Variation(models.Model): parent_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations') stock_quantity = models.IntegerField() what I want to do is sort a queryset of Products by stock_quantity. Now, I have two types of products: simple products, who have a stock_quantity directly attached to them variable products, who have a stock_quantity of None, but have Variations that point to them via the foreign key. In that case, the variations all have a stock_quantity For variable products, I want the sum of all the variation stock quantities to be relevant for sorting. How can I do that? I do have some ideas about annotations and aggregates in my mind, but not sure how to fit this all together. Thanks! -
cannot access local variable 'nr' where it is not associated with a value
def NearByDoc(request): if request.method == "POST": nearby = request.POST.get("NearBy") nr = nearby return render(request,'nearbyDoc.html',{'nrb':NearBy_Doctor.objects.all(),'near':nr}) How can I pass "nr" variable to the dictionary? Help me to solve this. I'm new at Django. -
Why is my django table not being found during testing?
I am trying to unit test a model that has an abstract model embedded in it but the table can't be found. I have tried deleted migrations and the db and after making new migrations, am still getting the same result. I have also tried the following command: py manage.py migrate --run-syncdb error Traceback (most recent call last): File "C:\main_venvs\prompted\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\main_venvs\prompted\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: boards_board models.py from django.db import models from .behaviors import PermalinkAble class Board(PermalinkAble, models.Model): short_name = models.CharField( max_length=3, unique=True ) long_name = models.CharField( max_length=24, unique=True ) info = models.TextField( max_length=300 ) url_name = 'board' def __repr__(self): return self.short_name @property def slug_source(self): return self.short_name behaviors.py from django.db import models from django.contrib.auth.models import User class PermalinkAble(models.Model): slug = models.SlugField() class Meta: abstract = True test_models.py from django.test import TestCase from prompted.boards.models import Board class BoardTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: Board.objects.create( id=1, short_name='nope', long_name='what the nope', info='what the actual nope', ) test_board = Board.objects.get(id=1) -
Google map widget in Django admin
I have a model with a location field like so: from django.contrib.gis.db import models as gis_models class Facility(models.Model): location = gis_models.PointField(srid=4326, verbose_name=_('location'), null=True, blank=True) I want the user to be able to set a location using a map in django admin. I have added the below code in my django admin: from django.contrib.gis.db import models as gis_models from mapwidgets.widgets import GooglePointFieldWidget @admin.register(Facility) class FacilityAdmin(admin.ModelAdmin): formfield_overrides = { gis_models: {'widget': GooglePointFieldWidget}, } at the end I have added the following setting to my settings.py: MAP_WIDGETS = { "GooglePointFieldWidget": ( ("zoom", 12), ("mapCenterLocation", [ 50.8157, 9.1846]), ), "GOOGLE_MAP_API_KEY": env('GOOGLE_MAP_API_KEY') } I am using postgis image as my database and the following is my requirements.txt: asgiref==3.5.2 async-timeout==4.0.2 branca==0.5.0 certifi==2022.9.24 chardet==5.0.0 charset-normalizer==2.1.1 click==8.1.3 colorama==0.4.6 Deprecated==1.2.13 Django==4.1.2 django-crispy-forms==1.14.0 django-environ==0.9.0 django-map-widgets==0.4.0 django-rq==2.5.1 folium==0.13.0 idna==3.4 Jinja2==3.1.2 lml==0.1.0 MarkupSafe==2.1.1 numpy==1.23.4 packaging==21.3 pandas==1.5.1 Pillow==9.2.0 postgis==1.0.4 psycopg2==2.9.4 pyexcel==0.7.0 pyexcel-io==0.6.6 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.5 redis==4.3.4 requests==2.28.1 rq==1.11.1 six==1.16.0 sqlparse==0.4.3 texttable==1.6.4 tzdata==2022.5 urllib3==1.26.12 wrapt==1.14.1 The map appears in django admin, but as it turns out, it doesn't read the settings. Also the styling of the map is just unacceptable. Is there any way it could be fixed? Right now this is what I'm getting in my django admin panel: -
Escaping html in admin list display, tinymce
Cannot find anyhere. My list display (content) shows html tags after installing tinymce editor. Do I need to find admin panel html template? -
designed django cart shopping
My shopping cart is designed in such a way that the user must be logged in. How can I design the shopping cart with these two conditions that it must be stored in the database and not in the session and that the user does not need to login to add the product to the shopping cart? my model : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return self.user.username my view : def cart_detail(request): cart = Cart.objects.filter(user_id=request.user.id) return render(request, 'cart/cart.html', {'cart': cart, }) -
I have a few categories and I would like to list the products per category
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get the categories but not the products to show in my HTML. I m new in django cant find the solution in models.py: from django.utils import timezone from distutils.command.upload import upload from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Main_Category(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Sub_Category(models.Model): main_category=models.ForeignKey(Main_Category,on_delete=models.CASCADE) name=models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): Status=('publish','publish'),('draft','draft') product_id=models.AutoField name=models.CharField(max_length=50) category=models.ForeignKey(Main_Category,on_delete=models.CASCADE,null=True,default="") sub_category=models.ForeignKey(Sub_Category,on_delete=models.CASCADE,null=True,default="") price=models.IntegerField(default=0) des=models.CharField(max_length=2000) status=models.CharField(choices=Status,max_length=200) delivery=models.IntegerField(null=True) date=models.DateTimeField() image=models.ImageField(upload_to="shop/images",default="Status") slug=models.CharField(max_length=150) def __str__(self): return self.name @property def get_products(self): return Product.objects.filter(categories__title=self.name) class Orders(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) amount=models.CharField(max_length=55) Order_id=models.AutoField(primary_key=True) name=models.CharField(max_length=55) email=models.CharField(max_length=30) address=models.CharField(max_length=200) phone=models.CharField(max_length=15) city=models.CharField(max_length=20) state=models.CharField(max_length=20) zip_code=models.CharField(max_length=10) date=models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username class OrderItem(models.Model): order=models.ForeignKey(Orders,on_delete=models.CASCADE) product=models.CharField(max_length=200) image=models.ImageField(upload_to="shop/images/cust_image") quantity=models.CharField(max_length=20) price=models.CharField(max_length=15) total=models.CharField(max_length=1000) def __str__(self): return self.order.user.username Views.py from django.shortcuts import redirect, render from .models import Main_Category, Product,Sub_Category,Orders,OrderItem from django.core.paginator import Paginator from django.contrib.auth.decorators import login_required from cart.cart import Cart from django.contrib.auth.models import User,auth from django.contrib import messages # Create your views here. def index(request): allproduct=Product.objects.all() …