Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
at=error code=H10 desc="App crashed" heroku retuning this error
at=error code=H10 desc="App crashed" heroku retuning this error Django Changed Procfile with all previous stack solution but still its same. web: gunicorn projectname.wsgi --log-file - web: gunicorn django_project.wsgi:application --log-file - --log-level debug python manage.py collectstatic --noinput manage.py migrate both format i used -
Exclude and filter graphene django query set
Hi i'm trying to add a filter and exclude to my query set but don't know how. I can filter and exclude separately but cant do it simultaneously. This is my resolver def resolve_articles(self, info, limit=None, offset=None, slug=None, search=None, exclude=None, braking=None, non_braking=None): if search: filter = ( Q(id__icontains=search) | Q(title__icontains=search) | Q(categories__name__icontains=search) ) return BlogPage.objects.filter(filter).order_by('-first_published_at')[offset:limit] How can i do this def resolve_articles(self, info, limit=None, offset=None, slug=None, search=None, exclude=None, braking=None, non_braking=None): if search and exclude: filter = ( Q(id__icontains=search) and Q(categories__name__icontains=exclude) ) return BlogPage.objects.filter(filter).exclude(filter).order_by('-first_published_at')[offset:limit] Thank you -
How to Send Emails to Subscribed Users in Django or How to send News Letters in Django
I am trying how can I send mass mails to the Subscribed Users. I have the E-mails of the User and want them to send News Letters or anything else. But, I am unable to do these. So Help me by the Explanation and providing CODE. Thanks in Advance !!! -
Retrieve data from external API and display in django admin
Rather than querying a local database I would like to use an external API to retrieve the data to display in the django admin. For simplicities sake I have a model, and plan to retrieve a list of names from the API: class Person(models.Model): first_name = models.CharField() last_name = models.CharField() class Meta: managed = False As it is not managed it therefore does not create the person table. What is the order of functions I must override in ModelAdmin to Perform the API call instead of the database lookup Output the data to a default table in the admin (with first name and last name) Disable functions such as to add (as this will just be a lookup table) Use the django admin search to query the external api - ie. perform a new request and display the new data. -
Problems with uploading large files in django
I have project with courses. Course contains videos that usually bigger that 100mb. But when i am trying to upload this file, it instantly redirects without any loading, and when i am opening the admin i can see the name of this video, but when i am trying to open, i am redirecting to the page with player that doesn't showing video. How i can upload large files? models.py class SectionVideos(models.Model): title = models.CharField(max_length=50,null=True) video = models.FileField(upload_to='courses/course_videos',max_length=100) section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True) preview_image = models.ImageField(upload_to='courses/course_videos_preview_images',null=True) short_description = models.CharField(max_length=50,null=True) -
Searching by category in Django and not by product
I have created a search bar which searches based on product name. I would now like to change this to search by category but I am finding it difficult. Here is my URLs file: ''' from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.marketplaceHome, name='marketplace-home'), url(r'^search/$', views.search, name='search'), url(r'^contact/$', views.Contact, name='contact'), url(r'^(?P<category_slug>[-\w]+)/(?P<product_slug>[-\w]+)/$', views.productPage, name='product_detail'), url(r'^(?P<category_slug>[-\w]+)/$', views.marketplaceHome, name='products_by_category'), url('^cart$', views.cart_detail, name='cart_detail'), url(r'^cart/add/(?P<product_id>[-\w]+)/$', views.add_cart, name='add_cart'), url(r'^cart/remove/(?P<product_id>[-\w]+)/$', views.cart_remove, name='cart_remove'), url(r'^cart/remove_product/(?P<product_id>[-\w]+)/$', views.cart_remove_product, name='cart_remove_product'), ] ''' views.py ''' from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404, redirect from .models import Category, Product, Cart, CartItem from django.core.exceptions import ObjectDoesNotExist from . import forms # Create your views here. def marketplaceHome(request, category_slug=None): category_page = None products = None if category_slug !=None: category_page = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category_page, available=True) else: products = Product.objects.all().filter(available=True) return render(request, 'marketplacehome.html', {'category': category_page, 'products': products}) def productPage(request, category_slug, product_slug): try: product = Product.objects.get(category__slug=category_slug, slug=product_slug) except Exception as e: raise e return render(request, 'product.html', {'product': product}) def search(request): products = Product.objects.filter(name__contains=request.GET['name']) return render(request, 'marketplacehome.html', { 'products': products}) ''' template.html ''' <ul class="navbar-nav ml-auto"> <form class="form-inline" action="{% url 'search' %}", method="GET"> <div class="input-group"> <input type="text" name="name" class="form-control" placeholder="Location" aria-label="Search" name="query"> <div class="input-group-append"> <button type="button" class="btn btn-warning" name="button"><i class="fas fa-search"></i></button> … -
How can I dynamically find out a subclass' package name in Python?
For context, I'm writing a library that uses Django's ORM. I don't want users of my library to have to define the app_label every time they subclass my custom Model superclass, instead I want to enforce a standard structure for projects created with it that makes sure the package name of every class that subclasses my Model superclass will equal the app_label. Here's the code I currently have: class Model(django.db.models.Model): class Meta: abstract = True def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # package_name = ??? cls._meta.app_label = package_name The ??? part is what I can't seem to figure out. Any ideas? -
How to deploy create-react-app and Django to the same linux server
I want to deploy create-react-app as frontend and Django with Graphene as backend to a Linux server. Gunicorn config in /etc/systemd/system/gunicorn.service is as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=name Group=www-data WorkingDirectory=/home/name/mijn-bureau/backend/app ExecStart=/home/name/mijn-bureau/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/name/backend.sock app.wsgi:application [Install] WantedBy=multi-user.target Nginx config in /etc/nginx/sites-available/ is as follows: server { listen 80; root /var/www/frontend/build; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location / { } location /api { include proxy_params; proxy_pass http://unix:/home/name/backend.sock; } } Thus, react frontend is served and I see the login screen. But when I want to login it doesn't work. The Graphql client config is as follows: const client = new ApolloClient({ uri: 'http://example.com/api/graphql/', fetchOptions: { credentials: 'include' }, request: (operation) => { const token = localStorage.getItem(AUTH_TOKEN_KEY) || ""; operation.setContext({ headers: { Authorization: `JWT ${token}` } }) }, clientState: { defaults: { isLoggedIn: !!localStorage.getItem(AUTH_TOKEN_KEY) } } }); What do I do wrong? -
Cross-Origin Request Blocked Django-project
I've built a REST API and I'm following along with this tutorial: https://www.youtube.com/watch?v=hISSGMafzvU&t=14s I've completed all up until 13minutes. addition of a JS script into the html template. When I run and check the console I get: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)." I have no idea what part of my projects the CORS header goes into? script type="text/javascript"> buildList() function buildList(){ var wrapper = document.getElementById('list-wrapper') var url = 'http://127.0.0.1:8000/api/task-list/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) }) } </script> -
Django I want to limit user voting to once per 24 hours but I limited it per article and not per user
I would like to kindly ask you for your help. I wanted to create simply voting system for questions. And I succeded, then I wanted to limit users to voting only once per 24 hours and I failed miserable. I know what I want to achieve but I don't know how to code it. Right now with my mistake I limited voting on QUESTION once per 24 hours. Instead of that I wanted to limit one USER to vote ONCE per 24 hour on EACH question. So I made pretty stupid mistake. Here is my code with my mistake: models.py: class Question(models.Model): question = models.CharField(max_length=300) answered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) votesscore = models.IntegerField(default='0') votescoresubmitted = models.DateTimeField(null=True, blank=True) amountofvotes = models.IntegerField(default='0') def __str__(self): return self.question views.py: @login_required() def questionvoteup(request, question_pk): question = get_object_or_404(Question, pk=question_pk, user=request.user) if request.is_ajax() and request.method == "POST": if question.votescoresubmitted is None or timezone.now() > question.votescoresubmitted + timedelta(minutes=1440): question.votesscore += 1 question.amountofvotes += 1 question.votescoresubmitted = timezone.now() question.save() data = { "msg": 'Thank you for your vote!' } return JsonResponse(data) else: raise forms.ValidationError("You can vote only one time every 24 hours.") else: return HttpResponse(400, 'Invalid form') Right now I … -
Django extra parameter of modelformset_factory
I noticed a behaviour I am not sure I understand with the parameter extra of modelformset_factory: When I set extra to an integer, django pulls out object instances that I recently deleted. How could this be the case ? Thank you. -
Why can't I update my heroku website via git push?
I am working on a website (django) that I uploaded online with heroku. Everything worked fine until I had to make a change in my views.py. Now when I do: - git add . - git commit -m "smtg" - git push heroku master It tells me that nothing change but I made some changes, it seems like it cannot see those. When I try git init it tells me " Reinitialized existing Git repository in C:/Users/Loic/Documents/my_site2/.git/ " Could you please help me it is a school project. Thank you -
Axios put request with image fields
Using django backend and React js as frontend. Facing error while doing put request with image fields. I create a picture record while creating a person record. While creating a picture record, I give a person reference in the serializer, so picture record is created with the primary key which refers to 'person' model. Now, I would like to update picture form with image fields and do a put request. return axios.put(`http://127.0.0.1:8000/picture/${this.props.match.params.ID}/`, { t_drawing: t_drawing, t_picture: t_picture, m_name: m_name, id: id, }, { headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW;application/json', } }) id is onetoone field to another model. In the form, <Input type='number' name='id' value={this.props.match.params.ID} /> I get the value of ID from another table using props. The error that I get is: TypeError: Converting circular structure to JSON --> starting at object with constructor 'HTMLInputElement' | property '__reactInternalInstance$cdidtli7jvl' -> object with constructor 'FiberNode' Please suggest, I am a beginner. -
'404 Not Found. The requested url / was not found on this server' Django deployment with apache2
I'm developing a django website and am currently working on deploying. I'm following this tutorial. And im in the last stage of the tutorial (1:08:00 in the video). After he finished configuration th django-project.conf file he saves and everything is working, but me on the other hand, i get an: Not Found The requested URL / was not found on this server. Apache/2.4.34 (Ubuntu) Server at **** Port 80 This is my projects .conf file: <VirtualHost *:80> ServerName _ Redirect 404 / Alias /static /home/user/project/static <Directory /home/user/project/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIDaemonProcess project_app python-path=/home/user/project python-home=/home/user/project/venv WSGIProcessGroup project_app </VirtualHost> This is my urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage), path('rh/', views.rh, name="rh"), path('gvt/', views.gvt, name="gvt"), path('fth/', views.fth, name="fth"), path('pages/', include('pages.urls')), ] This is my wsgi.py from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excelsite.settings') application = get_wsgi_application() sys.path.append('/home/alexholst/excelsite') This is the error.log (Couldnt copy, so i have this screenshot instead) here -
Override create for nested serializer and fetch model objects from ordered dict
I want to make a post to NewVariation model using NewVariationSerializer serializer. I am doing a Bulk Create With Django REST Framework as shown here. My issue is, I need id in ContWindowSerializer to be read_only but I am not able to access it in the parent serializer's create method using - window_id = data['Cont_window']['id'] class ContWindowSerializer(serializers.ModelSerializer): """Serializes the Cont Window model.""" id = HashidSerializerCharField( source_field='Conts.ContWindow.id', read_only=True, ) Cont = ContSerializer() period_dates = DateRangeField() start_time = serializers.TimeField(format='%H:%M') end_time = serializers.TimeField(format='%H:%M') class Meta: model = models.ContWindow fields = ( 'id', 'Cont', 'period_dates', 'start_time', 'end_time', ) class NewVariationSerializer(serializers.ModelSerializer): """Serializes the New Variation model.""" id = HashidSerializerCharField( source_field='Conts.NewVariation.id', read_only=True, ) Cont_window = ContWindowSerializer() reason = serializers.CharField(source='get_reason_display') start_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S') end_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S') class Meta: model = models.NewVariation fields = ( 'id', 'capacity', 'reason', 'Cont_window', 'start_datetime', 'end_datetime', ) def create(self, data): """Handle New variation creation.""" window_id = data['Cont_window']['id'] Cont_window = models.ContWindow.objects.get(id=window_id) data['Cont_window'] = Cont_window return super().create(data) Please let me know how to fix this or if there is a better way of doing it. It would be great if I could fetch the ContWindowSerializer object into the create method without the get query. -
Can't load static image in django when using a loop
I cant get an image to load in django when i use a for loop, the image will load if i specify the path for each file. Works: when I try to use a loop it won't load the images. view.py: operators = [] directory = os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR) ,'static'),'images'),'operators') for file in os.listdir(directory): if file.endswith(".png") or file.endswith(".jpg"): operators.append(file) then i try to return image using context. html file: {% if operators %} There are {{ operators|length }} records: {% for operator in operators %} <div class="media"> <img src="{{operator}}" class="align-self-center mr-3" alt="..."> </div> {{operator}} {% endfor %} {% else %} There are no records in the system {% endif %} It would be amazing if someone had an idea on how to fix my code. settings.py: STATIC_URL = '/static/' # Pointing django to the static file location. STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) -
Is there a way to add an aggregated field to an annotated Queryset
I have a queryset with two objects in it like below: fake = queryset({'id':1, 'price': 10, 'relation_field_id':5}, {'id':1, 'price': 15, 'relation_field_id':5}) All relation_field_ids have number 5. I want to have a Queryset or Dic that aggregated with sum of the price field and just one of the relation_field_id in it like: queryset({'total_price': 25, 'relation_field_id':5 }) I would be glad anyone answer to this question. Thank you. -
Dockerized django app don't run in the browser
I'm getting a problem when I run my docker image what I built with the next Dockerfile: FROM ubuntu:18.04 RUN apt update RUN apt install -y python3 python3-pip RUN mkdir /opt/app COPY Ski4All/ /opt/app/ COPY requirements.txt /opt/app/ RUN pip3 install -r /opt/app/requirements.txt COPY docker-entrypoint.sh / EXPOSE 8000 ENTRYPOINT /usr/bin/python3 /opt/app/manage.py runserver 0.0.0.0:8000 With the commando docker run -p 8000:8000 -it --rm skiapi Everything run Ok and I receive the message about the server is running at 127.0.0.1:8000 but when I try to access via browser it says that the connection has been restarted and I can't access to the web. Any tip? Thanks -
How do I universally connect to Redis both in Docker and PyTest?
One of the Django views in code I test connects to Redis using a redis.Redis class. red = redis.Redis(host='redis-map', port=6379) Obviously, this method isn't good when testing because it uses the same DB as when opening it outside of testing. I found a library called pytest-redis and replaced all the redis.Redis constructors with calling a function I created: import sys, redis from pytest_redis import factories def create_redis(): if not 'pytest' in sys.modules: return redis.Redis(host='redis-map', port=6379) else: return factories.redisdb('redis_proc')() However, when I run the test, it returns this error: web_1 | Failed: Fixture "redisdb_factory" called directly. Fixtures are not meant to be called directly, web_1 | but are created automatically when test functions request them as parameters. web_1 | See https://docs.pytest.org/en/latest/fixture.html for more information about fixtures, and web_1 | https://docs.pytest.org/en/latest/deprecations.html#calling-fixtures-directly about how to update your code. I don't want to rewrite what is pretty much all of my code - lots of code in my WebSocket consumer in Django Channels also uses Redis. What should I do? -
How dynamically define and create custom "through" model with specific fields and structure for all custom manytomanyfield
I have a model with a lot of m2m fields: class Model1(models.Model): useful_data = models.TextField(null=True) class Model2(models.Model): useful_data = models.TextField(null=True) class Entity(models.Model): field1 = CustomManyToManyField('entities.Model1') field2 = CustomManyToManyField('entities.Model2') field3 = CustomManyToManyField('entities.Model2') ... I want dynamically created model "through" for all CustomManyToManyField with specific fields. So for every CustomManyToManyField I need to dynamically create new model with this structure. For example for field1 field this model will be created: class CustomThroughModel(models.Model): entity = models.ForeignKey('entities.Organization') model1 = models.ForeignKey('entities.Model1') data_source = models.CharField() updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) I don't want to copy paste similar models for every manytomanyfields -
How to convert this category_detail function-based view to a CBV (DetailView)
I have this function-based view doing what I need it to do - get the list of all Posts filed under s specific Category and reach that list by going to example.com/economics/ (where economics is the slug od that specific Category). There I would find the list of all my posts filed under Economics category and create links so I can click on them and go to a single post page. Currently, my FBV looks like this: def category_detail(request, category_detail_slug=None): categories = Category.objects.all() #Show only published posts posts = Post.objects.filter(status__exact='1') if category_detail_slug: category = get_object_or_404(Category, slug=category_detail_slug) posts = posts.filter(category=category) return render(request, 'blog/category/single.html', {'category_detail_slug': category_detail_slug, 'category': category, 'categories': categories, 'posts': posts}) I started creating my CBV like this: class CategoryDetailView(DetailView): model = Category template_name = 'blog/category/single.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context I know I need to pass some context, but somehow this keeps failing me. My URL for this is defined as such: path('<slug:category_detail_slug>/', views.CategoryDetailView.as_view(), name="single_category") -
How to embed Bokeh(2.x) server in Django(2.x) application/view
I have been beating the problem for a very long time and I can 't find a solution. In general, need to embed bokeh server in Django app. There are a lot of examples on flask in the documentation, but there are no examples on django from the beginning to the end. The situation is next: I have a form of dropdown selection with strings as option values. For example MSFT, TSLA, GOOG, OLOLO. I select the option from dropdown form, then redirecting to select/{str: option} page. In the views.py that processes the page I want to embed bokeh server. I have another file visualization.py with class that contains all settings for plots. #visualization.py import pandas as pd from bokeh.io import curdoc from bokeh.models import ColumnDataSource, Legend, NumeralTickFormatter from bokeh.plotting import figure doc = curdoc() class BokehPlot: def __init__(self, data): self.data = data self.df = self.collect_dataframe() self.tools = 'pan,crosshair,wheel_zoom,reset' self.plot_width = 1000 self.width = 0.5 self.xaxis_dt_format = '%d %b %Y' if self.df['datetime'][0].hour > 0: self.xaxis_dt_format = '%d %b %Y %H:%M' self.major_x_axis = {i: date.strftime(self.xaxis_dt_format) for i, date in enumerate(pd.to_datetime(self.df["datetime"]))} self.inc_color = '#15aaba' self.dec_color = '#7F7F7F' def collect_dataframe(self): if self.data is None: raise Exception df = pd.DataFrame(self.data) df['datetime'] = pd.to_datetime(df.begin, format='%Y-%m-%d … -
how to call scrapy spider from view.py of my django application?
My aim is to check wether a particular javascript is present in the lis of URLs that the user enters in the front end of my application. I want to take that url and pass it to my spider and want to return two list. One which contains list of urls in which the javascript is present and the other list which doesn’t contain javascript. I want to display these lists back onto the html of the my application. When i run my spider from the terminal using command i get the desired output but want the front end of it. My django application view.py file from concurrent.futures import process from django.shortcuts import render from scrape.scrape.spiders import ScrapeSpider from scrapy.crawler import CrawlerProcess # Create your views here. def base(request): return render(request, "base.html") def home(request): search = request.POST.get("search") process.crawl(ScrapeSpider) data = { "search": search } return render(request, "scraping/home.html", data) My spider file looks like this. import scrapy class ScrapeSpider(scrapy.Spider): name = "scrape" allowed_domains = ["smolnarod.ru"] start_urls = [ "https://fribbla.com/en/20-dog-breeds-you-might-want-to-reconsider-getting/", ] def parse(self, response): data = response.xpath("//script[contains(., 'xyz')]").extract_first(default="not-found") if data == "not-found": print("Not Exists") else: print("Exists") The directory in which my spider is present scrape/scrape/spider/scrape.py While running the application i am facing … -
How to loop a function in python using a class?
I'm currently working on minesweeper using python and I have a function that goes through the buttons surrounding the clicked button and shows them if the clicked button's value is 0. My problem is, what if there is a 0 in the surrounding buttons. How do I apply the function then? class Gumb: def __init__(self, ID, broj): self.id = ID self.rednibroj = int(self.id[1])*10 +int(self.id[3]) self.r = self.rednibroj//10 self.s = self.rednibroj % 10 self.b = broj return def __repr__(self): return f'(ID:{self.id} \n Vrijednost: {self.b})' def postavljanje(): bombe=sample(range(0, 81), 10) bombe.sort() r={} for i in range(9): for j in range(9): r[f'r{i}s{j}']=0 for t in bombe: r[f'r{t//9}s{t%9}']='bomba' for i in range(9): for j in range(9): if r[f'r{i}s{j}'] != 'bomba': l=[f'r{i}s{j+1}', f'r{i}s{j-1}', f'r{i+1}s{j-1}', f'r{i+1}s{j}', f'r{i+1}s{j+1}', f'r{i-1}s{j-1}', f'r{i-1}s{j}', f'r{i-1}s{j+1}'] for t in l: if t in r and r[t]=='bomba': r[f'r{i}s{j}']+=1 print(r) return r r=postavljanje() def okolni(gumb,gumbi): i = gumb.r j = gumb.s l=[f'r{i}s{j+1}', f'r{i}s{j-1}', f'r{i+1}s{j-1}', f'r{i+1}s{j}', f'r{i+1}s{j+1}', f'r{i-1}s{j-1}', f'r{i-1}s{j}', f'r{i-1}s{j+1}'] for t in l: if t in r and r[t]!='bomba': g = Gumb(t, r[t]) gumbi.append(g) return gumbi def klik(request): ID = request.POST['ID'] vr = r[ID] print(ID) print(vr) print('bruh') gumbi = [] g = Gumb(ID, vr) gumbi.append(g) provjereni = [] provjereni.append(g) if vr == 0: okolni(g, … -
Using Muliple Model with Class based View Django 2.0
I'm building a warehouse management application in which I required to pass multiple models to class based views. For Example, I have a list of all the order with Product and fulfilment status. But I'm not able to pass multiple models form my class-based view to be displayed and use in my Template my Order Model class Order(models.Model): Order_id = models.IntegerField(primary_key=True) Product = models.ManyToManyField(Product) Shipping_addreess_1 = models.CharField(max_length=1000, blank=False) Shipping_addreess_2 = models.CharField(max_length = 1000,blank= True) Shipping_addreess_3 = models.CharField(max_length=1000, blank=True) Pin_Code = models.IntegerField(blank=False) City = models.CharField(max_length=256, blank=True) State = models.CharField(max_length=256, blank=False) Order_date = models.DateField Order_status = models.CharField(choices = order_status,max_length=2) Payment_method = models.CharField(choices = Payment_type,max_length=3) my Product model class Product(models.Model): SKU = models.CharField(max_length=365, unique=Tr) product_title = models.CharField(max_length=1000, blank = False) FSN = models.CharField(max_length=365,blank=True) Listing_ID = models.CharField(max_length=100, blank=True) ASIN = models.CharField(max_length=1000, blank=True) Price = models.IntegerField(blank=False) Product_category = models.CharField(max_length=256) #poster,t-shirt,notebook def __str__(self): return self.product_title I try passing through get_context_data method. As mention in some answer here. Views.py class OrderListView(ListView): def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['order'] = Order.objects.all() context['Product'] = Product.objects.all() return context But I got the error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/orders/ Django Version: 2.2 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'orders'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', …