Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django:How to use "objects.all()" and "for" in async
I want to access the information of the model periodically using asyncio and threading. After fetching the model data with objects.all() in the async coroutine, an error occurs when running the for loop. You cannot call this from an async context - use a thread or sync_to_async. ---code--- [task.py] asyncio.run_coroutine_threadsafe(chat.handle(), loop.LOOP) [chat.py] async def handle(): while True: users = user.objects.all() for user in users: print(user.user_id) await asyncio.sleep(60) ---Details--- [Website/loop.py] import asyncio LOOP = None def run_loop(): global LOOP LOOP = asyncio.new_event_loop() LOOP.run_forever() [Website/__init__.py] from Monitoring import loop import threading import sys threading.Thread(target=loop.run_loop).start() When you access the test page, check() in task.py will work. [Monitoring/task.py]] import asyncio from Monitoring import chat from Website import loop def check(): asyncio.run_coroutine_threadsafe(chat.handle(), loop.LOOP) [chat.py] import asyncio from Monitoring.models import User async def handle(): while True: users = User.objects.all() for user in users: print(user.user_id) await asyncio.sleep(60) -
How to force URL with django rest framework?
I use an apache container which acts as a loadbalancer and redirects the flow to 2 apache wsgi. I use django-rest-framework on the 2 apaches. I have a problem to get the files. Indeed, the api returns me: { avatar: http://127.0.0.1:8000/media/avatars/2.jpg } Instead of http://127.0.0.1:8000/, I want the api to return https://api.myservice/ How to force the url ? -
hosting django with angular on digitalocean with nginx
I have a Django-Angular project which I want to deploy on DigitalOcean with Nginx and I am successful in running the whole setup, but I have some doubts that I want to clear before finally proceeding with the solution. This is what I've done so far Currently, I've gunicorn.sock and gunicorn.service files to set up gunicorn and passed this file in Nginx's location block location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } The Django project is running without any issue. For the angular project, I am using supervisor, inside /etc/supervisor/conf.d/my_angular_app.conf, I've set up configurations for the angular app [program:my_angular_app] command=ng serve directory=/path/to/angular/project/ user=www-data autostart=true autorestart=true stdout_logfile=/path/to/angular/project/logs/angular.log redirect_stderr=true this starts the angular project on localhost:4200 Now, I've added another location block inside my Nginx file to proxy pass the requests to angular location / { include proxy_params; # this will pass the requests to angular project proxy_pass http://localhost:4200; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } This whole setup … -
Django Form inputs show up as blank in Django Admin
So I'm creating software for an ice cream company, and I'd like to get the customer's information from the order entry html. But when I fill out the first name, last name, shipping address, etc, it shows up in Django admin as blank. Here's my code: forms.py from django import forms from orderentry.models import customerInfo, orderInfo class customerForm(forms.ModelForm): firstName = forms.CharField(max_length=30) lastName = forms.CharField(max_length=30) shippingAddress = forms.CharField(max_length=60) billingAddress = forms.CharField(max_length=60) class Meta: model = customerInfo fields = ('firstName','lastName','shippingAddress', 'billingAddress',) views.py from django.http import HttpResponse import orderentry from orderentry.forms import customerForm def getCustomerInfo(request): form = customerForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() orderentry.forms.firstName = form.cleaned_data['firstName'] orderentry.forms.lastName = form.cleaned_data['lastName'] orderentry.forms.shippingAddress = form.cleaned_data['shippingAddress'] orderentry.forms.billingAddress = form.cleaned_data['billingAddress'] return redirect('/orderentry') else: form=customerForm() return render(request, 'orderentry.html', {'form' : form}) orderentry.html <p> <!--Basic Customer Information--> <form method = "post"> {% csrf_token %} {{ form.as_p }} <button type = "submit">Place your order!</button> </form> </p> Here's what it looks like in Admin It is blank in the python shell as well. I'm new to Django. Any help is appreciated. Thanks. -
passing 2 different models from 2 different apps to another app table
app1/model class Deployment(models.Model): uid = models.CharField(max_length=255, blank=True) target = models.CharField(max_length=255) name = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) app2/model class Account(models.Model): name = models.CharField(max_length=255, blank=True) file_name = models.CharField(max_length=255, blank=True) national_id = models.CharField(max_length=255, default="") app3/views.py class IndexView(LoginRequiredMixin, ListView): model = AccountRecord template_name = "tableview/table_view.html" paginate_by = 25 def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['deployment'] = Deployment.objects.all() return context app3 html template <table class="table card-table table-vcenter text-nowrap"> <thead> <tr> <th>Deployment</th> <th>Account</th> <th>National ID</th> <th>Filename</th> </tr> </thead> <tbody> {% for account in object_list %} <tr> <td>DEPLOYMENT.NAME HERE!</td> <td>{{ account.name }}</td> <td>{{ account.national_id }}</td> <td>{{ account.file_name }}</td> </tr> {% endfor %} </tbody> </table> I am trying to pass data from these 2 model to another apps html template. with my current app3/views.py the table only show blank column even after i put {{ deployment.name }} can anyone point out how to do it correctly. -
Forbidden error from Postman request to Django
I have the url of login/ to login to my web But when i tried to do the same thing on Postman, it failed by returning me 403 Forbidden. How come? From the traceback, it says Forbidden (CSRF token missing or incorrect.): /login/ . But when i tried it in my web browser, I am able to access the web page and even login. Is there something I am doing wrong? Postman: Traceback: -
problems dropdown filter saving data in the database but return error
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I follow the Article (https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) but not working. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null = True ) dati_esercizio = models.ForeignKey( Esercizi, … -
How to add date-time arguments to django URL tag
I am trying to get this URL in my template. path('show_date/<int:year>/<int:month>/<int:date>/',show_date,name='show_date'), My template <a href="{%url 'diary:show_date'{{date|date:'Y'}} {{date|date:'m'}} {{date|date:'j'}} %}">{{date}}</a> returns this error Could not parse some characters: 'diary:show_date'|{{date||date:'Y'}} Please help me fix this issue -
How to automatically run all django-crontab jobs?
I'm trying to schedule some work in my Django app with django-crontab -library. I've set up a job in my settings.py like this: CRONJOBS = [ ('*/1 * * * *', 'test_app.cron.my_scheduled_job') ] This is my cronjob function: def my_scheduled_job(): print("HELLO FROM CRONJOB") I'm using docker-compose to run the app and first I tried starting it with command: bash -c "python manage.py crontab add && python manage.py runserver 0.0.0.0:8000". This didn't do anything, so next I tried this: bash -c "python manage.py crontab add && python manage.py crontab run 874ec9a239dc8b28ca961ecd41c5fa60 && python manage.py runserver 0.0.0.0:8000". This runs the job correctly but only once. So my question is, how do I run the job automatically every minute after starting the server? -
Configure django logger to perform write logs to seperate file every 24hrs
I am using basic logging functionality of django. I have configured logger as follow. What I need is , I want to create separate file every 24hrs in logs directory so that all the logs will be written in date wise log files. LOGGING ={ 'version':1, 'disable_existing_loggers': False, 'formatters':{ 'simpleRe': { 'format': '[{levelname}] [{asctime}] [{module}] {process:d} {thread:d} {message}', 'style': '{', } }, 'handlers':{ 'to_file':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/debug.log', 'formatter':'simpleRe', }, }, 'loggers':{ 'django':{ 'handlers':['to_file'], 'level':'DEBUG' } }, } I also want file names should be something like 'debug_26102021.log' etc. -
How to call API in Django views
I wanted to call the API in Django views and want to render into html template but I couldn't able to pass the API.I have tried different way views.py def homeview(request): userbase = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() return render(request, 'home.html', {'userbase':userbase, 'table_data':table_data}) return render(request, 'home.html', {'table_data':table_data}) -
How can I make my Django app scalable for uploading CSV File?
I want to upload a big csv file (40MB). Now for 1 MB file it is taking almost 1.5 minutes and I think it's not good enough for me. I want to make it so fast. I used bulk create instead of create function but what I notice is that both are taking same amount of time. How can I make it fast? Which procedure is good enough for uploading big csv? Can I give the to django Celery for uploading big csv. #this is my code def upload_file_view(request): start_time = datetime.now() form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm obj = Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i == 0: pass else: print(row) date = row[0] appl_open = row[1] appl_high = row[2] appl_low = row[3] appl_close = row[4] appl_volume = row[5] appl_adjusted = row[6] dn = row[7] mavg = row[8] up = row[9] direction = row[10] Data.objects.create( date = date, appl_open = appl_open, appl_high = appl_high, appl_low = appl_low, appl_close = appl_close, appl_volume = appl_volume, appl_adjusted = appl_adjusted, dn = dn, mavg = mavg, up = up, direction = direction ) obj.activated = True … -
How to create endpoint admin/advisor in a Djangi API
Someone please help me in understanding how to create an endpoint admin/advisor in Django API. Since /admin/ is in Django is inbuilt endpoint how can I add advisor to it. See the photo please. -
Django javascript redirect using id
We are trying to redirect to our checkout.html page which requires an id in its arguments to get to, but we are trying to get to it using Javascript. In out store.html page {% for item in product %} <div class="col-md-3"> <div class="card" style="width: 90%; margin: 5px 5px;"> <a href="Product/{{item.id}}"><img src="{{item.image.url}}" class="card-img-top"></a> <div class="cart-footer text-center"> <button onclick="redirect()">Order</button> </div> </div> </div> {% endfor %} <script> function redirect() { var url = "{% url 'Checkout' %}"; var id = $(this).item('id'); window.location.href = url + "/" + id; } </script> We know we can just use a regular button like <button onclick="window.location.href='Checkout/{{item.id}}'">Order</button> Which is how we had it before, but we're trying to get it through Javascript for future use How do you get a specific objects' id in javascript? urls.py path('', views.Store, name= "Store"), path('Checkout/<id>', views.createlocation, name="Checkout"), path('Product/<id>', views.product_details, name="Product") -
Django Postgresql Error in Production (quiz.models.Question.DoesNotExist:)
I am creating a quiz application using a guide. My application works perfectly fine in development with both sqlite3 and postgresql databases. But when pushed to production, I am faced with errors using a postgresql database. So I tried using my development sqlite3 database in production to test things out. My sqlite3 database works fine in production, but postgresql does not work in production. Initially, I thought the error is on the views level, but now I am seeing the error coming from the postgresql. Could be errors in my views or models schema. I really can't tell. The corresponding error I get when using a postgresql database in production using a linux server with gunicorn and nginx is here below, and the whole models design and views are here below too. Thanks, I appreciate your time in giving me a suitable answer to my question. models.py from django.db import models import random from account.models import Profile from django.urls import reverse import datetime from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField class PublishedBookManager(models.Manager): def get_queryset(self): return super(PublishedBookManager, self).get_queryset().filter(publish_book=True) class Book(models.Model): name = models.CharField(max_length=120) description = models.TextField() created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL) number_of_questions = models.IntegerField() number_of_sections = models.IntegerField() time = … -
Django How to update some specific fields data after input from another model using signals
I have some problem with django signals. I wanna update PermohonanWP status model fields from 'PROSES' to 'SUCCESS' after I Input data to PenelitiPemindahanWP. (Suppose i have already input data to PermohonanWP model with status = 'PROSES') here my model.py class PermohonanWP(models.Model): npwp = models.CharField(max_length=15, null=False) nama = models.CharField(max_length=100, null=False) status = models.CharField(max_length=20, null=True) class PenelitiPemindahanWP(models.Model): permohonan_pemindahan = models.ForeignKey(PermohonanWP, on_delete=models.CASCADE) nomor_lhp = models.IntegerField(null=True) nomor_st = models.CharField(max_length=50, null=True) here my signals i input it in model.py @receiver(post_save, sender=PenelitiPemindahanWP, dispatch_uid="update_permohonan_id") def update_permohonan(sender, instance, **kwargs): pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan) pemohon.status = "SUCCESS" pemohon.save() I wanna update the status field from PermohonanWP but whenever i submit saved button, it not saved and not update the fields. -
Django axes resets cool off the moment another failed login occurs
Currently, django axes will reset the cool off timer to the latest time a failed login attempt happens eg. after 3 login failed login attempts axes will lock out the user account for 15 minutes until 1015am(unlock at 1030am). If i attempt a 4th time at 1020am it will extend the lockout to 1035am. Is there anyway to modify axes so that it will not reset the cool off time on login attempt failure? -
Django redirect using an object id?
The main issue I'm having is using the {% url 'Name' %} feature In my html file "productview.html" {% extends "droneApp/base.html" %} {% block content %} <div> {{ objects.name }}<br> </div> <button onclick="window.location.href='{% url 'Checkout/{{objects.id}}' %}'"> {% endblock %} The productview.html page's url is http://127.0.0.1:8000/Store/Product/1 Where 1 is the product id I'm trying to redirect to the checkout page using a button. But I don't understand how to redirect to my html Checkout.html In a previous html file we used href='Checkout/{{item.id}}' but if we use that in this file it just causes the urls to stack into http://127.0.0.1:8000/Store/Product/Checkout/1 instead of http://127.0.0.1:8000/Store/Checkout/1 How do I properly redirect to the right html file? urls.py file from django.urls import path from .import views urlpatterns = [ path('', views.Store, name= "Store"), path('Checkout/<id>', views.createlocation, name="Checkout"), path('Product/<id>', views.product_details, name="Product") ] Which is imported from another urls.py file path('Store/', include('storeApp.urls')), -
How do I configure Django's auth user model to have a UUID (Postgres DB)
I'm using Python 3.9 and Django 3.2. Here is my folder structure + cbapp - settings.py + models - __init__.py - custom_user.py - manage.py Here's what my customer_user.py file looks like $ cat models/custom_user.py import uuid from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Additionally, I have configured this in my settings.py file AUTH_USER_MODEL = 'models.CustomUser' However, when I run "python manage.py makemigrations", I get this error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'models.CustomUser' that has not been installed I have no idea what this means. I have this in my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cbapp', ] ... AUTH_USER_MODEL = 'models.CustomUser' -
Django Models, Custom Model Managers and Foreign Key -- don't play well together
I will simplify the problem as much as I can. I have Three model classes: # abstract base class MyAbstractModel(models.Model) # derived model classes Person(MyAbstractModel) LogoImage(MyAbstractModel) Each Person has: `image = ForeignKey(LogoImage, db_index=True, related_name="person", null=True, on_delete=models.PROTECT)` The MyAbstractModel defines a few model managers: objects = CustomModelManager() objects_all_states = models.Manager() as well as a state field, that can be either active or inactive CustomModelManager is defined as something that'll bring only records that have state == 'active': class CustomModelManager(models.Manager): def get_queryset(self): return super().get_query().filter(self.model, using=self._db).filter(state='active') In my database I have two objects in two tables: Person ID 1 state = 'active' Image ID 1 state = 'inactive' ------ NOW for the issue ---------------- # CORRECT: gives me the person object person = Person.objects.get(id=1) # INCORRECT: I try to get the image id which which works. I get the image object. image = photo.image PROBLEM: I have queried for the person object under objcets manager which is supposed to bring only those items with active status. the image in this person's foreign key is NOT active -- why am I getting it? It's not using the objects model manger to get it. WORKAROND ATTEMPT: added base_manager_name = "objects" to the MyAbstractModel class meta. … -
How to change model attribute in database by using ajax in django?
I have created a real time messages in my project by using AJAX. I refer from this tutorial, https://youtu.be/IpAk1Eu52GU Below is the code for the function. view_questions.html {%block content%} <h2>{{meeting_id}} - Panelist Review Question</h2> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/panelist/getMessages/{{meeting_id}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.questions) { var temp="<div class='container darker'><b>"+response.questions[key].shareholder_id + "</b>"+"<br><b>"+response.questions[key].sharehold_name + "</b><p>" + response.questions[key].question_id + "</p>"+ "<p>"+response.questions[key].question + "</p><span class='time-left'>"+response.questions[key].date_created+ "</span><input type='submit' name='filter_btn' class='btn btn-primary' value='Filtered' /></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') } }); },1000); }) </script> {% endblock %} </body> views.py def getMessages(request, meeting_id): meeting = Meetings.objects.get(meeting_id=meeting_id) questions = Questions.objects.filter(meetings_id=meeting) shareholder = [] for i in questions: shareholder.append( { "question_id": i.question_id, "question" : i.question, "date_created": i.date_created, "shareholder_id": i.shareholders.shareholder_mykad, "sharehold_name": i.shareholders.shareholder_name, } ) # print(list(shareholder)) return JsonResponse({"questions":list(shareholder)}) def questionsView(request, meeting_id): context = {'meeting_id':meeting_id} return render(request, 'view_question.html', context) models.py class Questions(models.Model): question_id = models.AutoField(primary_key=True) question = models.CharField(max_length=400, null=True) is_filtered = models.BooleanField(default=False) meetings = models.ForeignKey(Meetings, on_delete=CASCADE, related_name='questionMeeting') shareholders = models.ForeignKey(AuthenticationShareholders, on_delete=CASCADE, related_name='questionShareholder') date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return str(self.meetings) The real time chat is working but the problem is that I want to create a button that allow user to filter the real time messages by … -
Django ModelForm is not showing any data
I'm new to Django and need some help here, I want to make a page where sellers can sell your items with coupons code and customers can get these coupons. A little mix with JS and I hid the coupon, you have to "purchase" the item, so you can have it. I have 3 tables, "Produto" (Product), "Pedido" (Order) and "Cliente" (Client) and when the custumer try to "purchase" the item, it's only appearing his/her name ! Can someone help me please ? My view.py @login_required(login_url='login') def liberarForm(request, pk): produto = Produto.objects.get(id=pk) #The Product IDs are working in admin panel cliente = Cliente.objects.get(user=request.user) if request.method == 'POST': form_produto = LiberaProduto(request.POST) form_cliente = LiberaPedido(request.POST) if form_cliente.is_valid() and form_produto.is_valid(): form_cliente.save() form_produto.save() return redirect('/') else: form_produto = LiberaProduto(initial={'produto': produto}) #not working form_cliente = LiberaPedido(initial={'cliente': cliente}) context = {'form_cliente': form_cliente, 'form_produto': form_produto} return render(request, "liberar.html", context) My form.py class LiberaPedido(ModelForm): class Meta: model = Pedido fields = '__all__' exclude = ['produto', 'status', 'data_criado'] class LiberaProduto(ModelForm): class Meta: model = Produto fields = ['nome', 'lojista', 'status', 'estoque'] My models.py class Cliente(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) chapa = models.DecimalField(null=True, max_digits=20, decimal_places=0) cpf = models.DecimalField(null=True, max_digits=20, decimal_places=0) telefone = models.CharField(max_length=15, null=True) email = models.CharField(max_length=200, null=True) data_criado = … -
Django DB2 with Multiple Schemas
I would like to know whether it is possible for the Python(3.8.10)-Django(3.2) to connect to the DB2 with multiple schemas. Currently, I am using the settings similar to the example in the GitHub DATABASES = { 'default': { 'ENGINE' : 'ibm_db_django', 'NAME' : 'mydb', 'USER' : 'db2inst1', 'PASSWORD' : 'ibmdb2', 'HOST' : 'localhost', 'PORT' : '50000', 'PCONNECT' : True, #Optional property, default is false }, 'MYSCHEMA': { 'ENGINE' : 'ibm_db_django', 'NAME' : 'mydb', 'USER' : 'db2inst1', 'PASSWORD' : 'ibmdb2', 'HOST' : 'localhost', 'PORT' : '50000', ‘SCHEMA’ : ‘MYSCEHMA’, # no error for adding the ‘SCHEMA’ parameter (or not) until running 'PCONNECT' : True, #Optional property, default is false } However, it is using db2inst1 as the default schema. Is it possible to use other schema? For instance, I am using MYSCHEMA for the application. For the above settings, I am not sure what I could fill the schema name in the DATABASE variables. I have added in corresponding coding: SomeModel.objects.using(‘MYSCHEMA’).all() #The default is to use the “default” database connection. Once it is running in the Django, it will show db2inst1.tabname is an undefined name. (Table willing to use: MYSCHEMA.tabname) -
Easy 'for loop' for datetime field not working in Django(google chart)
I'm trying to use google chart in my Django project, the google chart required a format like ['label1', 'label2', 'label3', new Date(Y, m, d), new Date(Y, m, d), null, 100, null], it's like a list, so I'm trying to keep things simple first, I only replaced the date and leave other fields as default. I have a model in Django that has a start_date field and a due date field, so the only thing I'm doing not is to put them into the 2 'new Date' and for loop, somehow the codes were not working, I would really appreciate it if someone can have a look, cheers. models.py ''' start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) ''' views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.aggregate( to_do_count=Count('id', filter=Q(status='to_do')), in_progress_count=Count('id', filter=Q(status='in_progress')), done_count=Count('id', filter=Q(status='done')) ) todos = project.todo_set.order_by('-project_code') return render(request, 'todo_lists/progress.html', {"counts_data":counts_data,'team':team,'todos':todos}) ''' HTML ''' function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Task ID'); data.addColumn('string', 'Task Name'); data.addColumn('string', 'Resource'); data.addColumn('date', 'Start Date'); data.addColumn('date', 'End Date'); data.addColumn('number', 'Duration'); data.addColumn('number', 'Percent Complete'); data.addColumn('string', 'Dependencies'); data.addRows([ {% for todo in todos %} ['Introduction', 'Introduction Project', 'Introduction', new Date({{ todo.start_date|date:"Y,m,d"}}), new Date({{ todo.due_date|date:"Y,m,d"}}), null, 50, null], ]); {% endfor %} var options = … -
Is there a way to get all the exercise_uuids from array in JSONField in Django?
I have been looking and exploring similar questions but couldn't find anything. Is this even possible? I am using Django==3.2 and Postgres 12 class MyModel(models.Model): data = models.JSONField() Format of data [ { "exercises": [ { "exercise_id": 1 }, { "exercise_id": 2 }, { "exercise_id": 3 } ] }, { "exercises": [ { "exercise_id": 4 }, { "exercise_id": 5 }, { "exercise_id": 6 } ] } ] Desired Output [1,2,3,4,5,6]