Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Securing Settings Using django-environ
I'm following the documentation and a tutorial to create environment variables to safeguard my keys. They use a DATABASE_URL that they seem to stitch manually in the .env file. For example the documentation uses psql://urser:un-githubbedpassword@127.0.0.1:8458/database. My database might change eventually and I only want to change what I need. When I try to indicate anything other than a DATABASE_URL it says there are is no 'default' for database. I'm assuming that 'default' is a django-environ thing. How can I save my environment variables in this format: .env DEBUG=True SECRET_KEY='AAAAA' ENGINE=BBBBBB NAME=CCCCC DB_USER=DDDDD PASSWORD=EEEEE HOST=FFF.com PORT=5432 settings.py ENGINE = env('ENGINE') NAME = env('NAME') DB_USER = env('DB_USER') PASSWORD = env('PASSWORD') HOST = env('HOST') PORT = env('PORT') DATABASE_URL=ENGINE+'://'+DB_USER+':'+PASSWORD+'@'+HOST+':'+PORT+'/'+NAME DATABASES = { 'default': DATABASE_URL} -
Unexpected behaviour by elasticsearch "query_string" for different fields having same mapping
I am using Elasticsearch version 6.3.1 for a django project. I am using regular expressions supported by query_string filter but two of my fields in same index have same mapping although while searching with spaces, one key is returning values and other is not. As both of my fields have strings stored in them so I have tried with both keyword and full-text search with query_string. Mappings - Field 1 - {u'alias': {u'full_name': u'field1', u'mapping': {u'field1': {u'fields': {u'keyword': {u'ignore_above': 256, u'type': u'keyword'}}, u'type': u'text'}}}, Field 2 - u'extra_fields_values': {u'full_name': u'field2', u'mapping': {u'field2': {u'fields': {u'keyword': {u'ignore_above': 256, u'type': u'keyword'}}, u'type': u'text'}}}}}}} Query For field2 - {'_source': 'field1', 'from': 0, 'query': {'bool': { 'must': [ {'term': {'field3.keyword':'Test1'}}, {'term': {'field4': 1741}}, {'query_string': { 'fields': ['field2.keyword'], 'query': '/.*test abc.*/', } } ], }}]}}, 'size': 50} For field1 - {'_source': 'field1', 'from': 0, 'query': {'bool': { 'must': [ {'term': {'field3.keyword':'Test1'}}, {'term': {'field4': 1741}}, {'query_string': { 'fields': ['field1.keyword'], 'query': '/.*test abc.*/', } } ], }}]}}, 'size': 50} Output for field1 - {u'hits': [{u'_id': u'1', u'_index': u'test', u'_score': 8.594198, u'_source': {u'alias': u'test abc'}, u'_type': u'test'}], u'max_score': 8.594198, u'total': 1} Output for field2 - {u'hits': [], u'max_score': None, u'total': 0} What could be possible reason for this behaviour? -
Filtering data in HTML datatables and Django
I added a Datatable to a page of my Django project. This tables shows some data retrieved from a Django Rest Framework endpoint. Here is how a sample of the data retrieved looks like: { "item": "Someitem", "Price": 120, "Status": "Free" }, { "item": "SecondItem, "Price": 90, "Status": "Taken" }, I want to filter these records so that only the ones with the Status set to Free are shown in the table, but i don't really know how to do that from Jquery. Here is the code i use to load the table: $(document).ready(function() { var table = $('#mydb').DataTable({ "serverSide": true, "ajax": "/myapi/?format=datatables", "columns": [ {data: "item", {data: "Price"}, ] }); setInterval( function () { table.ajax.reload(); }, 10000 ); }); I tried to add an if statement to check data.Pair inside the Ajax call, but it gave me an undefined. Is there any other way to do this? Any advice is appreciated -
How to post to a modelform with two foreign keys?
I am trying to make a ModelForm from witch I can insert data to my model, but the data never gets saved. I believe the problem occur because of my two foreign keys. When i insert data from the admin page, directly to the models it works, so the models themselves should work. However when i use my modelform the data never gets saved. I do however get the desired redirect with a POST /ac/ HTTP/1.1" 200 respons which means my form is valid - right? So no errors, the data just dosen't get saved. I hope one of you are able to help me with this strange problem. My models look like this: class KnittingNeedleType(models.Model): length = models.CharField(max_length=25) def __str__(self): return self.length class KnittingNeedleBrand(models.Model): brand_name = models.CharField(max_length=30) def __str__(self): return self.brand_name class KnittingNeedle(models.Model): width = models.FloatField() type = models.ForeignKey(KnittingNeedleType, on_delete=models.CASCADE) interchangeable = models.BooleanField() brand = models.ForeignKey(KnittingNeedleBrand, on_delete=models.CASCADE) class Meta: ordering = ('width', 'type',) My form: class KnittingNeedleForm(ModelForm): class Meta: model = KnittingNeedle fields = ['width', 'type', 'interchangeable', 'brand'] My view: @csrf_protect def register_needle(request): if request.method == 'POST': form = KnittingNeedleForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('ac:index')) form = KnittingNeedleForm() return render(request, 'ac/registerNeedle.html', {'form': form}) And my template: {% extends 'base.html' … -
How to make API calls in real time with Django?
I'm new in Django world, I'm developing a web application and I need to get data from an external API every time its data changes, I've been looking for different ways to do it, and I found WebSockets can help me, so now I want to try doing it with channels, but still do not understand how to do it, any help? -
Termina linea grapico araña realizada en plotly.graph_objects
Cuando genero mi gráfico no me termina la linea , sin embargo e intentado de muchas formas , pero nada me a funcionada. lo que esta en r , son unas variables que tengo declaradas con valores ya definidos fig = go.Figure() fig.add_trace(go.Scatterpolar( name = "Ideal", r=[ ideal_Funciones_Responsabilidades, ideal_etapas_propias, ideal_Aspectos_Legales, ideal_Gestion_Ambiental, ideal_Gestion_de_Seguridad, ideal_manejo_Informacion, hallado_Tecnicos, ideal_Humanos , ideal_transversales], theta=categories, #connectgaps=True, #line_color = 'darkviolet' type= 'scatterpolar', mode = 'lines', )) fig.add_trace(go.Scatterpolar( name = "Hallado", r=[ hallado_Funciones_Responsabilidades, hallado_etapas_propias, hallado_Aspectos_Legales, hallado_Gestion_Ambiental, hallado_Gestion_de_Seguridad, hallado_manejo_Informacion, hallado_Tecnicos, hallado_Humanos, hallado_transversales], theta=categories, #mode = "markers", type= 'scatterpolar', mode = 'lines', #line_color = 'peru' )) fig.update_layout( polar=dict( radialaxis=dict( #visible=True, range=[0, maximo_valor + 1] ) ), #line_close=True, # showlegend=False ) enter image description here estare atento a su ayuda con este tema. -
AttributeError: 'Product' object has no attribute 'filter'
I'm trying to access the link 'http://127.0.0.1:8000/products/2' in which I'm using a generic view(DetailsView) and in that view I want to use my custom model manager. But I'm getting the error which states AttributeError: 'Product' object has no attribute 'filter'. I'm using python version3.8 and django version 2.2.6 # ModelManager #----------------------------------------------- class ProductManager(models.Manager): def get_by_id(self,id): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() return None # View #----------------------------------------------- class ProductDetailView(DetailView): # queryset = Product.objects.all( ) def get_queryset(self, *args, **kwargs): request = self.request pk = self.kwargs.get("pk") instance = Product.objects.get_by_id(pk) if instance is None: raise Http404("Product Couldn't be found") return instance # Error Internal Server Error: /products/2 Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/detail.py", line 106, in get self.object = self.get_object() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/detail.py", line 36, in get_object queryset = queryset.filter(pk=pk) AttributeError: 'Product' object has no attribute 'filter' [22/Oct/2019 18:51:56] "GET /products/2 HTTP/1.1" 500 75133 -
How to iterate over nested lists in django templates
I am trying to iterate over nested lists in django templates. I am getting this error "Unclosed tag on line 213: 'for'. Looking for one of: empty, endfor.". I made sure that both loops are closed. Is it possible at all to do it? lists = [ [1,2,3,4], [2,3,2,5], [3,2,3,4,5,2] ] def xview(request): return render(request, 'xxxx.html', {'lists':lists}) #django template {% for i in lists %} {% for j in i%} ... {% endfor %} {% endfor %} -
For Loop to Find Matching Values and Total in Python
I have a Django project where my Manifests model consist of item codes and quantity. I want to loop through the model and find the total of quantity for each item code. So I have the following in my view: manifest = Manifests.objects.all() How could I use a for loop or something to total the quantity for each item code. Or more clearly, if item code 10 is there 3 times with quantities = 1, 2, and 3. Total should be 6 for item code 10, and if item code 20 is there twice with quantities = 2 and 5 total should be 7. Here is the model for reference: models.py class Manifests(models.Model): quantity = models.IntegerField() item_code = models.ForeignKey(Products, default=None, blank=True, null=True) -
Selectively setting AWS S3 bucket's Metadata to "Content-Disposition:attachment" in order to make images downloadable in browsers
In a web app of mine (developed via Django/Python framework), I serve images to users via an AWS S3 bucket. I now want to provide a "download image" button next to each image served on the website. I understand the best way to do that is to change the Metadata of the Properties of the S3 bucket to Content-Disposition:attachment (guide here: https://docs.easydigitaldownloads.com/article/1172-how-do-i-force-files-to-download-in-amazon-s3) However, if I do that, all images would default to the download behavior on my web app. I only want to impart this functionality via the download button. What's my best course of action given the circumstances? I.e. how do I configure the S3 bucket to respond in a way that enables the download button to actually work (while the rest of the web app's functionality remains the same). I can't seem to wrap my head around this - perhaps some web developers with expertise greater than mine can shed light on how they would have done this. Btw, I know about the download attribute of the <a> tag. It works nicely enough, but only if the domain/subdomain etc of the downloadable resource is the same. In my case, I'm using an S3 bucket to host my files … -
Slow EC2 Performance with Python Threading?
I'm using Python threading in a REST endpoint, so that the endpoint can launch a thread, and then immediately return a 200 OK to the client while the thread runs. (The client then polls server state to track progress of the thread). The code runs in 7 seconds on my local dev system, but takes 6 minutes on an AWS EC2 m5.large. Here's what the code looks like: import threading [.....] # USES THREADING # https://stackoverflow.com/a/1239108/364966 thr = threading.Thread(target=score, args=(myArgs1, myArgs2), kwargs={}) thr.start() # Will run "foo" thr.is_alive() # Will return whether function is running currently data = {'now creating test scores'} return Response(data, status=status.HTTP_200_OK) I turned off threading to test if that was the cause of the slowdown, like this: # USES THREADING # https://stackoverflow.com/a/1239108/364966 # thr = threading.Thread(target=score, args=(myArgs1, myArgs2), kwargs={}) # thr.start() # Will run "foo" # thr.is_alive() # Will return whether function is running currently # FOR DEBUGGING - SKIP THREADING TO SEE IF THAT'S WHAT'S SLOWING THINGS DOWN ON EC2 score(myArgs1, myArgs2) data = {'now creating test scores'} return Response(data, status=status.HTTP_200_OK) ...and it ran in 5 seconds on EC2. This proves that something about how I'm handling threads on EC2 is the cause of the … -
How do I filter a django queryset based on pairs of fields from another queryset?
I have a table that handles ordering of tasks, and each user can have a different order for the same task. This might be difficult to explain, so I have a discrete example at the bottom of this post. Object representing the order of tasks for each user: class TaskOrdering(models.Model): task = models.ForeignKey(Task, related_name='ordering') user = models.ForeignKey(User, related_name='task_ordering') order = models.PositiveIntegerField(null=True) When I delete a task, I need to decrement the order of all tasks in each user's view that have an order greater than the deleted task's order. However, this deleted task's order is different for each user since they have their own view of the task list. Right now I am doing: # Instance is a Task object def perform_destroy(self, instance): # deleted_task_ordering is a set of TaskOrdering objects # representing the order of the task in EACH user's view deleted_task_ordering = instance.ordering.all() # deleted_task_ordering is a set of TaskOrdering objects # representing the order of OTHER tasks in EACH user's view other_tasks_ordering = TaskOrdering.objects.exclude(task=instance) for o in deleted_task_ordering: need_decrement = other_tasks_ordering.filter(user=o.user, order__gt=o.order) need_decrement.update(order=F('order') - 1) This works, but there must be a more efficient way by using django queries instead of a for loop. The reason I … -
update django json array with one that is populated without droping other fields
Hello I am developing a django web app where I am sending data from frant end and I would like to up make sure that this form can be posted without errors in Django rest So my django rest expect some data like this dat = { 'age':"", 'gender':"", 'description':"", ...others } my front however is sending data that is incomplete coz I expect to allow user fill other details later raw_dat = { 'age':"20", 'gender':"male", } I was was wondering if i can append the data in the second array to the first one keeping all those other fields that the second array does not have, I will really appreciate any help I can get -
Authentiaction error for "Single sign on" in Django application
I am trying to add SSO to my Django application. When I do token= token.get_token('user','Password'), it calls get_token method which will call HTTPBasicAuth with my credentials, from requests.post. I don't understand where my password is getting changed(trimmed or some special character, might be '/0' getting added), because of which I am not able to validate my request. I can directly do curl with my credentials to the authentication site and can see curl request getting response, but if I change anything in my password I will get the same error what I am getting from SSO integrated in my application. How can I figure out, where my password getting messed up. -
How to create a "check-in/check-out" system with timestamps?
I have an app that sort of works in a check-in/check-out manner. People just enter their ID, area, and click check in and it sends the timestamp to the db with their info. There is also a "check-out" button that currently does nothing. It's supposed to work so that, once the person fills the form and submits, it'll will either do one of these things: Find the previous check in entry based on the ID and Area entered and update the check out from NULL to timestamp. If the person forgot to previously check in, then it will create a new record with just the check out timestamp and the ID/Area. I thought that trying to find the user by matching both ID AND Area would be better since the same person can check in/out of different areas several times a day so matching only by ID could generate the problem of the program updating the wrong field at one point. models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class StationNumber(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, … -
Django throws "[12728] ERROR: CREATE DATABASE cannot run inside a transaction block" when tried to create postgresql database
I'm running django 2.1.4 on python 3.6 with latest Postgresql. Problem is, when I'm trying to create database from django code, it returning "current transaction is aborted, commands ignored until end of transaction block". Here is my code -> database create code But it creates the database from django shell -> shell image Here's the postgres log error -> [12728] ERROR: CREATE DATABASE cannot run inside a transaction block Here's the terminal errors generated -> Traceback (most recent call last): File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\promise\promise.py", line 487, in _resolve_from_executo r executor(resolve, reject) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\promise\promise.py", line 754, in executor return resolve(f(*args, **kwargs)) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\graphql\execution\middleware.py", line 75, in make_it_p romise return next(*args, **kwargs) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\contextlib.py", line 52, in inner return func(*args, **kwds) File "D:\xERP\graphqltest\users\schema.py", line 68, in mutate db.save() File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 869, in _do_insert using=using, raw=raw) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_metho d return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1136, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1289, in execut e_sql cursor.execute(sql, params) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 100, in … -
Setup nginx-ingress to match two paths to the same serviceName and servicePort
What I'm tryng to do Traffic to / needs to go to the FE client running on 3000. Traffic to /api needs to go to the BE server. apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress-service annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/add-base-url: "true" nginx.ingress.kubernetes.io/rewrite-target: /$1 spec: rules: - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api?/(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 The problem # urls.py urlpatterns = [ path('auth/', include('authentication.urls')), path('admin/', admin.site.urls), ] Fetches to /api/auth work fine. Fetches to /api/admin do not. Django removes the /api from the URL making it just /admin which doesn't exist. This seems to be the default behavior of Django. As far as I can tell there is no way to override it. What does work - path: /?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 Navigating to /admin works fine. However, this removes the ability for traffic to be routed to the client. Somehow, I need to prevent Django from stripping off the prefix. Or maybe there is a way to handle this type of routing from nginx-ingress. What doesn't work Any variation of the following: - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api?/(.*) backend: serviceName: server-cluster-ip-service … -
Unable to access webcam on other devices connected to local server of Django app
I am creating a camera web app using Django. My aim is to access the webcam or camera of the user's device and display it on screen. I hosted the web app locally. I am able to access the webcam on main device but I am unable to access it on other devices that are connected to it. I am using javascript to access the webcam. <script> var video = document.getElementById('videoElement'); function webcam(){ if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function(stream) { video.srcObject = stream; }); }} </script> How to solve this problem? -
RuntimeError("populate() isn't reentrant") on elastic beanstalk
I'm running django on Elastic Beanstalk and after pushing a new version of the app I'm getting a 500 internal server error. The logs show this: apps.populate(settings.INSTALLED_APPS) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant mod_wsgi (pid=21994): Target WSGI script '/opt/python/current/app/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=21994): Exception occurred processing WSGI script '/opt/python/current/app/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup Any advice on debugging this? My attempts to understand it/google it so far have been unsuccessful. -
How to upload csv to Django display csv data in table
How to upload CSV data into given field, but not save the data, save the only file into media/folder. I would like to display the data in table format and push the data out to do something via python. Here is the flow: USER(upload .csv) >> save the file >> read the file and display in table >> (no need to save the data) >> Button to run python script to take csv data and to other server. Do I need Model define each field, if I am not saving the data? How to save the file into the directory? In the form, should it form.Form() Thanks for the help -
django: Can not find the Data table row of the Extra field on many-to-many relationships?
Hello i am trying to understand Django Data Models and it´s possibilities. After using one-to-one and m2m i am now trying to understand the m2m extra fields. So i followed the Example of the Django Doc and populated the models with some Data. models.py class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) So far everything is fine, but as i looked into the model tables, via pgAdmin 4 ( i am using PostgreSQL), i could not find any members column in the Group model. So i made a little visual of my model and some screenshots of pgAdmin, for better understanding. As you can see Group has only a id and name column. Question my question: Is this m2m members relation of Group, only some kind of "virtual" created relation via the Membership.person.fk and Membership.group.fk? Meaning there is no field which will be populated? I try to imagine that it works like a recursive, instance query? -
How to Implement Non-endpoint API Functions?
This is a pretty high level question but I have been unable to find anything that explains it elsewhere: I have a django class-based view with endpoints (GET, POST) but I have another method that's not an endpoint but I would like to include as it's used in the GET/POST methods. What would be the best practice for implementing this? For example: class users(APIView): def get(self, request): # get method helperFunction() def post(self, request): # post method helperFunction() def helperFunction(): # not an endpoint Would this be the right way to do something like this? Should helperFunction() be standalone function outside of a class? Or should non-endpoint methods be in a separate class? Apologies for the lack of specificity. -
DRF: Add a new endpoint to a detail view
In my Django and DRF app, I already have an endpoint that looks something like this: /myapp/countries/<country_id>/ and it shows the details pertaining to a specific country. Now I want to add a new endpoint that would look like this: /myapp/countries/<country_id/cities/. Note that in my particular case, there is no database relationship between countries and cities. The list of cities that belong to the specified country would be calculated by parsing a file. This is how my urls.py looks like: router = DefaultRouter() router.register(r'countries', views.CountriesViewSet) How could I add this new /myapp/countries/<country_id/cities/ endpoint? Remember that the cities associated to a country would be "calculated" in the viewset, there is no DB relation between those two entities. -
Assigning list as value to many to many filed in my model django
I have a table with many to many to field, Now i have a variable with nested list(list with multiple list ex. [[],[],[]] like this) i want to put that variable as values to my many to many field by obj.fieldname.set() or .add() method . But it is showing error unhashable list type . Anyone can help?? Thanks in advance -
I am working with Django inclusion_tag and Wagtail Site Setting
I am new in Django and Wagtail and I am facing little problem. I want to assess Wagtail Site Setting using Django inclusion_tag. in short, {{ settings.app_1.SimpleHtmlSettings.heading }} and {{ settings.app_1.SimpleHtmlSettings.body }} in index.html is not printing any thing. I tried total two solutions but non of them is working app_1_extras.py (simple_html = SimpleHtmlSettings.for_site(context['request'].site)) app_1_extras.py (simple_html = SimpleHtmlSettings.objects.first) models.py from django.db import models from wagtail.contrib.settings.models import BaseSetting, register_setting # Create your models here. @register_setting class SimpleHtmlSettings(BaseSetting): heading = models.CharField( max_length=255, help_text='Enter heading') body = models.CharField( max_length=255, help_text='Enter body content') views.py from django.shortcuts import render from app_1.models import SimpleHtmlSettings from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'app_1/test.html') app_1_extras.py from django import template from app_1.models import SimpleHtmlSettings register = template.Library() @register.inclusion_tag('app_1/index.html', takes_context=True) def show_results(context): # simple_html = SimpleHtmlSettings.for_site(context['request'].site) simple_html = SimpleHtmlSettings.objects.first return {'simple_html': simple_html} index.py {% load wagtailsettings_tags %} <h1>{{ settings.app_1.SimpleHtmlSettings.heading }}</h1> <p>{{ settings.app_1.SimpleHtmlSettings.body }}</p> <p>Check</p> test.py {% load wagtailsettings_tags %} {% load app_1_extras %} {% show_results %} test.html only printing "Check" Thanks!!!