Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
regex for telephone number in validation form
in a django template with the html pattern tag and boostrap for form validation with this regex it validates a sequence of numbers that can be separated by a dash "^[+-]?\d(?:-?\d)+$" example: 12-65-25-75-84 or 12-255-0214 the javascript : (() => { 'use strict' const forms = document.querySelectorAll('.needs-validation') Array.from(forms).forEach(form => { form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) }) })() and the html <input type="text" class="form-control" id="exampleFormControlInput1" name="tel" id="tel" placeholder="Tel" pattern="^[+-]?\d(?:-?\d)+$" required> </div> I would like to know how to modify it to have the possibility of putting spaces between the numbers (in addition to the dashes) example: 12 57 125-98-457 and limit the total number of digits to 15 (excluding spaces and dashes) for example a string like this: 12-28-35-74-12 or 12 28 35 74 12 or 123-478 25 12 124-15 thank you -
Django MigrationSchemaMissing exception on Azure SQL using service principal auth
I'm actually working on a client's project we are connecting Azure SQL DB via service principal authentication. Our client has given us access to Azure SQL and they have given us the credential for it. so to connect to Azure SQL we're using Microsoft's mssql-django package. so this is what the DB configurations look like. DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': <db_name>, 'USER': <db_user>, 'PASSWORD': <db_password>, 'HOST': "<url>.database.windows.net", 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'connection_timeout':60, 'connection_retries':3, "extra_params": "Authentication=ActiveDirectoryServicePrincipal", }, } so when I'm trying to run the migrate command I'm getting the below error raise MigrationSchemaMissing( django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The specified schema name "<db_user>@<azure_tenant_id>" either does not exist or you do not have permission to use it. (2760) (SQLExecDirectW)')) by looking at the error we can definitely say that either the schema is not created or the DB user that they have given us does not have permission to create the tables in the DB. can anyone please suggest what could be going wrong, this is definitely not an issue from the Django or from the django-mssql package but an issue … -
How to organize multithreading
I have code, comes up WARNING: QApplication was not created in the main() thread, but the code runs, but 1 time, when it starts to run 2 times the site dies, how can I arrange multi-threading that it would not crash? from .forms import UserForm from bs4 import BeautifulSoup from django import forms from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage import sys import time import re import requests regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)" class Client(QWebEnginePage): def __init__(self,url): global app self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = "" self.loadFinished.connect(self.on_load_finished) self.load(QUrl(url)) self.app.exec_() def on_load_finished(self): self.html = self.toHtml(self.Callable) print("Load Finished") def Callable(self,data): self.html = data self.app.quit() def index(request): submitbutton= request.POST.get("submit") From='' To='' url='' prices = [] form= UserForm(request.POST or None) if form.is_valid(): From = (form.cleaned_data.get("From")).partition(", ")[2] To = (form.cleaned_data.get("To")).partition(", ")[2] context= ({'form': form, 'From': From, 'To': To, 'submitbutton': submitbutton,'prices': prices}) return render(request, "index3.html", context) I tried using the QThreadPool Class, but it didn't work correctly. What can I do to make the code handle links and not crash. -
Django mysql connection errors
Try to connect my django project with MySQL using wamp server i am facing error "Django.db.utils.NotsupportedError" I am tried older version of django To solve this error, but it seems also Same error. -
How to pass a dictionary to an url in POST request in Python
I have to get information about product stocks from marketplace's API via POST request. API requires to send products IDs (sku) in url Example: https://api.market.com/campaigns/{campaignId}/warehouse/{warehouseId}/stocks/actual.json?sku=sku1&sku=sku2&sku=sku3 So I guess, I have to pass a dict like {'sku': '1', 'sku': '2', 'sku': '3'} But of course, It's impossible to create a dict with same keys. I don't know how to solve this task. I made a function, using urllib (urlencode) that works. But it create an url with only last element in params. params = {"sku": "ps-22-1", "sku2": "ps-22-7-2", "sku3": "ps-22-7-3"} def get_stocks(self, campaign_id, warehouse_id, sku): """ Method for parse stocks Parameters: campaign_id (int): client_id in Store warehouse_id (int): warehouse_id in Warehouse sku (str): product sku in Product Returns: data (json): JSON with stocks data """ url = f"{self.url}campaigns/{campaign_id}/warehouses/{warehouse_id}/stocks/actual.json?" req = requests.get(url + urllib.parse.urlencode(sku), headers=self.headers) if req.status_code == 200: return True, '200', req.json() return False, req.json()["error"]["message"] I keep products IDs in my DB in such model: class Product(models.Model): name = models.CharField(max_length=150) sku = models.CharField(max_length=10) -
Django: Exception Value: The 'image' attribute has no file associated with it
Hi everyone I'm trying to create an auction system with Django. But when I go to the item profile, Django sends me an error: Exception Value: The 'image' attribute has no file associated with it. auction.html {% extends "base.html" %} {% block content %} {% load static %} <div class="page-header"> <h1>OPEN AUCTIONS</h1> </div> <div class="container"> <div class="row"> {% for item in auction %} <div class="col-sm-4"> <div class="card border-secondary" style="width: 25rem;"> <div class="card-header"> Auction {{item.id}} </div> <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> <div class="card-body"> <h3 class="card-title" style="text-align:center" >{{ item.object }}</h3> <p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br> End: {{ item.close_date }}</p> <form method="POST"> {% csrf_token %} <input type="number" name='auct_id' value={{item.id}} readonly> <button type="submit" class="btn btn-primary btn-sm">Go</button> </form> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this: view.py @login_required(login_url="login") def auction(request): if request.user.is_superuser: messages.error( request, "super user can access to admin/ and new_auction page only" ) return redirect("new_auction") auction = Auction.objects.filter(active=True) for data in auction: check = check_data(data.close_date) if check is False: data.active = False data.save() check_winner( request, data.id ) check_prof = check_profile( request ) if check_prof is … -
How to deploy django application with celery and celery beat in digitalocean droplet?
Hello developers i nedd to deploy django application with celery and celery beat in digitalocean droplet. where celery worker and celery beat will execute simulteneoulsy. for celery worker: celery -A <project_name>.celery worker --pool=solo -l INFO for celery beat: celery -A <project_name> beatb -l INFO afterward it will run. -
Django ImageField not updating database if i click submit button, but does it if i click enter key
The problem is The problem is that after filling a form without an image and clicking on the submit button, django does nothing and the default image does not get displayed, but if i click the Enter key on my keyboard it works, it shows the default image Can someone please tell me why this is happening, and what is the solution for it I tried changing the url for the button, expecting it to work just as it would if I clicked enter. But that did not work. I have been stressing about this for the past week. And Thanks in advance for everyone who helped. -
Django - Only update FileField column without overriding other columns
In Django, I have a model: class List(models.Model): item = models.CharField(max_length=200) document = models.FileField(upload_to='documents/', null=True, blank=True) Also, I have a page which is to ONLY upload a file to List.document for an existing List: In views.py, I have def upload(request, item_id): if request.method == 'POST': item = List.objects.get(pk=item_id) form = ListForm(request.POST, request.FILES, instance=item) if form.is_valid(): form.save() messages.success(request, 'File saved successfully.') else: messages.error(request, f'File not saved properly: {form.errors.as_data()}') return redirect('home') . However, since the form doesn't include List.item, while clicking Upload, an error occurs File not saved properly: {'item': [ValidationError(['This field is required.'])]}. The easiest way may be add List.item as a hidden element in the html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-10"> <input type="file" class="form-control" name="document" /> </div> <div class="col-md-2"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Upload</button> </div> </div> </form> Nevertheless, is there a better way to get over this? Maybe any options to skip overwriting existing columns? Thanks! -
Trigger React Event from Django Frontend
I want to open a Dialog-window in React whenever the User clicks on the corresponding button in Navbar. The Problem is that the Navbar is part of a Django Frontend. I have tried updating a value in localstorage but I wasn't successful. I have tried using the window.addEventlistener() , but it wouldn't update if changes where made from the Django Navbar. useEffect(() => { window.addEventListener('storage', console.log("CHANGED")) return () => { window.removeEventListener('storage', console.log("CHANGED")) } }, []) Django Template <div class="navbar-nav mr-auto" id="ftco-nav"> <button id="experimentbtn" onClick="open_experiment()" class="btn nav-link">Experiment</button> </div> <script> function open_experiment() { localStorage.setItem('experiment', 'true'); } </script> <div id="root"></div> #This is where the React part is rendered The suggested solution doesn't have to be related to this, i just want to know if there is any other way to make Django communicate with React to trigger such an event switch? -
How to prune inactive / bad APNs tokens in Django-push-notifications
I'm using django-push-notifications (DPN) to send notification to an iOS app. When I send a notification, DPN gives me the response from APNs as a dict with the device tokens and their status. r = devices.send_message(message="Fancy pansy message.", sound="default") Where the response looks something like: r = [ { '<devicetoken1>': 'Success', '<devicetoken2>': 'BadDeviceToken', '<devicetoken3>': 'Success', } ] I have a view in Django which takes POST requests. I use this endpoint to post the message I send to APNs with send_message() as well as save the message to my DB. So my plan was to add the following simple logic to the same view to prune the DB each time I get feedback on expired / bad device tokens from APNs (or something like it, I may of course need to add more statuses than "BadDeviceToken"). for token_str, token_status in r[0].items(): if token_status == 'BadDeviceToken': APNSDevice.objects.filter(registration_id=token_str).delete() My question is if there is a better way of doing this? Should pruning be done with some periodic task instead? Are there any issues with doing this kind of logic in the views in Django? Or am I missing any existing solutions to this problem (pruning tokens) in either Django or DPN? Cheers! -
How can I get a Django template message displayed when I select a value from a dropdown list that matches a condition in the parent table?
I have a form whose constituent fields are foreign keys to respective parent models as shown below: class vehicle(models.Model): STATUS = [ (OPERATIONAL, ('Operational')), (GROUNDED, ('Grounded')), (NA, ('Not Applicable')), ] reg no = models.CharField(max_length=100, null=True) operationalstatus = models.CharField (max_length=100, choices=STATUS, null=True) #####child model### class managecar(models.Model): reg_no = models.ForeignKey(vehicle, on_delete=models.CASCADE, null = True) location = models.CharField(max_length=100, null=True) ####forms.py#### class manageForm(forms.ModelForm): class Meta: model = managecar fields = '__all__' I created a view as shown below and linked a url to it to be called by ajax on the frontend to trigger a message if vehicle selected in the form is 'grounded' but it returns 404 in the console while am expecting it returns a message of vehicle is grounded if I select a vehicle that is listed grounded in the parent model. views.py def validate_operation_status(request): grounded = request.GET.get('grounded', None) data = { 'is_grounded': vehicle.objects.filter(operational_status__iexact='grounded').exists() } return JsonResponse(data) ajax method $("#id_registration_no").change(function () { console.log( $(this).val() ); $.ajax({ url: 'ajax/validate-status/', data: { 'grounded': id_registration_no }, dataType: 'json', success: function (data) { if (data.is_grounded) { alert("This vehicle is grounded."); } } }); }); I'd appreciate to be guided in the right direction or someone to point out where I am failing. Thank you in … -
Django - Add help text to field inherited from abstract base class
I just discovered the "help_text" attribute at Django model fields which automatically adds help textes to fields e.g. in the admin panel. Again, what a nice Django feature! Now I have the problem that I want to add the help_text to a field which is inherited from a parent abstract base class... how could I achieve this? class AbstractBioSequence(models.Model): """ General sequence (DNA or AA) """ name_id = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000, null=True, blank=True) sequence = models.TextField() class Meta: abstract = True class DnaSequence(AbstractBioSequence): some_dna_field = models.TextField() # -------- I want to add a DnaSequence specific helper text to the "sequence" field here -
How to get Google Calendar API working in production to create an event
Problem I'm trying to solve: Using Google Calendar API to create a calendar event. It works on locahost but not in production following the Google Documentation. I'm looking for a solution to get it working in production. What I've tried: I've spent a long time looking at solutions on here including this popular one: Google Calendar API authorization working on localhost but not on Heroku but for me I'm not using pickle. I also attempted all the relevant changes in the answer in relation to my code but I still could not get it to work. I have also made sure that my API console includes the relevant permissions. What's happening: Terminal logs are showing that my code attempts to open a browser on the server machine "Please visit this URL to authorize this application" instead of popping up a browser window for the user. This is most likely because my first try block is failing - which I think is where the problem lies. Please also note I have replaced my redirect URL in the code below for privacy reasons to myurl.com/calendar/. The redirect is simply set to the same page where I am running the code from. Google … -
Unique constraint in my model in my django project?
I would like to configure my Teacher model so that I can have several teachers with the same name, the same age but different departments How to do ? class Teacher(models.Model): name=models.CharField(max_length=70) age=models.IntegerField() service=models.CharField(max_length=100) Exemple output on my database : Name Age Service Arnaud 29 Science Carmen 37 Medecine Arnaud 29 Geologie -
Django: Get multiple id's from checkbox
I'm having problems getting multiple IDs from checkbox. It shows an empty list, and if I inspect my page, it doesn't even show it's value. Unlike the other, obj.stage for example, if I highlight this it shows it's value. So it's not possible to get each id on checkbox? Or I'm just doing it wrong? Hope you can help me, thank you! index.html <a class="btn btn-primary btn-xs" href="/save/">Save</a> {% for obj in queryset %} <tr> <td><input type="checkbox" name="sid" value="{{obj.id}}"></td> <td>{{ obj.stage }}</td> <td>{{ obj.time }}</td> <td>{{ obj.sample_number }}</td> </tr> {% endfor %} views.py sid = request.POST.getlist("sid") samples = SampleHandle.objects.filter(id__in=sid)[0:11] -
Django - givingan unique ID to a blog post/element so it could be used with http referer
I am currently creating my first project and I am using an HTML template that I found online. It is a social media application where you should be able to upload a photo, like the photo, leave a comment, etc. The issue is that I implemented all those functions, but liking, commenting, copying the URL (share buttong) refreshes the whole page and you end up at the very beginning of the page, because I am not sure how to refer the user to the post they liked/commented. I am using return redirect(f'{request.META["HTTP_REFERER"]}#{photo_id}') , but since my posts don't have an unique identifier, it does nothing. Any tips would be greatly appreciated. Thanks in advance! -
Render options of ModelChoiceField
I want to render the options for a ModelChoiceField: {% for value, label in form.fields.event_type.choices %} <option value="{{ value }}" {% if form.fields.event_type.value|add:"" == value %}selected="selected"{% endif %}> {{ label }} -- {{ form.event_type.value }} .. {{ value }} </option> {% endfor %} But this does not work: selected="selected" is not set. The output: <option value=""> --------- -- 2 .. </option> <option value="1"> OptionOne -- 2 .. 1 </option> <option value="2"> OptionTwo -- 2 .. 2 </option> This is strange, since the output "2 .. 2" did not trigger the "if" to include selected. How to solve this? -
sending mail works with mailtrap but not with an outlook server or other
I made a contact form, I tested with the mailtrap service and it works I receive the messages well. But when I put the smpt parameters for a real mail account I have this error message SMTPRecipientsRefused at /contact/ {'info@mysite.net': (550, b'relay not permitted: you must be authenticated to send messages')} the smtp server and the mail account is on the host alwasdata.net, but I tested with an outloock account it's the same thing always this same error. it seems to come from the line in the contact method: message, 'info@mysite.net', ['info@othersite.net'], fail_silently=False, in settings.py i have this config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = "info@mysite.net" EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'smtp-blablabla.net' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 in a views.py def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Message d'un visiteur sur votre site" body = { 'Nom': form.cleaned_data['first_name'], 'Tel': form.cleaned_data['tel'], 'Email': form.cleaned_data['email'], 'Message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail( subject, message, 'info@mysite.net', ['info@othersite.net'], fail_silently=False, ) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') form = ContactForm() return render(request,'pages/email_form.html',{'form':form}) the forms.py from django import forms class ContactForm(forms.Form): first_name = forms.CharField(max_length=100, required=True) tel = forms.CharField(max_length=15, required=True) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea, required=True) -
install postgresql extension before pytest set up database for django
I need to install citext extension to my postgresql database for django project. For the project itself it went smoothly and works great via migrations, but my pytest is configured with option --no-migrations, so pytest create database without running migrations. How can i make pytest to install citext postgres extension before tables are created? Currently i'm getting - django.db.utils.ProgrammingError: type "citext" does not exist while pytest trying to create table auth_users sql = 'CREATE TABLE "auth_user" ("id" serial NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" timestamp ...T NULL, "is_active" boolean NOT NULL, "date_joined" timestamp with time zone NOT NULL, "email" citext NOT NULL UNIQUE)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7fb313bb0100>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7fb30d9f8580>}) I tried to use django_db_setup fixture, but i did not figure out how to change it, because something like this @pytest.fixture(scope="session") def django_db_setup( request, django_test_environment, django_db_blocker, django_db_use_migrations, django_db_keepdb, django_db_createdb, django_db_modify_db_settings, ): """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if not django_db_use_migrations: from pytest_django.fixtures import _disable_native_migrations _disable_native_migrations() if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True with django_db_blocker.unblock(): from django.db import connection cursor = connection.cursor() cursor.execute("CREATE EXTENSION IF NOT EXISTS … -
Unable to login even after entering correct credentials
I have created a seperate app for user account management which handels registration, login and logout. However, after successful signup, I'm unable to login even after using the correct credentials provided during signup. Here are the required code for the review: models.py `from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('Email is required.') if not username: raise ValueError('Username is required.') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name,`your text` ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, username, email, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self.db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True` forms.py `from crispy_forms.helper import FormHelper from django import forms from .models import Account class RegistrationForm(forms.ModelForm): first_name = … -
enctype='multipart/form-data' is not storing images in django?
I wanted to save text and images in my database in django but when i used enctype='multipart/form-data' it is not storing the image. When i do it without enctype='multipart/form-data' it is storing the name of image this is my index.html ` <form method="POST" action="/index" enctype='multipart/form-data'> {% csrf_token %} <div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div> <div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div> <div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div> <div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div> <div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div> <div>Dish image: <input name="dish_image" type="file"></div> <button type="submit" class="btn btn-success">Submit</button> </form> this is my views.py def index(request): if request.method == "POST": dish_name = request.POST.get('dish_name') dish_size = request.POST.get('dish_size') dish_price = request.POST.get('dish_price') dish_description = request.POST.get('dish_description') dish_image = request.POST.get('dish_image') dish_category = request.POST.get('dish_category') item = dish(dish_name = dish_name, dish_size = dish_size, dish_price = dish_price, dish_description = dish_description,dish_category=dish_category, dish_image = dish_image, dish_date = datetime.today()) item.save() dishs = dish.objects.all() params = {'dish': dishs} return render(request, "card/index.html", params) this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here … -
How to monitor a thread in python?
I'm having a kafka consumer which is running in a thread in my django application, I want to apply some monitoring and alerting on that thread. So how can I add thread monitoring (check state if it is alive or dead) and if thread is dead then need to raise an alert. I have tried monitoring by creating scheduler which runs every 10 mins and calls thread.is_alive() method. But the problem is the scheduler is running in a different process and unable to access main process' s thread. So how can I resolve this? -
Two models with one-to-many into single JSON dict
I have two models for 'PO Header' and 'PO Item' data like this: class po(models.Model): po_number = models.CharField(max_length=16, null=True) buy_org = models.CharField(max_length=20, null=True) supplier = models.CharField(max_length=16, null=True) class poitm(models.Model): po = models.ForeignKey(po, on_delete=models.CASCADE, related_name='poitm') po_li = models.CharField(max_length=6, null=True) matnr = models.CharField(max_length=16, null=True) quantity = models.DecimalField(decimal_places=6, max_digits=16, null=True) I try to create a view that returns a json object like this: [{'po_number':'45000123','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123456','quantity':'12'},{'po_li':'020','matnr':'123457','quantity':'8'}]},{'po_number':'45000124','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123235','quantity':'15'},{'po_li':'020','matnr':'123499','quantity':'24'}]} ] In principle a list of purchase orders with each purchase order containing a list of purchase order items. I managed to create queryset containing the data like I need it but for performance reasons when using datatables.net with dom data I need to return the data in json format instead of looping through the queryset in the html template. def purchaseorders(request): polist=purchaseOrder.objects.all() itemlist=poItem.objects.all() for poentry in polist: poentry.itemlist=itemlist.filter(po_id=poentry.id) return render(request, 'purchaseorders.html', {"poitems":polist}) This seems to create a queryset with each object of a queryset. This then gives me a problem when I try to serialize it to json. Only the fields from the outer queryset are in the json result. I looked and tried for two solid days, turning in circles now, please help. -
How to get data from database, whenever database is updated in database Caching in Django [closed]
When i hit API every time data is fetching from database caching, even though database is updated(add or remove). How to communicate with cache and database, when changes are made in database