Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to import tensorflow on anaconda with python 3.6 version on 64bit system with 64bit anaconda
When I import tensorflow it gives me this error: Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\Users\User\Anaconda3\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "C:\Users\User\Anaconda3\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in import tensorflow as tf File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow__init__.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python__init__.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\Users\User\Anaconda3\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "C:\Users\User\Anaconda3\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/errors Please Help … -
Django: insert data in inhertance table using Django classbase function showing insert_id error
I'm submit form data in database using django classbase function. I create a modal and then create a inhert table for same modal and inserting data in inhert table using postgresql trigger function but when i'm submit my page django show me 'NoneType' object is not subscriptable error error image -
Copy a field translated with django-modeltranslation to another model instance
I would like to copy a translated field from a model instance A to another model instance B of a different class model.py class Product(OwnedModel): name = models.CharField(max_length=255,) class OrderedProduct(OwnedModel): name = models.CharField(max_length=255,) translation.py @register(Product) class ProductTranslationOptions(TranslationOptions): fields = ('name',) @register(OrderedProduct) class ProductTranslationOptions(TranslationOptions): fields = ('name', ) in my function: instance_ordered_product.name = instance_product.name instance_ordered_product This should copy the name filed for all language translations. Question: Is copying possible, without copying all languages individually, like instance_ordered_product.name_en = instance_product.name_en instance_ordered_product.name_fr = instance_product.name_fr -
show and create object from many2one relation in related model's template
I have this models design: class Node(models.Model): ID = models.DecimalField(max_digits=19, decimal_places=10) name = models.CharField(default='node', max_length=32) class Firm(models.Model): name = models.CharField(max_length=32) address = models.CharField(max_length=32) class ScheduledAction(models.Model): date = models.DateTimeField(default=datetime.now, blank=True) firm = models.ForeignKey('Firm', on_delete=models.CASCADE, null=True, blank=True) node = models.ForeignKey('Node', on_delete=models.CASCADE, null=True, blank=True) I created a form class for each model: NodeForm, FirmForm, and ScheduledActionForm. Now I want to create a template where: I can show for one Firm: the list of nodes (in a checkbox list), the list of already created scheduled actions for this firm, and a simple input area where for the selected nodes, I create scheduled actions. So this is what I started in planification.html: <div name="FirmName"> {{ object }} <h1>Firm: {{ object.name }}</h1> </div> <div name="NodesOfFirm"> {% for instance in object.node_set.all %} <input type="checkbox" name="{{ instance.name }}" value="{{ instance.id }}"> {{ instance.name }}<br> {% endfor %} </div> <div name="planification"> <h1>Planification</h1> </div> <div name="scheduledActions"> <h1>Scheduled Actions</h1> {% for instance in object.scheduledaction_set.all %} <p>{{instance.date}} - {{ instance.node }}</p> {% endfor %} </div> in views.py: def planification_view(request, id): obj = Firm.objects.get(id=id) context = { 'object': obj } return render(request, "node/planification.html", context) My problem is that I can't figure out how to create a scheduled action (input area in planification div). … -
How to acces the the django ManyToMany Field in django Template
I have set of attributes in my Models from which one of the attribute is of Type ManyToMany Field. I am able to access all the Attributes in Template instead of ManyToMany Field. I have tried following in my template {% for post in all_posts %} {{ post.likes }} {% endfor %} views.py def home(request): template = loader.get_template('home.html') all_posts = Posts.objects.all() context = { 'all_posts': all_posts, } return HttpResponse(template.render(context, request)) When i Use {{ post.likes }} what renders on page is auth.User.None -
Cannot load a static file in django template script tag
I'm using d3.js v3 for creating a Directed Graph in my Django template. When I try to get data from a csv file as below, d3.csv("file_name.csv", function(error, links) { ... }); and use links, I get an error stating TypeError: links is undefined Also in the command prompt I can see an error that file_name.csv could not be found. I'm suspecting it is looking for the file in some other location rather than in the template's directory itself. But I've tried putting the file in static folder as well and have had no luck. Note: However, if I open the html template directly in a browser and have file_name.csv in the same directory, everything works fine and I can see the graph being created. -
how to return two httpresponse in the same function
I need to return two response, let's call A response and B response, during the same triggering condition. I try to write a pseudo code to explain my question. def trigger_condition(request): return A_response, B_response or def trigger_condition(request): return A_response, then callback another_function def another_function(request): return B_response -
Django - Setting AUTH_USER_MODEL
I have created a Django project named Backend and in that, I have created an app called Tool. Now, I have created a User model by inheriting the AbstractUser model and I have created 2 accounts using this model. class User(AbstractUser): is_student = models.BooleanField(default=False) is_mentor = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) college = models.CharField(max_length=100) ... class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... I have updated the settings.py in Backend folder in this way: AUTH_USER_MODEL = 'Tool.user' After makemigrations and migrate, I am getting the following error: ValueError: Related model 'Tool.User' cannot be resolved -
Is there any other solution to set debug=false and make django project ready for production?
I'm developing one simple website that is for company profile along with products/service descriptions and blogs in Django==2.1.6 with python==3.7 and the database is Postgres. The development is finished and I was trying to host on the Heroku and succeed. But as it is not good practice to keep DEBUG=True for the production so I have set DEGUG=False and also set ALLOWED_HOSTS=['localhost', '127.0.0.1'] to test it locally but it returns Server Error (500). I have tried to run on Django server and also on the Heroku by hosting it and at both servers, it works perfectly if DEBUG=True. I was searching on the internet but all the answers/solution said "to set DEBUG=False, ALLOWED_HOSTS=['*'] for any hosts but which is not recommended for production or ALLOWED_HOSTS=['www.example.com','.example.com'] but any of this does not work on the Heroku or on Local. """ Django settings for FactOneTech project. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from django.contrib.admin import AdminSite import django_heroku AdminSite.site_header = "Fact One Tech Administration" # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start … -
Add ?q=search+term in django url
I want to integrate elastic search with django but first I need to get a nice parameter in url http://127.0.0.1:8000/search?q=search+term urls.py (of the view) urlpatterns = [ path('?q=', SearchIndexView.as_view(), name="search-index"), ] urls.py (of the app) urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('u/', include('user.urls')), path('search', include('search.urls')), ] That is what I have so far but I cant figure out how to make it work. I want to use tha path() and not url() if possible -
Why aren't MEDIA_URL and MEDIA_ROOT loading into template?
I'm using an inlineformset so that a user can upload multiple images at once. The images are saved and functionality is as expected, except on the front-end side. When I loop through my formset with a method resembling {{ form. image }}, I can clearly see that my image is saved and when I click the url, I am redirected to the uploaded file. The problem seems to be that the absoulte url is not stored when I try to set the image's URL as a src for an image element. Trying to log MEDIA_URL and MEDIA_ROOT in a <p> tag yields no results. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ROOT_URLCONF = 'dashboard_app.urls' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] models.py class Gallery(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) image = models.ImageField(upload_to="gallery_images") uploaded = models.DateTimeField(auto_now_add=True) views.py def EditProfile(request): user = request.user galleryInlineFormSet = inlineformset_factory(get_user_model(), Gallery, form=GalleryForm) selectedUserGallery = Gallery.objects.filter(user=user).order_by('uploaded') userGallery_initial = [{'image': selection.image} for selection in selectedUserGallery] # Using this syntax because formset initials accept dictionaries if request.method == "POST": profile_form = ProfileEditForm(request.POST, instance=request.user) gallery_inlineformset = galleryInlineFormSet(request.POST, request.FILES) # Essentially, we're passing a queryset if profile_form.is_valid() and gallery_inlineformset.is_valid(): # Altering the User … -
Django How to Get rid of Migration Errors
I am using Django ; and when I change a model , getting an error everytime . I am changing only one field in model, and getting stupidly a lot of errors EVERYTIME. django.db.utils.OperationalError: no such table: or django.db.migrations.exceptions.InconsistentMigrationHistory: or OperationalError no such column: table.colunm or django.db.utils.OperationalError: "Table already exists" and bla bla bla.. I got maybe all error types in Django , and now it is bothering me really. I am trying all solutions everytime : Delete migrations find . -path "/migrations/.py" -not -name "init.py" -delete find . -path "/migrations/.pyc" -delete Clear the migration history for each app Remove the actual migration files. Create the initial migrations Fake the initial migration python manage.py migrate --fake python manage.py migrate --fake-initial python manage.py migrate --run-syncdb Drop database Every solutions what i can find. Stupidly trying all the solutions , and; at the last , yes i can find solutions BUT , I really really bored now from this stupidly errors. Is there any way to get rid of migration errors in Django ? Only I need the answer for this ; 'When I change a model field only, why am I getting these all madly errors, EVERYTIME ??!!!?' For example : … -
how to show the rank based on a field value in django Templates?
I have a list of details which contain total score. i want to show the rank based on the total score. if the scores are equal the rank must be same. how to do it? thanks in advance. {% for rank in ranking %} {% with forloop.counter as count %} <tr> <td>{% if rank.name %} {{rank.name}} {% endif %}</td> <td>{{count}}</td> <td>{% if rank.total_score %}{{rank.total_score}}%{% else %} {% trans '0%' %}{% endif %}</td> </tr> {% endwith %} {% endfor %} -
How to access data of Django ManyToMany Field?
I want to Create a Like Functionality in Home page of my Social media Website. I am using ManyToManyField for Storing Likes on Particular post as shown in models.py. In my home page I have list of Posts and I want to check weather a Posts in already Liked by Current Logged in User or not. In my views.py I am using post = Posts.objects.filter('likes') if post.likes.filter(id=request.user.id).exists(): models.py class Posts(models.Model): title = models.CharField(max_length=250, blank=False) content = models.CharField(max_length=15000, help_text="Write Your thought here...") likes = models.ManyToManyField(User, blank=True) views.py def home(request): post = Posts.objects.filter('likes') print('Thats just Test', post) if post.likes.filter(id=request.user.id).exists(): print("Already Exixts") is_liked = False context = { 'all_posts': all_posts, 'is_liked': is_liked, } return HttpResponse(template.render(context, request)) hometemplte.html: (Only Like Button) <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" name="like" value="{{ post.id }}" class="btn upvote liked">Liked</button> {% else %} <button type="submit" name="like" value="{{ post.id }}" class="btn upvote">Upvote</button> {% endif %} </form> -
How to change the data before .create is called in django rest
I have this following model class User(models.Model): UserName = models.CharField(max_length=20) Password = models.CharField(max_length=255) RoleName = models.CharField(max_length=30) Email = models.EmailField(max_length=50) ApartmentName = models.CharField(max_length=50) UserId = models.BigAutoField(primary_key=True) I have saved the data by calling this view class Register(generics.CreateAPIView): serializer_class = serializers.UserSerializer def get_queryset(self, *args, **kwargs): return models.User.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) But before the row to be created in the database table i need to change the password to the hashed form, i cant alter the post variables in the request since it is immutable.How to hash the password with make_password before saving the data? -
Best Possible Architecture to Design a heatlchare SaaS with ML and AI embedded
I am designing a healthcare SaaS platform for my new Startup. Its a platform for early stage diagnosis of disease like tumor, breast cancer etc. and it will also connect patients with doctors for further treatment options. Now, I am confused between 2 of the possible ways to do that. Build my microservices and Frontend on MERN Stack. Build and Train my AI models on Python and Expose them via a Flask Restful API , then connect them with my Nodejs Microservices. Build and Deploy Everything (From Basic microservices to AI AND ML Models) using Django and Python alone. I am thinking to go on with the first approach because doing it this way would separate my ML, CPU Intensive Code and the basic microservices code and it will be easier to extend in future. -
Forms only showing up after submit button is clicked
I've checked similar posts about forms not showing up at all and I've tried applying the fixes, but it did not fix it for me. I have the following: search.html: <form method="post" class="form-inline my-2 my-lg-0"> {% csrf_token %} {{ symbol_form }} <button class="btn btn-secondary my-2 my-sm-0" type="submit">Add Stock</button> </form> views.py: class PortfolioStockListView(ListView): model = StockPortfolio template_name = 'stocks.html' def post(self, request): symbol_form = StockSymbolForm(request.POST) if request.method == 'POST': if symbol_form.is_valid(): model_instance = symbol_form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return redirect('/') else: print(symbol_form) return render(request, 'stocks.html', {'symbol_form': symbol_form} ) else: form = StockSymbolForm() return render(request, 'stocks.html', {'symbol_form': symbol_form} ) forms.py: class StockSymbolForm(ModelForm): class Meta: model = StockPortfolio fields = ['username', 'stock_symbol' , 'stock_qty'] models.py: class StockPortfolioUser(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) usercash = models.PositiveIntegerField(default=100000) class StockPortfolio(models.Model): username = models.ForeignKey(StockPortfolioUser, on_delete=models.CASCADE) stock_symbol = models.CharField(max_length=5) stock_qty = models.PositiveIntegerField(default=0) How to fix the issue that is causing the forms to hide until the button is clicked? I can share more code from other files if necessary. -
getting ConnectionDoesNotExist error when attempting to migrate mysql database in django
here's my code in django settings.py for the database: DATABASES= { 'defualt': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cameronkc', 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '' } } here's the error im recieving when executing >python manage.py migrate in command prompt django.db.utils.ConnectionDoesNotExist: The connection default doesn't exist -
Django(v2.0.7) Admin: Callback post DB transaction commit
I've a huge model with a lot of attributes including multiple ManyToManyMapping. Most of the addition/update in app is via REST API, but for minor correction I have used Django Admin Form. This admin form also has multiple inline formset. I want to publish some event to Kafka(publish_event) after the model is updated either through form or REST API. And I want this to happen when the transaction is committed to DB so that services listening to Kafka events don't end up fetching stale data from DB. I referred this SO post but it appears to be doing it on every transaction not on per model basis and having on_commit poses problems of things getting called twice(more below). Things I've tried so far: Signals: Rejected since due to adding ManyToManyMapping, model.save() needs to be called twice which ended up with 2 events published. Also, it operates on model save, not transaction commit, so in case of rollback, I will still end up with publishing an event. Overriding model's save(self, *args, **kwargs): method: Rejected for same reason as model.save() is called twice. Overriding ModelAdmin's save_model: This is one of the first things to be called when we hit Save on form, … -
Author_name not showing up in Django syndication rss feed
I have a Django-based site. It has a feed which uses the django syndication framework). Although I've specified author_name in the feed's definition, no author appears in the feed itself. An author is required to submit the feed to all the directories I've checked with. My feeds.py looks like this: from django.contrib.syndication.views import Feed from django.utils.feedgenerator import Rss201rev2Feed from Audits.models import Audit from django.urls import reverse class SubscriptionFeed(Feed): feed_type = Rss201rev2Feed title = "Audio feed title" link = "/listen/" description = "A description of the audio feed." author_name = "Example feed author" author_email = "example@gmail.com" def items(self): return Audits.objects.all().filter(published=True).exclude(audio_file='').order_by('-year_integer', '-month_integer') def item_title(self, item): return item.title def item_description(self, item): return item.abstract def item_link(self, item): return reverse('Podcast-Pages', args=[item.pk]) def item_author_name(self, item): return "Example Item Author" -
Can't import models to celery tasks.py file
in my tasks.py file I want to import models from polls app, but I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet when starting the worker tasks.py from __future__ import absolute_import import sys ,os from polls.models import User from .celery import app @app.task def add_user(user): # for user in users: print('urra') #user = User(user.first_name, user.last_name, user.email) # user.save() celery.py: from __future__ import absolute_import, unicode_literals from celery import Celery import os, sys from task import celery_config import dotenv from os.path import dirname, join app = Celery('task', broker='amqp://root:lusine_admin@localhost/task', backend='amqp://', include=['task.tasks']) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "task.settings") app.config_from_object(celery_config) # app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) if __name__ == '__main__': app.start() Actaually I got error polls module not found, but then from bash I added it to pythonpath and know I get this error. -
How to test if form.is_valid(): using Django unit test
The urls.py part that sends the request : path('branch/add/', views.branch_add, name="branch_add"), The form: class AddBranchForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'إسم الفرع '})) class Meta: model = models.Branch fields = ['name'] Here is the view : @login_required def branch_add(request): print('############################') add_branch_form = forms.AddBranchForm(request.POST) if request.method == 'POST': if add_branch_form.is_valid(): form = add_branch_form.save(commit=False) check = models.Branch.objects.filter(name=form.name) if check.count() != 0: messages.error(request, 'يوجد فرع بهذا الاسم بالفعل') else: form.save() new_storage = models.Storage(name='مخزن ' + str(form.name), branch=form) new_storage.save() return redirect('branch_details', pk=form.id) else: add_branch_form = forms.AddBranchForm(request.POST) context = { 'add_branch_form': add_branch_form, } return render(request, 'branch_add.html', context) And finally the test file: class TestBranchAdd(TestCase): def test_add_branch_view_loads(self): self.user = User.objects.create_user(username='user', password='test') self.client.login(username='user', password='test') # defined in fixture or with factory in setUp() response = self.client.get('/branch/add/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'branch_add.html') def test_post(self): self.client.login(username='user', password='test') # defined in fixture or with factory in setUp() response = self.client.post(path=reverse('branch_add'),data={'name':'test_name'}) self.assertEqual(response.status_code, 302) Here am testing the get and post request for the view, now I want to do a test for the post request that takes data and checks on the part of if add_branch_form.is_valid(): , how to do this? -
django.db.utils.ProgrammingError: relation "accounts_myuser" does not exist
Ubuntu 16.04 LTS I'm working on a django project, and I'm using postgresql instead of sqlite3. The thing is, when I try to customize User model as shown in "https://docs.djangoproject.com/ko/2.1/topics/auth/customizing/", an error happens during migrating. After editing code just as that site, I added from django.contrib.auth import get_user_model User = get_user_model() wherever from django.contrib.auth.models import User is written. Then, at terminal, I ran python manage.py makemigrations and, I tried to run python manage.py migrate However, it doesn't migrate, showing this error: django.db.utils.ProgrammingError: relation "accounts_myuser" does not exist How can I fix this? Thank you. --------------The below is what shown at the terminal------------------- python manage.py migrate admin /home/seokchan/server/mdocker/lib/python3.5/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. """) System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/auth' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. Operations to perform: Apply all migrations: admin Running migrations: Applying admin.0006_auto_20181225_0549...Traceback (most recent call last): File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return … -
Django |safe Tag Preventing Google Map Callback Function
I am embedding a javascript Google Map in my Django project. Currently, I have the map working while passing in one model using the syntax {{past_deals|safe}}, where past deals was passed using Model.objects.all() from the views.py. I am attempting to pass another model using the same syntax: {{listing_deals|safe}}. I then parse the JSON data and use it for my needs. However, the when the '|safe' tag is added to only the listings data, it fails to callback the InitMap() function of google maps. However, the safe tag is working as directed, when I view the source of the page, the object data is parsed neatly in the same fashion as the past_deals data. I have tried using DjangoJSONEncoder but in the views.py it alerts me both my Listings and PastDeals models are not iterable. views.py from django.shortcuts import render from PastTransactions.models import PastTransaction from Listings.models import Listing from django.core import serializers def index(request): past_deals = serializers.serialize('json', PastTransaction.objects.all()) listing_deals = serializers.serialize('json', Listing.objects.all()) template = 'Map/index.html' context = { 'past_deals': past_deals, 'listing_deals': listing_deals } return render(request, template, context) <script type="text/javascript"> // The map to be used throughout script var map; // Array to hold markers currently on map var markers = []; … -
Displaying dictionary in html from django render
I am trying to display some data (which is outputted from django view as a dictionary) into a html collapseable div (from bootstrap3). For example i get the object "data" into my template which has the following structure: group value A 1 A 2 A 3 B 1 B 2 I know I can iterate through the object easily. For example {% for i in data %} {{i.group}} However, what I want to do is to be able to use the "group" as the parent within the collapseable and the items as the "values". Something like {% for i in data %} <div class="panel-group"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" href="#{{ i.group }}">{{ i.group }}</a> </h4> </div> <div id="{{ i.group }}" class="panel-collapse collapse"> <ul class="list-group" style="margin-left:30px"> <div class="row"> <li class="list-group-item">{{ i.value }}</li> </div> </ul> </div> </div> </div> {% endfor %} </div> As you can see the issue is that if i do it as the way above, it will create multiple parent catergories for the non-unique "group" values.