Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can't get the value of a RadioSelect to validate my form
I'm quite new to django, what I want to do: I have several music files and I want to let the user choose which music file he likes. I can display all files in a fieldset with radiobuttons to chose one file. What the html site looks like But when I try to proceed I get the following error: AttributeError at /creation/music 'list' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/creation/music Django Version: 2.2.10 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'get' Exception Location: C:\Users\ssi\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\forms\widgets.py in value_from_datadict, line 652 Python Executable: C:\Users\ssi\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['D:\\Dropbox\\dev\\django_project', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\ssi\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\Pythonwin'] Server time: Mi, 3 Jun 2020 14:26:43 +0000 For the form I used the following code (forms.py): class VideoMusicForm(forms.ModelForm): def __init__(self, round_list, *args, **kwargs): super(VideoMusicForm, self).__init__(*args, **kwargs) self.fields['music'] = forms.CharField(widget=forms.RadioSelect(choices=round_list)) class Meta: model = Video fields = ['music'] In my views.py I defined the following function: def makemusic(request): lst = getSamples() if request.method == 'POST': form = VideoMusicForm(request.POST, lst, instance=request.user.video) if form.is_valid(): form.save() return redirect('overview') else: form = VideoMusicForm(lst, instance=request.user.video) else: form = VideoMusicForm(lst, instance=request.user.video) return render(request, 'videomaking/music.html', {'form':form}) Here is the html file for this … -
How to pass multiple values from models.py to HTML via views.py in Django
I have a following models.py for my Django blog, I made a following views.py to pass the value of the slug for my URL parameter. However I am struggling to create a model in views to get other data(person & description) from Category class. I have tried some patterns by myself but can not pass them to HTML. (always Error or not showing) Can you please give me some idea of how to solve this. models.py class Category(models.Model): person = models.CharField(max_length=20) description = models.TextField() slug = models.SlugField() def __str__(self): return self.person views.py def blog_category(request, category): posts = Post.objects.filter(categories__slug__contains=category).order_by("-created_on").distinct() context = {"category": category, "posts": posts} return render(request, "blog_category.html", context) HTML(Localhost:8000/slug) {{ person }} {{ description }} -
Django manual form creating whitespace in between objects in option list
When this form renders it is creating a whitespace between options - as if you can select whitespace as an option. <div class="form-group col-md-6 mb-0"> <label>Select Category</label> <select id="categories" name="categories" class="form-control"> {% for category in form.category %} <option id="{{ category.id }}" value="{{ category.id }}"> {{ category }} </option> {% endfor %} </select> </div> What is wrong? -
How to get list of object(equipement) for each object (intervention) manytomany relationship in django
models equipement https://i.stack.imgur.com/38e6o.png models intervention https://i.stack.imgur.com/8V1JL.png models intervention with relationship manytomany so when i add a new "intervention" it will add to table of association https://i.stack.imgur.com/KZZcd.png i need to list all equipement of each intervention this is my view : https://i.stack.imgur.com/Mtnqf.png and this is when i list all intervention int template html https://i.stack.imgur.com/LSvzv.png -
How to remove objects from ManyToMany Field in Django Rest Framework neasted serializer?
I can successfully add a new object(s) into notification_days but what is the most idiomatic way to handle removing any object(s)? models.py DAYS_OF_WEEK = ( (0, 'Mon'), (1, 'Tue'), (2, 'Wed'), (3, 'Thu'), (4, 'Fri'), (5, 'Sat'), (6, 'Sun'), ) class WeekDay(models.Model): day = models.IntegerField(choices=DAYS_OF_WEEK) def __str__(self): return self.get_day_display() class Company(models.Model): name = models.CharField(...) notification_days = models.ManyToManyField(WeekDay) serializers.py class WeekDaySerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) day_display = serializers.SerializerMethodField() class Meta: model = WeekDay fields = ['id', 'day', 'day_display'] def get_day_display(self, obj): return obj.get_day_display() class CompanySettingsSerializer(serializers.ModelSerializer): notification_days = WeekDaySerializer(many=True) class Meta: model = Company fields = [ 'name', 'notification_days' ] def update(self, instance, validated_data): notification_days = validated_data.get('notification_days') for day in notification_days: day_id = day.get('id', None) if item_id: if not instance.notification_days.filter(pk=day_id).exists(): week_day = WeekDay.objects.get(pk=day_id) instance.notification_days.add(week_day) return instance api.py class CompanySettingsAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsCompanyAdmin, ) serializer_class = CompanySettingsSerializer def get_object(self): return Company.objects.get(pk=self.kwargs.get('pk')) Sample GET response: { "name": "Django", "notification_days": [ { "id": 1, "day": 0, "day_display": "Mon" }, { "id": 2, "day": 1, "day_display": "Tue" }, { "id": 3, "day": 2, "day_display": "Wed" } ] } -
Field Error during Password reset in Django custom user
I have a custom User in my django app. And when I submit an email to reset password in the the built in password reset form, I get the following error FieldError at /password_reset/ Cannot resolve keyword 'is_active' into field. Choices are: active, address, admin, bio, company_category, company_desc, company_name, company_site, country, designation, email, first_name, grad_year, id, last_login, last_name, linkedin, logentry, markets, no_employees, password, phone, photo, resume, staff, technologies, university My custom user model and model manager are as follows: # ----------------------------- USER MANAGER ----------------------------- class UserManager(BaseUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email = self.normalize_email(email), ) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.set_password(password) user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, staff=True, admin=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user # ----------------------------- CUSTOM USER ----------------------------- class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) resume = models.FileField(upload_to='res/', blank=True, null=True, verbose_name='resume') photo = models.ImageField(upload_to='pi/', default='img/default.png', blank=True, null=True) bio = models.CharField(max_length=1000) designation = models.CharField(max_length=255) university = models.CharField(max_length=255) company_name = … -
Django 3: Adding Data to DetailView
I have a very similar question to this and this and my guess is I overlooked something. I want to query related objects (foreign keys) from the model in the template: models.py: class PartBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price per part", decimal_places=2, max_digits=6) class Sett(models.Model): name = models.CharField('Name', max_length=120) class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='setts', on_delete=models.SET_NULL, null=True) views.py: class SetDetailView(DetailView): model = Sett context_object_name = "setts" template: {% for p in setts.partrelation_set.all %} <p>value: {{ p.get_part_price }}</p> {% endfor %} Problem: empty HTML page - so setts.partrelation_set.all is empty / does not exist. What I tried was adding a queryset to the view class: class SetDetailView(DetailView): model = Sett context_object_name = "setts" queryset = Sett.objects.all() def get_queryset(self): return self.queryset.filter(setts = self.kwargs.get("Sett_id")) But I took a wrong turn here somewhere. What I also tried is adding a lot of return attribute methods in the model and so I could get it to work in the shell - but not in the DetailView. -
No module named 'django.utils.six'
I cannot add img on admin site after use cloudinary on my django project. It will show error: No module named 'django.utils.six'. Does anything else need to setup? cloudinary config on setting.py: INSTALLED_APPS = [ ... 'cloudinary_storage', 'django.contrib.staticfiles', 'cloudinary', ... ] MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': '***', 'API_KEY': '***', 'API_SECRET': '*****', } urls.py: urlpatterns = [ ... ]+ static(settings.MEDIA_URL, document_root=settings.DEFAULT_FILE_STORAGE) models.py: class article(models.Model): title = models.CharField(max_length=200) content = RichTextField() slug = models.SlugField(unique=True) default='article_img/coming_soon.jpg') article_img = models.ImageField(upload_to='article_img', blank=True) status = models.IntegerField(choices=STATUS, default=0) topic = models.IntegerField(choices=TOPIC, default=0) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='article') -
How to remove/add many to many object in Django Rest Framework?
models.py DAYS_OF_WEEK = ( (0, 'Mon'), (1, 'Tue'), (2, 'Wed'), (3, 'Thu'), (4, 'Fri'), (5, 'Sat'), (6, 'Sun'), ) class WeekDay(models.Model): day = models.IntegerField(choices=DAYS_OF_WEEK) def __str__(self): return self.get_day_display() class Company(models.Model): name = models.CharField(...) notification_days = models.ManyToManyField(WeekDay) serializers.py class CompanySettingsSerializer(serializers.ModelSerializer): class Meta: model = Company fields = [ 'name', 'notification_days' ] api.py class CompanySettingsAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsCompanyAdmin, ) serializer_class = CompanySettingsSerializer def get_object(self): return Company.objects.get(pk=self.kwargs.get('pk')) Sample GET response: { "name": "Django", "notification_days": [ 1, 3 ] } I can send PUT with added or removed IDs in notification_days but how can I have objects instead of IDs and be able to update/remove it in PUT request? -
In my django project, a guest user inputs 3 or 4 records and takes printout the processed data. How to retrieve those records only
A guest user visits my site and enters some records in my model db. After he should view only those records only. My database already has some records. I want to list only this sessions records only. -
How do I allow my django website to be hosted by a local server (127.0.0.1) and a Heruko server
I don't know if I am explaining my problem correctly but I can clarify with the following picture of my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True DEBUG = False # ALLOWED_HOSTS = [] ALLOWED_HOSTS = ['sheryar-portfolio.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', 'calculator', 'amino' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Now here in ALLOWED_HOSTS, I have declared two hosts. The Heroku one is running perfectly whereas I am having some issues in the local one. It seems like that my static folder is not being located by django as I can only see the HTML of my website in local server. In short, I cannot see the CSS being applied to my website when I am including the local server in ALLOWED_HOST -
Celery Queues and after_task_publish
I'm trying to monitor my celery queues and which tasks they are running. The main idea is to get a better understanding of how everything works. I'm fairly new to celery outside of calling delay or setting up a periodic_task. I'm running into a bit of a pickle, no pun indented and I'm using datadog to monitor some of this information. What I setup is an after_task_publish function that I'd like to use to track the task and queue it was processed on. I actually would like the worker as well. I have extended my celery results so I can look things up in redis and see the queue. @after_task_publish.connect() def on_task_publish(sender=None, headers=None, body=None, **kwargs): task = app.tasks.get(sender) task_name = task.name queue_name = ( task.__dict__.get("_exec_options").get("queue") if task is not None else "unknown" ) tag = f"{queue_name}:{task_name}" statsd.increment("celery.on_task_publish.increment", tags=[tag]) Currently the tasks _exec_options queue is always None. Below is an example. {'queue': None, 'routing_key': None, 'exchange': None, 'priority': None, 'expires': None, 'serializer': 'json', 'delivery_mode': None, 'compression': None, 'time_limit': None, 'soft_time_limit': None, 'immediate': None, 'mandatory': None} Now this I don't understand because I set the queue, and also know the job ran so it had to be queued. sender.add_periodic_task( 10.0, health_check_background_crawls.s(), name="health_check_background_crawls", … -
Django Python - SQLDecodeError on deleted attribute after Migration
I am currently using Django2.2 with Djongo1.2.38, and running into a SQLDecodeError - DuplicateKey after I changed the model and ran a migration. I had a model, Project, that had an attribute called customer_po. I removed this attribute and changed around a bunch of attributes, and made/applied a migration. I can see in the output from making my migration this line: - Remove field customer_po from project I applied my migration and it was successful. I created a new project object, and when I go to create a second one I am met with this error: FAILED SQL: INSERT INTO "crud_project" ("id", "project_number", "purchase_order", "quotation_number", "client_name", "project_name", "project_owner_id", "project_manager_id") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s) Params: (UUID('eb7184ee-cc0c-4765-a04c-455a2a70af15'), '123', '12345', '321312', 'Hello', 'Ads', UUID('30f86ee3-e1b7-4820-a39e-c996a1799254'), UUID('c29f869a-e629-46b3-9cc6-cace7de1b987')) Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'customer_po': 1}, 'keyValue': {'customer_po': None}, 'errmsg': 'E11000 duplicate key error collection: psm.crud_project index: customer_po_1 dup key: { customer_po: null }', 'op': {'id': UUID('eb7184ee-cc0c-4765-a04c-455a2a70af15'), 'project_number': '123', 'purchase_order': '12345', 'quotation_number': '321312', 'client_name': 'Hello', 'project_name': 'Ads', 'project_owner_id': UUID('30f86ee3-e1b7-4820-a39e-c996a1799254'), 'project_manager_id': UUID('c29f869a-e629-46b3-9cc6-cace7de1b987'), '_id': ObjectId('5ed7c79ddfacbb6c0315927a')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} Even though the attribute is not in the params, or inside the … -
Heroku constantly change url for my heroku-redis addon
Im using the heroku-redis addon as a message broker for my django app, which is hosted on a VPS. The problem is that Heroku constantly change de URL of the service, so my app keep crashing from time to time, when the url is changed. Anyone knows a way to fix this? Is there a way of getting automatically the updated URL for my heroku-redis addon? -
How to get rid of this weird error in django?
I had migrated an app to Heroku recently and everything was going well until I hit a Server Error today, a normal 500 error that occurred due to requests being an old version. Once I had upgraded requests, the error still persisted and the site came only after I turned DEBUG=True in my settings.py file which is absurd because DEBUG should not be true but when I change it to False it triggers the same error and the problem is: 2020-06-03T15:13:41.896001+00:00 heroku[router]: at=info method=GET path="/" host=know-ur-level.herokuapp.com request_id=d4fd68f3-5111-493e-b75c-c4f5a9f2e519 fwd="49.37.194.191" dyno=web.1 connect=1ms service=618ms status=500 bytes=649 protocol=https 2020-06-03T15:13:41.893360+00:00 app[web.1]: 10.10.68.189 - - [03/Jun/2020:15:13:41 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36" I do not know what to make of this output. Can someone tell me what's wrong?. The reason I tagged this as python-requests is that maybe this error is somehow related to this? I'll put up the necessary files. Let me know if I can add anything more. My settings.py import os import django_heroku import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '******' DEBUG = True #area of absurdity … -
How to create Django application with User and ActivityPeriod models with help of RESTAPI for the below output?
This is an expected output JSON format. -
Django - Unable to import npm module from js file
I'm trying to import Vue as a npm module in my js file using this syntax : import Vue from 'vue'; But I get this error : Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../". But when I try any of these examples, it can't even find the folder node_modules in my application. Any idea ? -
Starting up an existing Django project by one command after cloning from git
Lately I have come across a requirement to facilitate the ability to start a Django project by one command. That is, they want to clone a Django project from git, go to the project root directory and run some majic command like python manage.py start_me_magically without going through all that tedious manage.py migrate, pip install -r requirements.txt stuff. I know that this sort of things are best solved by Docker, but I am looking for a vanilla solution in a form of a python script or a management command. I should also be able to automatically create a virtualenv, and run the project with this virtual env activated. Now I am going to write a simple python script like 'setup.py' and put it in the root directory of the project, but I am afraid to do something which would look like a novice "junk" solution, or to invent a wheel. After googling around, I wasn't able to find something similar, but I am sure there should be a ready-to-use solution for that. Any hints ? -
How should i save the data that i'm getting from a script into db (Django)?
So i'm new to django and i have a python Script which get's some data from an api and does some tasks on it and prints out a list with two variables. I get new data everyday from the api and i want to save the output of this script into the database automatically every time it runs. Can u guys give me a overall guide on how should i do this ? -
How to set field via m2m-changed?
I have a receiver function waiting for a m2m field to be changed. This receiver is called, but I can't set these fields in my model? My receiver looks like this, by the print option, I can see that is is called. @receiver(m2m_changed, sender=targetAdress.neighbours.through) def setNeighs(sender, instance,pk_set, action, **kwargs): if action == "post_add": objs = sender.objects.all() instance.neighbours.set(objs) For this I get a typeError because a DWDstation object is expected as neighbour. Instead I get a targetAdress.neighbours object. How do I transfer this into something that works? -
when i try to execute my code,i am getting this error?How to resolve this issue?
ProgrammingError at / (1146, "Table 'multi_traffic.django_session' doesn't exist") Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 1.11.5 Exception Type: ProgrammingError Exception Value: (1146, "Table 'multi_traffic.django_session' doesn't exist") Exception Location: C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\MySQLdb\connections.py in query, line 277 Python Executable: C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\Scripts\python.exe Python Version: 3.6.2 Python Path: ['F:\projects\MULTI_TRAFFIC\MULTI_TRAFFIC\Code\Multi_Traffic_Scene_Perception', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\Scripts\python36.zip', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\DLLs', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\Scripts', 'C:\Users\SAI RAM\AppData\Local\Programs\Python\Python36\Lib', 'C:\Users\SAI RAM\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages'] -
Conditional for loop in Django template
I'm using the same template for two different queryset. view: def events_list_view(request, type): events_NMS = dateEvent.objects.filter(a filter) events_all = dateEvent.objects.filter(another filter) context = { 'events_NMS': events_NMS, 'events_all': events_all, } return render(request, 'events/events_list.html', context) urls: path('events/<type>/', events_list_view, name='events_list'), How can I, depending on which type is in the URL, use events_NMS or events_all? I'd like do do something like this in my template: {% if "/events/nms/" in request.path %} {% for event in events_nms %} {% else %} {% for event in events_all %} {% endif %} ...rest of for loop... -
OSError in django
I'm trying to load my trained TensorFlow model in Django for some reason I'm not able to load it. I'm not sure how to load a TensorFlow model in django this is my code in the view.py file enter code here if request.method=='POST': enter code here file_path_enc=request.FILES["file_path"] enter code here new_file_path = file_path_enc enter code here fs=FileSystemStorage() enter code herename=fs.save(new_file_path.name,new_file_path)enter code here enter code here url=fs.url(name) enter code here DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) enter code here filepath=DIR+url enter code here IMG_SIZE = 250 enter code here img_array = cv2.imread(filepath) enter code here new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) enter code here reshape=new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3) enter code here print(reshape) enter code here path=DIR+"AI_detector/plant.model" # model name enter code here model = tf.keras.models.load_model(path) -
Sum If Another Column Is Distinct Djagno
I have a two tables in djagno class Item(models.model): name = models.TextField() type = models.ForeignKey(ItemType) quantity = models.IntegerField() and class ProductionRecord(models.model): item = models.ForeignKey(Item) done = models.IntegerField() What i am wanting to do is group the items by its type, sum the total quantity of items needed, and then sum the total quantity of items produced. I was fairly close but the issue i ran into was that when doing .annotate(Sum("quantity")) if an item has multiple production records, it will sum the quantity again, per record. Below is an example of my current data set after joining the tables and before grouping. +--------+--------+--------------+----------------------+ | ItemId | TypeId | ItemQuantity | ProductionRecordDone | +--------+--------+--------------+----------------------+ | 1257 | 7 | 4 | 1 | | 1257 | 7 | 4 | 4 | | 1259 | 7 | 4 | 4 | | 1261 | 7 | 4 | 0 | | 1263 | 7 | 4 | 4 | | 1265 | 7 | 4 | 0 | +--------+--------+--------------+----------------------+ When doing a normal sum on the quantity column, it returns 24 because it is summing for item id=1257 twice. But what i would like to return after grouping is: +--------+--------------+------+ | … -
How can I use a variable from views.py in a base template for multiple templates?
In a Django application I have several html pages with a similar structure. I am already using a base_site.html template for all my project but for these other pages I would like to use a second template to create tables. These tables could have more or less rows and columns than others. My idea was that the functions in views.py would send a list of the headers for any given page together with a dict of the data to populate the table, then in the html page I would iterate the list of headers to place the headers in the table then I would iterate the dict to populate the table with the data. How can I have a table-template.html to use a variable say headers from every function in views.py whenever they are called? Something like table-template.html <h1>TEST</h1> <table> <tr bgcolor="#ccc"> <th>{% for h in headers %} {{ h }} {% endfor %}</th> </tr> </table> Considering that every function in views.py would return its own headers list Then how can I use it in any of the html pages {% extends "admin/base_site.html" %} {% load static %} {% block content %} {% include "table-template.html" %} {% load static %} …