Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modal content not updating
I have a pretty basic JS modal right now, but the content is not loading from the modal.html call. Here is my function: var modal = $('#userModal') var button = $('submit') button.on('click', function(event) { var str = "Testing content" $("#modal_body").html(str) modal.modal("show") The modal_body is a paragraph with the ID "modal_body". The modal is opening but the variable "str" content is not populating. Am a beginner to Ajax working in a Django Jinja2 template. Thank you! -
Django fails to process ManyToMany form field within view to create and save new model instance
I have two Models with a ManyToMany relationship. In my view I want to process the user input of the MultipleChoicesField and assign the selected choices to the Poller object. It raises the following error: Direct assignment to the forward side of a many-to-many set is prohibited. Use poller_categories.set() instead. Models.py class Categories(models.Model): poller_category = models.CharField(max_length=30) poller_category_id = models.IntegerField(default=0) def __str__(self): return str(self.poller_category) class Pollers(models.Model): [..] # Poller Category poller_categories = models.ManyToManyField(Categories) def __str__(self): return str(self.poller_id) Forms.py class PollersForm(forms.Form): [..] # Poller Tags poller_categories = forms.ModelMultipleChoiceField(queryset=Categories.objects.all()) views.py def raise_poller(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required poller_nature = form.cleaned_data['poller_nature'] poller_text = form.cleaned_data['poller_text'] poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] poller_categories = form.cleaned_data['poller_categories'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_nature = poller_nature, poller_text = poller_text, poller_choice_one = poller_choice_one, poller_choice_two = poller_choice_two, poller_categories = poller_categories, # here seems to be my issue? created_by = created_by) p.save() # redirect to a new … -
Datetime field interfering with Django order_by in annotate query
I'm currently working with three models, Routes, Attendances and Containers. Each route has two attendances and each attendance has one container, so I'm annotating on the number of routes for each container. I managed to almost get the result I want but I also need the created_at field in my Routes model, however if I call it, the sorting does not work anymore. Models class Container(models.Model): license_plate = models.CharField(max_length=255) container_number = models.IntegerField(default=-1) container_type = models.BooleanField(default=True) # True para calientes, False para fríos created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.license_plate class Meta: db_table = "trucks_containers" class Attendance(models.Model): IN = 'in' OUT = 'out' CHECKIN_TYPES = [ (IN, 'in'), (OUT, 'out') ] type = models.CharField(max_length=10, choices=CHECKIN_TYPES) closed = models.BooleanField(default=False) damaged = models.BooleanField(default=False) datetime = models.DateTimeField() is_crashed_container = models.BooleanField(default=False) is_crashed_truck = models.BooleanField(default=False) has_solar_panel = models.BooleanField(default=False) truck = models.ForeignKey(Truck, on_delete=models.CASCADE, null=True) container = models.ForeignKey(Container, on_delete=models.CASCADE) gate = models.ForeignKey(Gate, on_delete=models.CASCADE) snapshot = models.ForeignKey( general_models.Snapshot, on_delete=models.SET_NULL, null=True ) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "trucks_attendances" class Route(models.Model): start_attendance = models.ForeignKey( Attendance, related_name='start_attendance', on_delete=models.CASCADE ) end_attendance = models.ForeignKey( Attendance, related_name='end_attendance', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "trucks_routes" Almost correct result Query used: containers_routes = truck_models.Route.objects\ .values('end_attendance__container__id', 'end_attendance__container__container_number', 'end_attendance__container__license_plate')\ .annotate(completed_routes=Count('end_attendance__container__id'))\ .order_by('-completed_routes') Result: <QuerySet [{'end_attendance__container__id': … -
How to pass in the user in the request for Auth0? (React Frontend and Django Backend)
I am creating a web application and trying to use Auth0 for my user authentication. I want to secure some endpoints where the user must be logged in to be able to successfully access an endpoint. I followed this tutorial on setting up Django with Auth0 and it went perfectly. (https://auth0.com/docs/quickstart/webapp/django/01-login) However though I want to be able to signin from the frontend (React) to be able to access the secured endpoints on my Django backend. This is what I have for my endpoint that I'm testing. views.py from django.http import JsonResponse def test(request): user = request.user if user.is_authenticated: return JsonResponse({ 'outcome': 'success'}) else: return JsonResponse({ 'outcome': 'failure'}) This endpoint is called path('test/', views.test), in my urls.py. When I login using the templates and then try to access the endpoint it works perfectly. templates/index.html <div class="login-box auth0-box before"> <img src="https://i.cloudup.com/StzWWrY34s.png" /> <h3>Auth0 Example</h3> <p>Zero friction identity infrastructure, built for developers</p> <a class="btn btn-primary btn-lg btn-login btn-block" href="/login/auth0">Log In</a> </div> However though the issue is when I try logging through the my React frontend. I can't seem to get the JsonResponse to be 'success' and keep on getting 'failure'. fetch('test/') .then(response => response.json()) .then(data => console.log(data)); I can see that from … -
Filter output items of reverse relations in Django
I have these models: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=150) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books") published_at = models.DateField() And this is my query: Author.objects.filter(books__published_at__ragne=[date_from, date_to]).annotate(books_count=Count('books')) The query's output will be sent to below serializer(inherit django rest framework serializer): class AuthorSerializer(serializers.ModelSerializer): books_count= serializers.IntegerField(read_only=True) books = serializers.StringRelatedField(many=True) class Meta: model = Author fields = ['id', 'name', 'books_count', 'books'] The AuthorSerializer output will be all authors who have at least one book published in specified range, with the number of books published by each author, and also the string representation of all books of each author. The books__published_at__ragne filter affect output authors and books count, but it won't affect books of authors. I mean for each author, all books are returned, not only books which are published in specified range. How can i also filter books with that specified parameters? -
How to also ignore warnings in pytest about removal in Django41?
https://docs.pytest.org/en/6.2.x/warnings.html#deprecationwarning-and-pendingdeprecationwarning teaches me to use this in my pytest.ini filterwarnings = ignore:.*U.*mode is deprecated:DeprecationWarning but i still get warnings that are like this: ../usr/local/lib/python3.8/dist-packages/django/apps/registry.py:91 /usr/local/lib/python3.8/dist-packages/django/apps/registry.py:91: RemovedInDjango41Warning: 'pattern_library' defines default_app_config = 'pattern_library.apps.PatternLibraryAppConfig'. Django now detects this configuration automatically. You can remove default_app_config. app_config = AppConfig.create(entry) I would like to suppress this as well, as this is also a third party library of which I have no control over even though i have laready submitted a PR to update it. What should i add to my pytest.ini? -
add serializer methid field to a generics.ListAPIView
class PermitListSerializer(serializers.ModelSerializer): def __init__(self,page=None, *args, **kwargs): self.page = page super().__init__(*args, **kwargs) page_number = serializers.SerializerMethodField() userfullname = serializers.SerializerMethodField() show_subsystem = serializers.SerializerMethodField() def get_show_subsystem(self,obj): return obj.subsystem.name def get_userfullname(self, obj): return obj.issuer.get_full_name() if obj.issuer.get_full_name() else 'Unknown' def get_page_number(self, obj): return self.page class Meta: model = Permit fields = '__all__' my view: class c_receive_tm(generics.ListAPIView): serializer_class = PermitListSerializer filter_backends=(filters.SearchFilter,) search_fields=('name', 'description') def get_queryset(self): return Permit.objects.all().order_by('-id') by I get an error: Object of type Permit is not JSON serializable if i remove all SerializerMethodField its works I need this additional fiels -
disk-cache is not happening for one-endpoint in browser + django
kindly advise why there is no client level caching is not happen when i use @method_decorator , even i am seeing cache_control attribute set as max_age in response header. and after i use method_decorator, I am not seeing as Disk-cache in the browser, due to this, everytime request is going to server, which we dont need to go request to server for particular time class WithdrawViewSet(AbstractViewSet): group_permissions = { 'GET': ( roles.xyz ) } class AbstractViewSet(ModelViewSet): http_method_names = ['get', 'options'] permission_classes = [IsAuthorizedUser] def _list(self, request, *args, **kwargs): try: response = wrapper.get(‘test_url’, timeout=50) except : raise exception return Response(data= response) @method_decorator(cache_page(“60 * 60 * 2”)) def list(self, request, *args, **kwargs): return self._list(request, *args, **kwargs) urls.py : from django.urls import re_path from test import WithdrawViewSet urlpatterns = [ re_path(r'^withdraw/$’, WithdrawViewSet.as_view(), name=‘withdraw’), ] Browser inspect : and I am not seeing as Disk-cache in the browser, due to this we everytime request is going to server, we dont need like that -
Redirecting with Additional Arguments after Script Function
I have a Django site running with Jinja2 templates where I need to create a form that takes an username variable and returns a User ID on the same page. For this, I have both a standard viewbase as well as a function in my views.py. The function takes the POST request from the HTML form on the 'List' page, transforms it into an ID using a python script stored in the app, and then redirects back to the main page which has an 'if' statement to display the text. I cannot simply render 'list.html', as additional context in the original view creates a list. The issue is, no matter what I try I cannot receive the data back on the main page. My latest error is (ignore my test values please): NoReverseMatch("Reverse for 'list' with keyword arguments '{'username': 'asdfa', 'ID': 'hi'}' not found. 1 pattern(s) tried: ['/list/$']",) My end goal is to make the '{% if 'username'} section into a modal, but until I can confirm the data is being handled, I assume I shouldn't even think about that. Here is the code: views.py class ListView(TelegramViewBase): template_name = "telegram/list.html" @method_decorator(login_required) @method_decorator(permission_required("sig.telegram.view", raise_exception=True)) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, … -
How to add mobile number validater in Django model?
def validate_mobile_number(value): if not str(value).isdigit(): raise ValidationError("Please Enter Valid Mobile Number") class ModelA(AbstractUser): mobile = models.CharField(_("Mobile"), unique=True, max_length=10,validators[validate_mobile_number,validators.MinLengthValidator(limit_value=10)]) -
(DJANGO) How to save session for user shopping cart in to restore session in next login?
guys, I create a shopping cart in Django with using session, but after logout, it removes my cart, and also I cannot see my cart on another computer . so please help me -
Why does Django not render a basic form?
I have a simple form that doesn't render on the frontend: Forms.py class PollsForm(forms.Form): poller_version = forms.ChoiceField(choices=("Question", "Information")) poller_text = forms.CharField(strip=True) poller_choice_one = forms.CharField(label='Choice one', max_length=20) poller_choice_two = forms.CharField(label='Choice two', max_length=20) Views.py from django.shortcuts import render, HttpResponseRedirect from .forms import PollsForm def raise_poll(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PollsForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = PollsForm(), return render(request, 'pollinator/raise_poll.html', {'form': form}) raise_poll.html <form action="/post-poll/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py path('raisepoll/', raise_poll, name='raise_poll'), When I use {{ form.as_p }}it renders just nothing, but if I use `{{ form }} it renders the form but as string not as html elements: What do I miss? -
django.db.utils.ProgrammingError: relation "Industry" does not exist
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "Industry" does not exist LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR... -
Django Unable to load static files - internal-nginx-static comes in URL
Hope you are all having a very good Friday! I am running a django project on nginx, and my project is each time going into this url - https://sitename.com/internal-nginx-static-location_uat/project_name/static/images/success.svg I didn't configure this internal-nginx-static, and If I load the same project on another website, it works fine, is it something I can handle in code, or I have make changes in server conf. Here is my URL.py Files from django.conf import settings from django.contrib import admin from django.conf.urls.static import static from django.urls import path, include urlpatterns = [ path('', include('portal.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and settings file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(DATA_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Django migrate command doesn't create any table on Heroku
It shows that tables are successfully created when I do heroku run -a "app-name" python manage.py migrate Running python manage.py migrate on ⬢ app_name... up, run.0000 (Free) System check identified some issues: ... Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK ... But when I create a superuser, it tells me that there is no table Any suggestions? I’m sticking in it for 3 days now so I will be grateful for any help. P.S. I use heroku postgresql hobby-dev. P.P.S. File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auth_user My production configuration from .base import * import dj_database_url import environ DEBUG = False try: from .local import * except ImportError: pass environ.Env.read_env() env = environ.Env() DATABASES = { 'default': env.db() } -
Django finds template but doesn't render it and throws out an empty HTML page
I have a view in views.py: def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print(uploaded_file_url) context = { 'uploaded_file_url': uploaded_file_url } return render(request, 'simple_upload.html', context) return render(request, 'simple_upload.html') Then, a url in urls.py: urlpatterns = [ path('', views.project_index, name='project_index'), path('<int:pk>/', views.project_detail, name='project_detail'), path('upload/', views.simple_upload, name='upload') ] And when I hit the route /projects/upload, instead of a form I get an empty page. However, the simple_upload.html route has this structure: {% extends "base.html" %} <h1>H</h1> {% load static %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} You can see, I'm getting a blank page. No errors are occurred. -
Why media files are not rendered and are not shown when I run the application?
I am working with Django 3.2.6 and I am just a beginner. I have one project(AwsomeWeb2) which has 4 applications(Users, Posts, PasswordReset, Contact). I have one class in Users that saves the information of user's profiles: class MyUser(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) mobile_number = models.CharField(max_length=20, unique=True, null=True, blank=True) birthday = models.DateField( null=True, blank=True) profile_photo = models.ImageField(default="images.png", null=True, blank=True,upload_to='profiles') date_joined = models.DateTimeField(auto_now_add=True, null=True, blank=True) country = models.CharField(max_length=15, null=True, blank=True) city = models.CharField(max_length=15, null=True, blank=True) region = models.CharField(max_length=15, null=True, blank=True) address = models.TextField(null=True, blank=True) postal_code = models.CharField(max_length=10, unique=True) is_active = models.BooleanField(default=True) user_email = models.EmailField(null=True, blank=True) uni_name = models.ForeignKey('University' , on_delete=CASCADE , default='university name') major_name = models.ForeignKey('Major' , on_delete=CASCADE , default='major name') def __str__(self): return f"{self.first_name} {self.last_name}" User.profile = property(lambda u : MyUser.objects.get_or_create(user = u)[0]) And I have one field as profile_photo that is for saving users' profile pictures. I have a form in forms.py which is related to this model: class MyUserProfile(forms.ModelForm): class Meta: model= MyUser fields = ( 'first_name', 'last_name', 'mobile_number', 'birthday', 'profile_photo', 'country', 'city', 'region', 'address', 'postal_code', 'user_email' ) I also add a few lines in setting.py for media files: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') And when … -
How to override the model's update method in django?
I have a class model which has some fields and I have put up unique constraints on some of those fields. Now my query is I am updating some of my classes status to cancelled, that led me to the error. duplicate key value violates unique constraint "unique-class" DETAIL: Key (class_id, calendar_date, is_cancelled, cancellation_count)=(6-9Hip523, 2021-10-27, t, 0) I want to skip this error on model level. How to do that? My custom update method is not getting called, please let me know what I am doing wrong here. my model class Meta: constraints = [ models.UniqueConstraint(fields=['class_id', 'calendar_date', 'is_cancelled', 'cancellation_count'], name='unique-class') ] def update(self, *args, **kwargs): if self.is_cancelled: try: super().update(*args, **kwargs) except: print("Classes are already cancelled.") -
how to add custom permissions and role based in django rest framework
models.py =============== from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): username = models.CharField(max_length=10, unique=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="admin_account") def __str__(self): return self.user.username class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="teacher_account") def str(self): return self.user.username class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="student_account") def str(self): return self.user.username -
How to create extra option in django admin
want to create similar in Django admin for movies website extra option how i can do this ? what is best way? -
Access a view variable within a template
I have a context variable which is dynamic because of a loop I perform: context['categories'] = choices.CATEGORIES for category_type, category in context['categories']: context[category_type] = Article.objects.filter(category=category_type).count() But in the template it just prints the category type instead of the number which is on the variable but I also need type for a link: {% for type, category in categories %} <a href="{% url 'app:category' type %}">{{category}}</a> {{type}} {% endfor %} How can I access this dynamic variable in a for loop? -
django TypeErrorin admin panel bug with database (expected a number but got)
hello i'm trying to make model manytomany field. my main goal is to write a model where i can assing my users human skills. for instance, i have skills[Good judgment, Patience with others, Strong communication] and i want to assign this 3 skill to user when i am doing that i am getting error like this. Field 'id' expected a number but got <Id: luka>. luka is one of my user which i created from admin panel. this is my models file class Skills(models.Model): skill_name = models.CharField(max_length=30) def __str__(self): return self.skill_name class Id(models.Model): first_name = models.CharField(max_length=100, null=True) human_skills = models.ManyToManyField(Skills, related_name="SkillsNames") def __str__(self): return self.first_name and when i am saving this is error: -
When I run my Django app using python manage.py runserver on a different pc I get a sqlite3.OperationalError: unable to open database file
Error message 'cudart64_110.dll'; dlerror: cudart64_110.dll not found 2021-09-03 13:07:38.728939: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 2021-09-03 13:07:44.525563: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found 2021-09-03 13:07:44.525916: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303) 2021-09-03 13:07:44.533594: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: LAPTOP-673JJ4RS 2021-09-03 13:07:44.533921: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: LAPTOP-673JJ4RS 2021-09-03 13:07:44.535340: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 209, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\threading.py", line … -
Django - how to get id of get_or_create model instance?
assuming the following code: new_file, created = Files.objects.get_or_create( descriptor=somevalue, file_path=somevalue, file_name=somevalue, s3_backend=somevalue ) if created: new_file_id = ??? where << new_file, created >> is a tuple formed out of the model instance and a bool. At my if statement I only want to retrieve the id of new_file as string not as model instance. How can I do that? Thanks in advance -
Django/Python used two model in one html
I created movies website, using Django , I have two model first one is class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=10) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) and second is class Series(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=10) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) in view.py def home(request): user = request.user # Movies_obj = models.Movie.objects.all().order_by('-id')[:10] Movies_obj = models.Movie.objects.filter(category__in=['A']).order_by('-id')[:10] Movies_main_slider = models.Movie.objects.filter(category__in=["M"]).order_by('-id')[:10] Movies_main_suggest = models.Movie.objects.filter(status__in=["Suggest"]).order_by('-id')[:10] serial_obj = Serial seriali = models.Serial.objects.all().order_by('-id')[:10] return render(request,'index.html',{'user':user,'movies':Movies_obj,"main_slider":Movies_main_slider, "favorite":Movies_main_suggest,"serils":seriali}) def details(request,post_slug): movies_obj = Movies get_movie = Movies.objects.filter(slug = post_slug) return render(request,'Movie/movie_details.html',{"movies":get_movie}) also have two HTML file , index.html and movie_details.html , but when i add new Series not working in movies_details.html in movies_details i am using {% for i in movies %} {{ i.descritpion }} {% endfor %} and when i add series not working ,only movie models working , what is best way to used two model in one html ? created new html for series model ?