Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is their any other method for defining on django
I am facing a problem in creating a django web application ![whereasindex is already defined in views.py and from which we are importing to urls.py ]2 -
legacy mysql data to django model using inspectDB
I have legacy database in mysql. I would like to use this in my django project. I used 'inspectDB' to generate django Model. However, this model does not have foreign key relationship. for example, I expect, person = models.ForeignKey('Person', on_delete=models.CASCADE) but it shows, person = models.IntegerField(db_column='Person') # Field name made lowercase. how can I make it correctly? Thank you in advance -
Django: form not displaying in browser
The form doesn't display in the browser. The navbar and submit button show up but no form in between. The problem must be straightforward but I haven't been able to find the issue. Thank you for your help. views.py def ProductCreateView(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('set_app/product_list.html')) else: product_form = ProductForm() return render(request, 'set_app/product_form.html', {'product_form':product_form}) forms.py class ProductForm(forms.Form): class Meta(): model = models.Product fields = ('code', 'barcode', 'name', 'description', 'brand', 'status') product_form.html {% extends "set_app/basic_app_base.html" %} {% block body_block %} <h1> {% if not form.instance.pk %} Create Product {% else %} Update Product {% endif %} </h1> <form method="post"> {% csrf_token %} {{ product_form.as_p }} <input type="submit" class="btn btn-primary" value="Submit"> </form> {% endblock %} -
raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'image'
I have spent a LOT of time trying to resolve this- Read Django docs, consulted forms but not got anything satisfactory. So please be patient here with me. I am trying to do an upload of an Image file here from my html template The file upload happens properly an d I am able to see the uploaded image file in the HTML. In my views.py, views.py from django.shortcuts import render import requests import sys from subprocess import run,PIPE from django.core.files.storage import FileSystemStorage def button(request): return render(request,'home.html') def output(request): data=requests.get("https://www.google.com/") print(data.text) data=data.text return render(request,'home.html',{'data':data}) def external(request): inp= request.POST.get('param') image=request.FILES['image'] print("image is ",image) fs=FileSystemStorage() filename=fs.save(image.name,image) fileurl=fs.open(filename) templateurl=fs.url(filename) print("file raw url",filename) print("file full url", fileurl) print("template url",templateurl) out= run([sys.executable,'D:/corona/Image Edit Html Button Run Python Script/Image Edit Html Button Run Python Script/test.py',inp],shell=False,stdout=PIPE) image= run([sys.executable,'D:/corona/Image Edit Html Button Run Python Script/Image Edit Html Button Run Python Script/image.py',str(fileurl),str(filename)],shell=False,stdout=PIPE) print(out) print(image.stdout) return render(request,'home.html',{'data':out.stdout,'raw_url':templateurl,'edit_url':image.stdout}) In my home.html home.html <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <button onclick="location.href='{% url 'script' %}'">Execute Script</button> <hr> {% if data %} {{data | safe}} {% endif %} <br><br> {% if raw_url or edit_url %} <span> RAW IMAGE: <img src={{raw_url}} height=500 width=500> PROCESSED IMAGE: <img src={{edit_url}} height=500 width=500> </span> … -
Error: Requested setting INSTALLED_APPS, but settings are not configured..?
I have just started django and I have stuck in an error that I can't find the solution. As my first project in django is: To Do list web app. from django.db import models # Create your models here. class ToDo(models.Model): added_date = models.DateTimeField() text = models.CharField(max_length=200) When I run this code it show me these error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django user change Password
So we're working on a django project where users are supposed to change their passwords. I enabled a view for edit profile fields like name, last name or email but password has to have its own form. First of it all, id like to know how can i put this two forms in the same template but in two differents distributions and how to put the change password in work. and if doing this, the "No password set" advice will dissapear. template <div class="tab-pane container p-0 active" id="home1"> <form method="POST" action="#" id="datosForm"> {% csrf_token %} <p>Por favor, no dejes ningún campo en blanco. {{ form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" name="datosForm"> Save </button> </p> </form> </div> <div class="tab-pane container p-0 fade" id="home2"> <form method="POST" action="#" id="contraForm"> {% csrf_token %} <p>Por favor, llena los siguientes campos para cambiar tu contraseña. {{form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" name="contraForm" > Save </button> </p> </form> </div> views.py def profileedit_view(request): form= PerfilEditadoForm(request.POST or None) if request.method== 'POST'and 'datosform' in request.POST: form.instance = request.user if form.is_valid(): form.save() return redirect('profileedit') else: form= PerfilEditadoForm(instance=request.user) args= {'form': form} return render(request, 'profileedit.html', args) context = { 'form': form } return render(request, "profileedit.html", context) def change_password(request): if … -
Why is Django not publishing a valid form?
I am creating a website using Django. I'd like to give users the chance to comment on pictures they have posted. I have created a comment model and a comment form, and put the following code into the HTML document for the photo gallery: <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form However, the form is not displaying - there is nothing between 'Leave a comment' and the submit button on the page. I don't understand this as my form in forms.py appears to be configured correctly: class CommentForm(forms.ModelForm): body = forms.CharField(help_text="What is your comment?", widget=forms.TextInput(attrs={'size': '1000'}), required=True) class Meta: model = Comment fields = ('body',) def as_p(self): # Returns this form rendered as HTML <p>s. return self._html_output( normal_row='<p%(help_text)s<p></p>%(field)s</p>', error_row='%s', row_ender='</p>', help_text_html=' <span class="helptext">%s</span>', errors_on_separate_row=True)` So does my model in models.py: class Comment(models.Model): COMMENT_MAX_LENGTH = 1000 image = models.ForeignKey(Picture, on_delete=models.CASCADE, related_name="comments") user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) body = models.TextField(max_length=COMMENT_MAX_LENGTH) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.user) I'd really appreciate any suggestions anyone could please offer. Thanks Jeff -
Django model with User, Profile and company
I am trying to build an app but have a hard time to figure out my model. I have already setup the User authentication. Next: Each User needs to be member of a Company (company has address info etc) Each User should have a Profile Invoices should be presented based on Company membership so every member gets the same page of invoices. So the tables (models) are: Profile Invoice Company User (this already exists and is the default django User) What would be the appropiate model relationships between those models. I would really appreciate the written model relationships like ForeignKey and ManyToMany e.d. -
django-keycloak | Set username as Keycloak Username (instead of Keycloak ID)
I am integrating Keycloak with Djnago https://github.com/Peter-Slump/django-keycloak/issues Keycloak Server This is what my keycloak User Screen looks like BUT when I log within django, user.email is proper (whats present in keycloak) user.username is getting set as ID from keycloak. Is there a way to retain djnago username as keycloak username? https://github.com/Peter-Slump/django-keycloak/issues/39 -
Loop through queryset and a dictionary with similar keys in order
I have a django queryset containing information about network things. Primary key is IP. Then, I have a dictionary with IPs as keys containing some data. I would like to display all IPs from either of the two sources in order, together with some info. For example, given: <Queryset[{'ip':'10.2.2.2', 'type':'laptop', ...}, {'ip':'10.4.4.4', 'type':'camera', ...}, {'ip':'10.5.5.5', 'type':'iot', ...}, {'ip':'10.8.8.8', 'type':'switch', ...}]> and: {'10.1.1.1': 'foo', '10.6.6.6': 'bar', '10.9.9.9': 'baz'} I want the following output: 10.1.1.1 foo 10.2.2.2 type: laptop ... 10.4.4.4 type: camera ... 10.5.5.5 type: iot ... 10.6.6.6 bar 10.8.8.8 type: switch ... 10.9.9.9 baz I could do nested loops, but is there a neat pythonic way? -
Django's Wagtail images have faulty S3 URL
I'm trying to upload images to my Django site's S3 storage using Wagtail. The images upload properly, but Wagtail appends ?AWSAccessKeyId= followed by a bunch of gibberish to the image URL. This causes the image to fail to load in both Wagtail's admin as well as the actual site. If I remove the appended text then the URL works properly. The problem is, I don't know how to stop Wagtail from appending the text in the first place. -
Error during template rendering - Required parameter name not set
I am a new developer that is stuck on this problem. The issue seems to be with the bootstrap code that I copied from their site, which is confusing. My site was working fine until I deployed it to Heroku. When I add a new post to my site I am presented with the following error: ERROR MESSAGE - ValueError - Required parameter name not set Thank you for your help! -
How to filter a Django model based on requirement from another model?
I'd like to retrieve all my contacts from my Contact model excluding those listed on my DoNotContact model. Is the following the most efficient way to do that: contacts = Contact.objects.filter(dont_contact=False) Wondering if this is going to take long to process, is there a more efficient way? class Contact(models.Model): email = models.CharField(max_length=12) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) audience = models.ForeignKey(Audience, on_delete=models.CASCADE) def dont_contact(self): try: get_object_or_404(DoNotContact, email=self.email) return True except: return False def __str__(self): return self.email class DoNotContact(models.Model): email = models.CharField(max_length=12) #views.py def send_email(request): if request.method == "POST": contacts = Contact.objects.filter(dont_contact=False) -
How to redirect API call to another API which will return the response to the requester directly
CLIENT Side: UserA requests GET /file/from/some/location SERVER Side: UserA request will hit the API1 which will generate a URL and redirect the user to API2 the API will take the generated URL and return the file to the user directly without sending a response to the API1. -
Django: How to add model class inside class or refer?
I have a class called artist which is a profil for an artist class Artist_object(models.Model): surname = models.CharField(max_length=120) name = models.CharField(max_length=120) Biography = models.TextField(default='Bitte Biography eingfügen', null=False) now I want that this artist can have multiple paintings with a desrciption. class Artist_painting(models.Model): painting1 = models.ImageField() painting1_desc = models.CharField(max_length=120, default=None) painting2 = models.ImageField() painting2_desc = models.CharField(max_length=120, default=None) How can I put class Artist_painting inside the Artist_object that for every artist I view (i got def get_absolute_url(self): return f'/artist/{self.id}' ) it have an description for every image ? -
How to create a new record using a django form
I want to create a new record by using django form but I am stuck on it and i get this kind of error IntegrityError at /academy/add_academy/3/ null value in column "Student_name_id" violates not-null constraint DETAIL: Failing row contains (39, da10, 2020-03-06, A, 11, 11, null). Here is my view.py file def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.filter(Student_name=child) form=AcademicForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } return render(request,'functionality/more/academy/add.html',context) Also this is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And here is my template file <div class="card"> <div class="card-header bg-primary text-white"> <h4> <i class="fas fa-user-plus"></i> Enter {{child.Firstname}} {{child.Lastname}} details </h4> </div> <div class="card-body"> <form action="" method="POST" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </form> </div> Thanks for your help -
Docker-compose can't import Django (ModuleNotFoundError)
I'm very new to Docker and I've been trying to get a very simple 'Hello World' program to run on docker. No matter what I do I always get "ModuleNotFoundError: No module named 'Django'" I've been stuck with this for two days now. Still no luck. Could you please point me in the right direction? What am I doing wrong? Here's the terminal output. C:\path\to\app\root>docker-compose up Creating network "hello-world_default" with the default driver Creating hello-world_web_1 ... done Attaching to hello-world_web_1 web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 10, in main web_1 | from django.core.management import execute_from_command_line web_1 | ModuleNotFoundError: No module named 'django' web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 21, in <module> web_1 | main() web_1 | File "/code/manage.py", line 16, in main web_1 | ) from exc web_1 | ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? hello-world_web_1 exited with code 1 Here's the dockerfile # Pull base image FROM python:3.7 # Set environmental variables … -
Trying to display multiple image for my product
I'm trying to display multiple images for one product but the images won't display and i don't know why can anyone help. My Models. I have to image field one is used to display and product and if the user wants more detail the other is used to show more images of the product. class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def get_absolute_url(self): return reverse('single',args=[self.id,self.slug]) class ProductImage(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return self.product.image Views def single(request, id, slug): try: # products = Product.objects.get(slug=slug) product = get_object_or_404(Product, id=id, slug=slug) images = ProductImage.objects.filter(product=product) return render(request, "single.html", {'product': product}, {'images':images}) except: raise Http404 How I tried to display the images on the Html page. {% for img in images %} {% if item.featured %} <img class="img-responsive"src="{{ MEDIA_URL }}{{ img.image.url }}" height="px" width="px" class="pr-5 mr-5"> {% endif %} {% if not item.featured %} <img class="img-responsive"src="{{ MEDIA_URL }}{{ img.image.url }}" height="px" width="px" class="pr-5 mr-5"> {% endif %} {% endfor %} -
Cannot run Django with active venv in zsh
I've got a properly activated venv in zsh, because I can see (venv) at the beginning of the prompt, but when I try to run Django with the command python manage.py runserver I've the error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? If I run which which python I can see python: aliased to /usr/local/bin/python3.7 that it seems wrong, because I expect something like /Users/myuser/Python-Projects/test/venv/bin/python. In fact if I disable the venv the result of which python is the same. I tried to the same steps with bash and everything works fine, so I guess I've got something wrong with zsh, but I don't know what. … -
Django how can i make inner join
MY models.py class Forms_in_Document(models.Model): document_submit = models.ForeignKey(Document_submit, on_delete=models.CASCADE) class Document_data(models.Model): forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE) document_structure = models.ForeignKey(DocumentStructure , on_delete=models.CASCADE) date_created= models.DateTimeField(default=datetime.now(),null=False) string = models.CharField(null=True, max_length=100) integer = models.IntegerField(null=True) date_time = models.DateTimeField(null=True) class Application(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=False) date_created = models.DateTimeField(default=datetime.now(),null=False) forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE, null=True) closed = models.BooleanField(default=False, null=False) new = models.BooleanField(null=False) media = models.BooleanField(default=True) Path_info = models.ForeignKey(Path_info, on_delete=models.SET_NULL,null=True) The raw SQL query that I am trying to do in Django views.py is "Select * from Application app inner join Document_data dd on dd.forms_in_document=app.forms_in_document" How can I do this using Django in my VIEWS.PY Thanks in Advance -
How can i get a url param for an updateview in django?
url: `path('my-domains/<str:domain_name>/dns-settings', login_required(DNSSettingsUpdateView.as_view()), name='dns_settings')` I want to get to use in my updateview: class DNSSettingsUpdateView(UpdateView): model = Domain form_class = NsRecordModelForm template_name = "engine/dns_settings.html" def get_object(self, queryset=None): return Domain.objects.get(name=[would insert it here]) def get_success_url(self): return reverse("my-domains") How can I do this? can anyone help? Thanks in advance -
Django AJAX delete object in deleteView
Good day. I'm trying to understand how to use ajax by deleting a object. Main problem, i don't understand how to pass slug argument to url in AJAX call. path('posts/<slug:slug>/delete/', DeletePost.as_view(), name='delete_post') class DeletePost(CsrfExemptMixin, DeleteView): queryset = Post.objects.all() def get_object(self, queryset=None): obj = super(DeletePost, self).get_object() profile = Profile.objects.get(user_id__exact=self.request.user.id) if obj.profile_id != profile.id: raise Http404 return obj def delete(self, request, *args, **kwargs): self.get_object().delete() payload = {'delete': 'ok'} return JsonResponse(payload) What i also want to understand, is the functionality correct? I've tested without json and get_object returns the correct object. {% for post in user_posts %} <tr id="post_table"> <th scope="row"> <input type="checkbox" aria-label="Checkbox" style="display: none"> </th> <td class="tm-product-name"><a href="{% url 'post:edit_post' post.slug %}">{{ post.title }}</a></td> <td class="text-center">145</td> <td class="text-center">{{ post.total_likes }}</td> <td>{{ post.created_at }}</td> <td><button class="delete-icon" onclick='deletePost({{ post.slug }})'>btn</button></td> {#<td><i class="fas fa-trash-alt tm-trash-icon delete-icon" id="{{ post.id }}"></i></td>#} <td> {#<form method="post" action="{% url 'post:delete_post' post.slug %}" id="delete">#} {#{% csrf_token %}#} {#<i class="fas fa-trash-alt tm-trash-icon"></i>#} {#</form>#} </td> </tr> {% endfor %} <script> function deletePost(slug) { let action = confirm('Are you sure you want to delete this post?'); if (action !== false) { $.ajax({ method: 'POST', url: '{% url 'post:delete_post'%}', success: function (data) { if (data.delete()) { $('#post_table').remove() } } }); } } </script> Obviously … -
what is the best way to implement operation-wise and row-wise authentication if there is something like this
I'm creating a project using DRF (Django Rest Framework), I'm stuck at a point while updating data in tables, I find it highly vulnerable to misuse. My code is below models.py from django.db import models from Mera.settings.common import AUTH_USER_MODEL from Mera.constant import UNIT_TYPES class Item(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, related_name='item_owner', null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) previous_code = models.CharField(max_length=100, blank=True, default="") short_name = models.CharField(max_length=100, blank=True, default="") serializers.py from rest_framework import serializers from commodity.models import Item from Mera.settings.common import AUTH_USER_MODEL class ItemSerializer(serializers.ModelSerializer): def create(self, validated_data): return Item.objects.create(**validated_data) def update(self, instance, validated_data): # instance.name = validated_data.get('name', instance.name) instance.save() return instance def to_representation(self, instance): response = super().to_representation(instance) response['owner'] = UserSerializer(instance.owner).data return response class Meta: model = Item fields = '__all__' class UserSerializer(serializers.ModelSerializer): items = serializers.PrimaryKeyRelatedField(many=True, queryset=Item.objects.all()) class Meta: model = AUTH_USER_MODEL fields = ['id', 'username', 'items'] views.py from rest_framework import generics from rest_framework import mixins from django.contrib.auth.models import User from commodity.models import Item from commodity.serializers import ItemSerializer, UserSerializer class ItemList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(owner=self.request.user) class ItemDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer def … -
why 404 in django url?
I made url for signUp page. but it returns 404 error. all of the other urls work well. I don't know the reason. main urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('mobileWeb.urls')), path('api/', include('api.urls')), ] Application urls urlpatterns = [ path('', views.index, name='index'), path('index', views.index, name='index'), path('addComment', views.addComment, name='addComment'), # users path('signUp', views.signUp, name='signUp'), path('accounts/', include('allauth.urls')), path('martDetail/<int:martId>', views.martDetail, name='martDetail'), path('trade/<int:itemId>', views.trade, name='trade'), path('registerMart', views.registerMart, name='registerMart'), path('registerItem', views.registerItem, name='registerName'), path('delete', views.delete, name='delete'), path('deleteMart', views.deleteMart, name='deleteMart'), path('deleteItem', views.deleteItem, name='deleteItem'), path('purchaseItem', views.purchaseItem, name='purchaseItem'), path('selectItem', views.selectItem, name='selectItem'), path('addStatistics', views.addStatistics, name='addStatistics'), path('viewStatistics', views.viewStatistics, name='viewStatistics'), path('imtPosRegister', views.imtPosRegister, name='imtPosRegister'), path('imtPosRegisterTest', views.imtPosRegisterTest, name='imtPosRegisterTest'), path('imtPosSaleInfoTest', views.imtPosSaleInfoTest, name='imtPosSaleInfoTest'), path('imtPosSaleConfirmTest', views.imtPosSaleConfirmTest, name='imtPosSaleConfirmTest'), path('fsOe9ms1b', views.fsOe9ms1b, name='fsOe9ms1b'), path('fsOe9ms1b_ma', views.fsOe9ms1b_ma, name='fsOe9ms1b_ma'), path('ssOe9ms1b', views.ssOe9ms1b, name='ssOe9ms1b'), path('ssOe9ms1b_ma', views.ssOe9ms1b_ma, name='ssOe9ms1b_ma'), path('tsOe9ms1b', views.tsOe9ms1b, name='tsOe9ms1b'), path('tsOe9ms1b_ma', views.tsOe9ms1b_ma, name='tsOe9ms1b_ma'), path('writeChatting', views.writeChatting, name='writeChatting'), path('imageUploadChatting', views.imageUploadChatting, name='imageUploadChatting') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 404 in web browser 404 in console -
Render objects from two queries in single for loop in Django
I am trying to fetch objects from two different queries by using select_related() in order to get all of the related objects. In template, I am using For loop in order to render all objects of first model separately, as separate containers of the data. Inside each of these rendered objects of the first model, I need to show the corresponding data from both queries for the related second model. The issue is that, when I am using For loop in template, I can only get the objects for the first related query, but not for the second query which is also related to the first model (basically, what second query is doing is getting all of the objects based on date less then today.) Here is the code: # IN THE MODELS class BillType(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name class Bill(models.Model): bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE, related_name='billtype') month = models.CharField(max_length=200) amount = models.IntegerField() due_date = models.DateField(blank=True) note = models.TextField(blank=True) recurring = models.BooleanField(default=True) currency = models.CharField(max_length=100) created_on = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.month # IN THE VIEW # This will get all of the Bill Types needed for For Loop in the template bill_types …