Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TANGLE.js in Django
I want to create a reactive calculator which would generate a result on the basis of the clicked check boxes. These check boxes would take price value from the database. I heard that TANGLE.js is the go to option for this. but I have no idea of TANGLE.js or how to create such a calculator and pass it in the Home template. Any hints on how to achieve this would be helpful. I'm posting the desired outlook of the calculator. models.py class FoodData(models.Model): item_name = models.CharField(max_length=50) item_price = models.SmallIntegerField(blank=False,null=False) class DecorData(models.Model): decor_item_name = models.CharField(max_length=50) decor_item_price = models.SmallIntegerField(blank=False, null=False) class PhotographyData(models.Model): photography_pkg_name = models.CharField( "Photography package", max_length=50) photography_price = models.SmallIntegerField(blank=False, null=False) homepage.html {% block asd %} <br> <div class='container' align='right'> {% if decor_count %} Decorations<hr> {% for i in decor_data %} {{ i.decor_item_name }} Rs.{{ i.decor_item_price }} {% if i.decor_pic %} <img src="{{ i.decor_pic.url }}" alt='Not found' width="124" height="124"/> {% else %} {% endif %} {% endfor %} {% else %} {% endif %} </div> <br> <div class='container'> {% if Web_count %} Wedding Related News<hr> {% for x in Web_data %} {{ x.web_title }}<br> <a href="{{ x.my_img }}"> <img src="{{ x.my_img }}" alt='{{ i.photography_pic }}' width="90" height="90"/></a><hr> {% endfor %} {% … -
Compare Django Count() to Integer
In my Django project. I am trying to show True/False if there are unanswered questions for a topic. I tried something along the lines of: Topic.objects.all().annotate(has_unanswered_questions = Count('question', filter = Q(question__status.text='open')) > 0) However, You can't compare type Count with int -
How many times a page had been visited? django2.1.7
I'm new to django, I made new site using django2.1.7 and now I want to some were in my template (e.g. in 'home.html' page) show the number of visit times of my site! I also check "django-tracking, django-tracking2- django-hint, django-tracking-analyzer, ..." but there were lots of error when i followed their instructions, its be very awesome if "django-tracking-analyzer" could work but it has very low detailed paper. no example, no temple_tags! or any one could guide me how to create my own one? django-tracking, django-tracking2- django-hint, django-tracking-analyzer -
Efficiently re-ordering a ranked collection in Django
Let's say I want to have collections of books and within each collection the books sorted by a unique ranking. One simple implementation may look like this: class Book(models.Model): title = models.CharField(max_length=100) class Collection(models.Model): # e.g. adventure, classic, fairy tale, .... genre = models.CharField(max_length=100) class Membership(models.Model): collection = models.ForeignKey(Collection, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) rank = models.PositiveSmallIntegerField() class Meta: ordering = ('rank',) # 1. Can't have same rank twice in a given collection # 2. Don't want duplicate books in same collection unique_together = (('collection', 'rank'), ('collection', 'book')) This works OK, but the main problem is if I want to re-order the collection in an arbitrary way whilst respecting uniqueness constraints E.g. Let's say some collection has War and Peace Crime and Punishment The Gambler For Whom The Bell Tolls Moby Dick And we want to re-order to Moby Dick For Whom The Bell Tolls Moby Dick Crime and Punishment The Gambler How can we do that? Simply trying to re-assign ranks like Moby Dick = 1, would fail, because there'd already be a Membership with rank 1 ("War and Peace") and the unique constraints would forbid it. I'd have to somehow change all the … -
How to translate the post in Django?
I am trying to make a multilingual website using i18n. I almost translate all the text, but I can’t even imagine how to translate my posts. I use mixins in my project. img (click here) html post detail template: <h3> {% trans post.title %} </h3> <h6 style="float: right; opacity: 0.5; margin-top: 6px; margin-right: 30px;"> {{ post.date_pub }} </h6> <div style="clear: right;"></div> <p> {{ post.body|safe }} </p> models.py: class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, blank=True, unique=True) body = RichTextUploadingField(blank=True, db_index=True) description = models.TextField(max_length=100, blank=True, db_index=True) tags = models.ManyToManyField('tag', blank=True, related_name='posts') date_pub = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('post_update_url', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('post_delete_url', kwargs={'slug': self.slug}) def save (self, *args, **kwargs): if not self.id: self.slug = gen_slug(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['-date_pub'] forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'slug', 'body', 'tags', 'description'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'slug': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.TextInput(attrs={'class': 'form-control'}), 'tags': forms.SelectMultiple(attrs={'class': 'form-control'}), } def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug may not be "Create"') return new_slug views.py class PostDetail(ObjectDetailMixin, View): model = Post template = 'main/post_detail.html' class PostCreate(LoginRequiredMixin ,ObjectCreateMixin, View): … -
Making a django attribute an abstract property
I have a parent class which should be inherited by child classes that will become Django models. The child classes all have a common property x, so it should be an abstract property of the parent. The thing that differs between the children, is whether the property is a django model attribute or if it is directly set. class A(Model, metaclass=abc.ABCMeta): class Meta: abstract = True @property @abc.abstractmethod def x(self): pass class B(A): x = "hello" class C(A): x = models.CharField(max_length=100, default='defaultC') class D(A): x = models.CharField(max_length=50, default='defaultD') So in my example, for some child classes the property x is known, but in other cases it needs to be selected. But one certain thing is that all descendants of the class A need an x attribute as it is a common property that must be defined by any descendants. The problem is that if I ever instantiate a class of C or D, I get the following: TypeError: Can't instantiate abstract class C with abstract methods x I think the issue is something behind the scenes with Django's metaclass. It removes any django model attributes and replaces them with deferred attributes, or something, and so the property is never actually … -
Not able to change the view of **Login-Logout** link in templates. Stuck at **Login** only. View of Login not changing to Logout if already logged in
I am building an app to do some work. Work requires the login of a user. Everything is working fine except the change in view of login to logout. SO this is my code for user_login and user_logout in view.py from django.shortcuts import render from purpose_finder import forms from purpose_finder.functions import find_purpose from purpose_finder.forms import UserForm,UserProfileInfoForm from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import login,logout,authenticate @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) and this is for user_login def user_login(request): if request.method=="POST": username=request.POST.get('username') #get field from HTML code password=request.POST.get('password') user=authenticate(request, username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Deactivated") else: return HttpResponse("Login Failed!!") else: return render(request,'purpose_finder/login.html',{}) and this is the code for base.html which is being inherited for most of the forms using Bootstrap for static navigation bar on top <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <ul class="nav navbar-nav"> <li><a class="navbar-brand" href="{% url 'index' %} " >Home</a></li> <li><a class="navbar-link" href="{% url 'admin:index' %}" >Admin</a></li> <li><a class="navbar-link" href="{% url 'purpose_finder:user_register' %}" >Register</a></li> {% if user.is_auhenticated %} <li><a class="navbar-link" href="{% url 'user_logout' %}">Logout</a></li> {% else %} <li><a class="navbar-link" href="{% url 'purpose_finder:user_login' %}" >Login</a></li> {% endif %} </ul> </div> </nav> I can Login and logout … -
Django models issue
I have created a model in Django as shown below class work(models.Model): Image = models.FileField() text = models.CharField(max_length=10000) sub_text = models.CharField(max_length=10000) color=models.CharField(max_length=200) opacity = models.CharField(max_length=200) link =models.CharField(max_length=10000) grid_column = models.CharField(max_length=10000,blank=True) category = models.CharField(max_length=200,default=all) def __str__(self): return '{}'.format(self.text) and while am trying to add values to that models through admin panel it throws the below error TypeError at /admin/mysite/work_dummy/add/ all() takes exactly one argument (0 given) Can anyone help me to solve this -
explain through_relation construction for MTM relation
I work on the project. Faced the following construction. Previously, I have not seen this anywhere. I do not understand at all what it is and why? Explain, please. M2M_FIELDS = { 'capitalization_periodicity': { 'm2m_relation': 'capitalization_periodicity', 'through_relation': 'credit_capitalization_periodicity_through', 'rel_field': 'capitalization_periodicity', }, -
React: How to solve unexpected token (<) error?
Related to this tutorial: https://www.youtube.com/watch?v=GieYIzvdt2U I get the error: ERROR in ./leadmanager/frontend/scr/components/App.js 6:15 Module parse failed: Unexpected token (6:15) You may need an appropriate loader to handle this file type. | class App extends Component { | render() { > return <h1>React App</h1> | } | } @ ./leadmanager/frontend/scr/index.js 1:0-35 when I run npm run dev You can find my code on https://github.com/bewaresandman/django I'm pretty sure my code mirrows exacly the one from the tutorial, so I'm at my wit's end. Several solutions from the Internet. Double checking the code, and so on. -
How to fix "KeyError: '*' " in elasticsearch
I'm trying to implement elasticsearch in my project, but I got this error when I tried to run this command python manage.py index_orders I've tried changing the elasticsearch version to the latest one (7.1.1) and run it. This is my command method which I'm trying to run index_orders.py help = 'Indexes Orders in Elastic Search' def handle(self, *args, **options): es = Elasticsearch( [{'host': settings.ES_HOST, 'port': settings.ES_PORT}], index="order" ) order_index = Index('order') order_index.doc_type(OrderDoc) if order_index.exists(): order_index.delete() print('Deleted order index.') OrderDoc.init() result = bulk( client=es, actions=(order.indexing() for order in Order.objects.all().iterator()) ) print('Indexed orders.') print(result)``` This is the error message ```Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/app/blowhorn/order/management/commands/index_orders.py", line 26, in handle OrderDoc.init() File "/usr/local/lib/python3.6/site-packages/elasticsearch_dsl/document.py", line 138, in init i.save(using=using) File "/usr/local/lib/python3.6/site-packages/elasticsearch_dsl/index.py", line 289, in save current_settings = self.get_settings(using=using)[self._name]['settings']['index'] KeyError: '*' -
How can I do to delete some entries? [duplicate]
This question already has an answer here: In Django QuerySet, how do I do negation in the filter? 1 answer I have this code : A.objects.filter(specialid=a).specialid data.specialid And actually the specialid of data are included into A and I would like to delete the entries of A which are not in specialid of data Do you have an idea to do this ? Thank you ! -
How to make nested replies for comments in Django?
This is the end result of my current comment app in Django: How to I make it as such that the children of parent comments be nested to one another. These are associated codes, if you would like to alter it a bit: models.py class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) # content types framework content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def children(self): return Comment.objects.filter(parent=self) views.py def blog_detail(request, blog_slug): blog = get_object_or_404(Blog, slug=blog_slug) session_key = 'blog_views_{}'.format(blog.slug) if not request.session.get(session_key): blog.blog_views += 1 blog.save() request.session[session_key] = True content_type = ContentType.objects.get_for_model(Blog) object_id = blog.id # look at CommentManager as well comments = Comment.objects.filter(content_type=content_type, object_id=object_id).filter(parent=None) initial_data = { 'content_type':blog.get_content_type, 'object_id': blog.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_t = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model = c_t) obj_id = form.cleaned_data.get('object_id') content = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment = Comment.objects.create( user = request.user, content_type = content_type, object_id = obj_id, content = content, parent=parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) context = { 'blog': blog, 'categories': get_category_count(), 'comments':comments, 'form':form, … -
Passing Optional List argument from Django to filter with in Raw SQL
When using primitive types such as Integer, I can without any problems do a query like this: with connection.cursor() as cursor: cursor.execute(sql='''SELECT count(*) FROM account WHERE %(pk)s ISNULL OR id %(pk)s''', params={'pk': 1}) Which would either return row with id = 1 or it would return all rows if pk parameter was equal to None. However, when trying to use similar approach to pass a list/tuple of IDs, I always produce a SQL syntax error when passing empty/None tuple, e.g. trying: with connection.cursor() as cursor: cursor.execute(sql='''SELECT count(*) FROM account WHERE %(ids)s ISNULL OR id IN %(ids)s''', params={'ids': (1,2,3)}) works, but passing () produces SQL syntax error: psycopg2.ProgrammingError: syntax error at or near ")" LINE 1: SELECT count(*) FROM account WHERE () ISNULL OR id IN () Or if I pass None I get: django.db.utils.ProgrammingError: syntax error at or near "NULL" LINE 1: ...LECT count(*) FROM account WHERE NULL ISNULL OR id IN NULL I tried putting the argument in SQL in () - (%(ids)s) - but that always breaks one or the other condition. I also tried playing around with pg_typeof or casting the argument, but with no results. Notes: the actual SQL is much more complex, this one here … -
how to add new auto incremented column in mysql db using django?
i need some help.in my form i set +button and clicking on that a new text box is auto generated. now how can i stored the data of new textbox in mysql using django? please help me to find out... thanks in advance.. models.py class Rows(models.Model): service=models.TextField(default='',max_length=200) item=models.TextField(default='',max_length=200) def __str__(self): return self.service add1.html <body> <div class="col-sm-2"> <form method="post" action=""> {% csrf_token %} <table id="myTable" class=" table order-list" > <tbody> <tr> <th> <label for="id_service" name="service">Services Provided</label> </th> <td> <textarea name="service" maxlength="500" required id="id_service"></textarea> </td> <td colspan="5" style="text-align: left;"> <input type="button" class="btn-sm-2 pull-right btn btn-success" id="addrow" value="+"/> </td> </tr> </tbody> </table> <table id="Table" class=" table order-type"> <tbody> <tr> <th> <label for="id_item" name="item">Awards</label> </th> <td> <textarea name="item" maxlength="500" required id="id_item"></textarea> </td> <td colspan="5" style="text-align: left;"> <input type="button" class="btn-sm-2 pull-right btn btn-success" id="addaward" value="+" /> </td> </tr> </tbody> </table> <button type="submit" >submit</button> </form> <a href="{% url 'work:add' %}"> </a> </div> </body> <script> $(document).ready(function () { var counter = 0; $("#addrow").on("click", function () { var newRow = $("<tr>"); var cols = ""; cols += '<td><input type="text" class="form-control" name="service' + counter + '"/></td>'; newRow.append(cols); $("table.order-list").append(newRow); counter++; }); }); $(document).ready(function () { var counter = 0; $("#addaward").on("click", function () { var newRow = $("<tr>"); var cols = … -
Model Many to Many relations with Abstract Class (error : fields.E331)
I test this code : https://code.djangoproject.com/ticket/11760# but he does not work class ClassA(models.Model): pass class AbstractClass(models.Model): name = models.ManyToManyField(ClassA, related_name = '%(class)s_name', through = 'ClassA_%(class)s') class Meta: abstract = True class MyClass(AbstractClass): pass class ClassA_MyClass(models.Model): class_a=models.ForeignKey(ClassA, on_delete=models.CASCADE) my_class=models.ForeignKey(MyClass, on_delete=models.CASCADE) I have this error : (fields.E331) Field specifies a many-to-many relation through model 'ClassA_%(class)s', which has not been installed. -
Django's GUI is broken at my URL homepage on pythonanywhere
I don't know why but my homepage's GUI is broken and only shows text in my homepage on pythonanywhere Even my admin page doesn't have any GUI but only text (like when our webbrowser fails to load HTML webpage ...) -
Cannot open include file: 'mysql.h'
I am new to Python and Django. Now I would like to connect to mysql from Django and I just run pip install mysqlclient. First I installed xampp and I just use phpmyadmin to connect MySQL and I created new database and tables Second I installed Microsoft Builds Tools 2017 But this error is still showing. So I just download the MySql and I got a zip file. I extracted and mysql.h exist in this folder. I don't know what I have to with this zip file. :( Third I download the mysql-installer.msi and I installed MySQL and python connection. but this error still happens. I am really messing with this database. So how can I connect to MySql from Django like other people does (They does like this is very easy.). -
NOT NULL constraint failed: instashot_data.user_id
I am rendering a form and when I am submitting that form getting this error IntegrityError NOT NULL constraint failed: instashot.user_id models.py class data(models.Model): description = models.CharField(max_length=400) user = models.ForeignKey(User,on_delete=models.CASCADE) img = models.ImageField(upload_to='images/') form.py class info(forms.ModelForm): class Meta: model = data fields = ['description','img', ] views.py def detail(request, template_name='website.html'): if request.method == 'POST': form = info(request.POST, request.FILES) if form.is_valid(): form.save() else: form = info() return render(request, template_name, {'form': form}) .html <div class="container"> <div class="jumbotron"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> </div> </div> I don't know why this error is coming -
This field is required Error when make POST request DRF
When I try to POST through the browser, request can't save field organization. Photo of POST request: Provide below my code. serializers.py: class DescriptionOrganizationSerializer(serializers.PrimaryKeyRelatedField, serializers.ModelSerializer): class Meta: model = Organization fields = ("id", "org_name") class DepartmentSerializer(serializers.ModelSerializer): emp_count_for_dep = serializers.SerializerMethodField() organization = DescriptionOrganizationSerializer(queryset=Organization.objects.all()) class Meta: model = Department fields = '__all__' models.py: class Organization(models.Model): org_name = models.CharField(max_length=100) def __str__(self): return self.org_name class Department(models.Model): dep_name = models.CharField(max_length=100) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='departments') def __str__(self): return self.dep_name views.py: class DepartmentView(viewsets.ModelViewSet): queryset = Department.objects.all() serializer_class = DepartmentSerializer Error: So I think it's maybe because I added queryset=Organization.objects.all() and PrimaryKeyRelatedField - without that, I can't select organization field and got another error (I solve it, but provide it here because this could help you understand my code more): AssertionError at /api/v1/department/ The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `api.serializers.DepartmentSerializer`, or set `read_only=True` on nested serializer fields. Another thought is ForeignKey in Organization model need to be changed to something like OneToManyField, but I'm not sure. Hope you will see, what I am missed here -
How to access django development server on virtual machine from hostcomputer?
ImageI have my actual laptop which has vmware player installed. I am running centos as a virtual machine and I installed django on the virtual machine and am testing my app so I did python manage.py runserver and I can access the app by visiting 127.0.0.1:8000 from my VM. I have tried following methods. As mentioned by Kerberos, in VMWare, go to Player ==> Manage ==> Virtual Machine Settings... On the Hardware tab, select Network Adaptor, then select the radio button for Bridged: Connect directly to the physical network. Select OK I tried running the server on 0.0.0.0:8000 by using python managge.py 0.0.0.0:8000 .Then, I tried to run django development server installed on vm by using the ip address of VM, it says 'chrome could not connect to http://:8000 '.. Any idea how to fix it? -
Is there any way in which I can edit "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css" file?
I tried doing it by creating a css file style.css in the same folder, copied the source code of the bulma link provided and then linked it to my html doc. But then, it shows no css features at all. -
Ajax returning empty string in Django view
I am developing a web application through Django and I want to get information from my javascript to a view of Django in order to access to the database. I am using an ajax call as this post shows. I am calling the js in html by an onclick event : sortedTracks.html ... <form action="{% url 'modelReco:sortVideo' video.id %}"> <input type="submit" value="Validate" onclick="ajaxPost()" /> </form> ... clickDetection.js function ajaxPost(){ $.ajax({ method: 'POST', url: '/modelReco/sortedTracks', data: {'tracksSelected': tracksSelected}, success: function (data) { //this gets called when server returns an OK response alert("it worked! "); }, error: function (data) { alert("it didnt work"); } }); }; So the information I want to transfer is tracksSelected and is an array of int like [21,150,80] views.py def sortedTracks(request): if request.is_ajax(): #do something print(request) request_data = request.POST print(request_data) return HttpResponse("OK") The ajax post works well but the answer I get is only an empty Query Dict like this : <QueryDict: {}> And if I print the request I get : <WSGIRequest: GET '/modelReco/sortedTracks/?tracksSelected%5B%5D=25&tracksSelected%5B%5D=27&tracksSelected%5B%5D=29'> I have also tried to change to request_data=request.GET but I get a weird result where data is now in tracksSelected[] -
how to implement ExpressionWrapper, F and Sum properly in django
I have two models Product and Damaged. Product has quantity of an item and Damaged has the number of damaged quantity of that item. In my template list_product I have listed total quantity of each product. When I add number of damaged_quantity into the Damaged model it should be deducted from the number of total quantity in Product. I have implemented the following code. Everything works fine. The only problem I am having is if the total number of quantity in Product is equal to number of damaged_quantity from Damaged it doesn't show 0 in the template of product_list. How to solve it? models.py class Damaged(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) damaged_quantity = models.IntegerField(default=0) class Product(models.Model): name = models.CharField(max_length=250) quantity = models.IntegerField() views.py def list_product(request): products = Product.objects.annotate(damaged_product_quantity=Sum( 'damagedproducts__damaged_quantity')).annotate( real_quantity=ExpressionWrapper(F('quantity')-F('damaged_product_quantity'), output_field=IntegerField())) damaged_products = Damaged.objects.all() return render(request, 'pos/list_product.html', {'products': products, 'damaged': damaged_products}) list_product template {% if not product.real_quantity %} {{product.quantity}} {% elif product.quantity == product.real_quantity %} 0 {% else %} {{ product.real_quantity }} {% endif %} -
My generic DetailView not showing list of items
I am following a django tutorial series, the music website contains the ListView which contains Albums(this is showing) but the DetailView Containing the list of songs in each Album is not showing. I have tried changing the iteration name in the for loop but it still not working, the list shows when i am not using the generic method i.e using index and detail function instead of the IndexView and DetailView classes. MY music.views Code class IndexView(generic.ListView): template_name='music/index.html' def get_queryset(self): return Albums.objects.all() class DetailView(generic.DetailView): model = Albums template_name = 'music/detail.html' My detail.html code which is supposed to show the list of songs but not working {% extends 'music/base.html' %} {% block title %} Album Details {% endblock %} {% block body %} <img src ="{{ all_album.alb_logo }}"> <h1>{{ all_album.alb_title }}</h1> <ul> {% for song in all_album.song_set.all %} <li>{{ song.song_title }} </li> {% endfor %} </ul> <br> {% endblock %} My index.html which shows the list of albums, this is working {% extends 'music/base.html' %} {% block body %} <h2>List of Current albums available</h2> <div class='container-fluid'> <div class='row'> {% for album in object_list %} <div class='col-lg-4'> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ album.alb_logo }}" > <div class="card-body"> <h5 class="card-title">{{ album.alb_title …