Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate total price from selected menu
I created a restaurant web using django frameworks. so i have a problem when i want to calculate all the menu prices are selected. This is the simple Flowchart: Login → user selecting customer → create customer order → billing but i not yet create the billing here this my models.py from django.db import models from django.contrib.auth.models import User class Menu(models.Model): name = models.CharField(max_length=255) price = models.FloatField() def __str__(self): return self.name + ', Rp ' + str(self.price) + '00' class Customer(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(default='', max_length=255) gender = models.CharField(max_length=255) phone = models.CharField(max_length=255) address = models.TextField() def __str__(self): return self.name + ', phone = ' + self.phone def absolute_url(self): return self.slug class Order(models.Model): menu = models.ManyToManyField(Menu, related_name='order') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) total_prc = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.customer + ', total price = ' + self.total_prc class Transaction(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) total = models.FloatField() paid = models.FloatField() def __str__(self): return self.order so the menu and order models that i've been create with many to many relationship then form.py for the create customer order menu_choices = Menu.objects.all().values_list('pk', 'name') menu_choices_list = [] for menu in menu_choices: menu_choices_list.append(menu) class CreateOrder(forms.ModelForm): class Meta: model = Order fields = … -
Django admin display only one option in a drop down list created via the use of foreign key depending on the logged in user
Am using django admin dashboard to manage both customers and admin in an online mall. The customers are the owners of the shop while the admin is the one who creates customers and assign shops to them. models.py class Shop(models.Model): name = models.CharField(max_length=20) class Product(models.Model): name = models.ForeignField(Shop) After creating a customer, the admin gives the customers the permissions to add, view, edit, and delete products. When the customer logs into the same admin dashboard he is able to add, view, edit, and delete products. The problem is when it comes to selection of a shop to add products to, the customer is able to see other shops hence data leakage. Also the customer is able to view products of other shops when the he clicks the products -
raise DecodeError( jwt.exceptions.DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode()
I see this raise DecodeError( jwt.exceptions.DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode(). when i am trying to decode like this class UserView(APIView): def get(self,request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token,'secret', algorithm=["HS256"]) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) Its mainly happening for this line: payload = jwt.decode(token,'secret', algorithm=["HS256"]) Do you have any suggestion for this. I am struggling with this issue. Any suggestion will be great help. Solutions i got so far: 1 downgrade jwt version to PyJWT==1.7.1. 2. downgrade azureml-core==1.18.0.post1 (is this necessary?) do i need to perform these 2. since i am using jwt 2.0.1 will it acceptable if i downgrade my jwt to fit with the only current issue of saying decodeerror. Thanks, -
How can I monitoize my django rest api requests
Hi I have a django rest api for my android app. I would like to monitorize requests. Also I am using nginx. How can I do it with open source tools. -
Django Rest Framework - @csrf_exempt not working with custom JWT-HTTPOnly Cookie authentication
Forgive me if this question was already posted, I could not find a solution for hours so felt a need to ask here. I am doing custom authentication for DRF where JWT Token will be set as HTTP-Only cookie and alongside CSRF token will be set as simple cookie so that I can read it with JS and add to header. So the code is as below. Authentication works and CSRF check is done only for unsafe methods however now, csrf_exempt decorator is not working. I have tried it with almost all the possible ways, setting it over dispatch method, other methods, created func based views and added there but still csrf is required. I think after diving deep in Django source code I found the problem is related that I am calling process_view function and givin callback_view as None so the check is returning false. In anyway, I would like to know how I can solve this issue? import jwt from rest_framework.authentication import BaseAuthentication from django.middleware.csrf import CsrfViewMiddleware from rest_framework import exceptions from django.conf import settings from django.contrib.auth import get_user_model class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): # Return the failure reason instead of an HttpResponse return reason class MyJWTAuthentication(BaseAuthentication): … -
PypeR suddenly stops working when two or more users use it
I am using Pyper as a way to connect Python to R using Django framework ,I am using it in a way that i am running r script through pyper using r.run("source('"+path2script+"')"). But i am running into an issue where pyper suddenly stops when two or more users try to access it. I do not understand why it is happening and how pyper stops suddenly. Also r script i am using performs lot of calculations. My idea is calculation is filling the r session and then pyper stops. Can anybody help me with this. Thanks in advance. -
How can I reduce the number of SQL queries in my view?
I have a functional view but it makes too many SQL queries and I can't optimize it to reduce the number of SQL queries. My Model : class MbGroups(models.Model): """ groups for users """ name = models.CharField("Nom", max_length=70) club = models.ForeignKey("clubs.Club", verbose_name="Club", on_delete=models.CASCADE) peoples = models.ManyToManyField(User, verbose_name="Liste des personnes", blank=True, related_name="groups_user") parent_group = models.ForeignKey("utilisateurs.MbGroups", related_name="sub_group", blank=True, null=True, verbose_name="Groupe parent", on_delete=models.CASCADE) level = SmallIntegerField(verbose_name="niveau", default=0) @property def has_subgroup(self): return MbGroups.objects.filter(club=self.club) \ .filter(parent_group=self) \ .exists() class Meta: verbose_name = "Groupe ou sous groupe" verbose_name_plural = "Groupes ou sous groupes" ordering = ['name'] def __str__(self): full_path = [self.name] k = self.parent_group while k is not None: full_path.append(k.name) k = k.parent_group return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): if self.parent_group: self.level = self.parent_group.level + 1 else: self.level = 0 super(MbGroups, self).save(*args, **kwargs) The purpose of this model is to be able to create groups and sub-groups with people in them. I created a view to assign some groups to an user : @login_required @manager_required def add_groups_to_user(request, pk): """ add one or many groups to an user """ club_pk = request.user.profil.club_administrator.pk user = User.objects.filter(pk=pk).prefetch_related("groups_user").first() if not request.method == "POST": mbgroups = cache.get_or_set("get_list_groups_club_{}" \ .format(club_pk), MbGroups.objects.filter(club__pk=club_pk) \ .order_by("name") \ .prefetch_related("sub_group") \ .prefetch_related('peoples') \ .only("pk", "name", … -
Model Admin Error: Cannot Exclude Field because it is a Foreign Key to the parent model
My goal is to be able to select a location and Input part numbers without seeing this quote field. I dont even completely understand what this select box is looking for. I have Quote objects saved and yet these are not coming up as selectable options. Not that I want them to, Im just saying. My thinking regarding the seelctable options is that this would be auto-populated? You can probably tell my confusion even in my explanation. Ultimately, I dont want to see a select box at all as Im not really interested in whatever this pointing to, but just for kicks would like to know what it is trying to point to. quote/Models.py class Quote(models.Model): QUOTE_ENVIRONMENTS = ( ('testing', 'Test'), ('production', 'Production') ) SALES_SOURCE=((1, 'Marketplace'), (2, 'Webstore'), (3, 'Physical Store'), (4, 'Phone') ) environment = models.CharField(max_length=20, choices=QUOTE_ENVIRONMENTS, default="testing") sales_source = models.IntegerField(choices=SALES_SOURCE, null=True) order_notes = models.TextField(blank=True) locations = models.ManyToManyField('products.ProductSelection') products/models.py class Product(models.Model): pass class Warehouse(models.Model): pass class ProductSelection(models.Model): location = models.ForeignKey('Warehouse', on_delete = models.CASCADE) product = models.ManyToManyField('Product') Admin.py class ProductOrderForm(forms.ModelForm): locations = forms.ModelChoiceField(queryset= Warehouse.objects.all()) part_number = forms.IntegerField() def clean_product_id(self): cd = self.cleaned_data logger.info(cd) value = cd['part_number'] if value not in Products.objects.list_part_numbers(): raise forms.ValidationError("Not a valid partnumber") class ProductSelectionTabularInline(admin.TabularInline): form = … -
How to manage partial dates with django-partial-date and SelectDateWidget?
I have to manage partial date I have declare a date as PartialDateField() in my model and I want to render this date as 3 differents select in my form so I use SelectDateWidget But doing that, form validation failed is it possible? how shoud I manage partial date in forms? class mymodel(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE ide = models.AutoField(primary_key=True) dat = PartialDateField("my date", null=True, blank=True) log = HistoricalRecords() class myform(forms.ModelForm): dat = forms.DateField( label= "my date", widget=forms.Select() ) class Meta: model = mymodel fields = "__all__" -
./runtests (in django) ImportError: cannot import name 'NullTimeKeeper'
The following command was executed in the tests directory inside the development version of django ./runtests.py Traceback (most recent call last): File "./runtests.py", line 26, in <module> from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner ImportError: cannot import name 'NullTimeKeeper' I am using python 3.8 and am following the instructions for contributing to django from https://docs.djangoproject.com/en/3.1/intro/contributing/ where I have resolved all errors up to this point. Could someone explain what I would have to do as I already ran python3.8 -m pip install -r requirements/py3.txt in my virtual environment that I created using python3.8 -m venv /path/to/venv -
PREVIOUS AND NEXT BUTTONS with Javascript to handle a List of DATA from an API
I have a function to set two buttons " PREVIOUS AND NEXT" to display a list that I sourced from an API. There is a maximum amount of results to be displayed of 11. I am not coming up with the right logic to display when page == 0, only the next button, and when page > 0, the next button AND the previous button, and if the page < 0, only the Next Button to be showing. this is my JS function: function appendData(Data) { var newselement = document.getElementById('newselement'); var previous = document.getElementById('previous'); var next = document.getElementById('next'); var fulllist = []; var page = 0; previous.style.display = 'none'; for (var i = 1; i < Data.length; i++) { var Containersummary = document.createElement("div"); Containersummary.setAttribute('id','artsum'); Containersummary.innerText = Data[i].body; var Containerimage = document.createElement("img"); Containerimage.setAttribute('id','artimg'); Containerimage.src = Data[i].imageurl; var Containername = document.createElement("div"); Containername.setAttribute('id','arttit'); Containername.innerText = Data[i].title; var Containerurl = document.createElement("a"); Containerurl.setAttribute('href', Data[i].url); Containerurl.innerText = Data[i].url; var arrayList = document.createElement("div"); var hr = document.createElement("hr") hr.setAttribute('id','brake'); var br = document.createElement("br") arrayList.appendChild(Containername); arrayList.appendChild(Containerimage); arrayList.appendChild(Containersummary); arrayList.appendChild(Containerurl); arrayList.appendChild(br); arrayList.appendChild(hr); fulllist.push(arrayList); } for (var i = 0; i < page + 11; i++){ newselement.appendChild(fulllist[i]); } next.addEventListener("click", () => { if (page > 0){ previous.style.display = 'block'}; page == fulllist.lenght … -
Python, Django: ForeignKey with dependencies (models.py)
Good day, I would like to ask, if it's possible to determine an additional dependencie on a models.ForeignKey-field? For example ... models.py class Object_A(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) date_created = models.DateTimeField(auto_now_add=True) class Object_B(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) object_a = models.ForeignKey(Object_A, null=False, blank=False, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) class Object_C(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) object_a = models.ForeignKey(Object_A, null=False, blank=False, on_delete=models.CASCADE) object_b = models.ForeignKey(Object_B, null=False, blank=False, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) forms.py class Create_Object_C_Form(ModelForm): class Meta: model = Object_C exclude = [ 'object_a', 'date_created', ] What I'm trying to do... As you can see, I'm excluding the object_a, because at this point inside my app where the form is used, the user doesn't have to choose for an object_a. His own steps have anticipated this choice! The same - or at least almost the same - goes for object_b: Is it possible to only show choices that are related to the same object_a? Hoping I could explain my problem understandably and somebody can help or has an idea!? Have a great day! -
Not able to post the form
So i have a table in ms sql database.the connections is open but the form wont submit. def add(request): print('start') if request.method == "POST": print('post') if request.POST.get('name') and request.POST.get('contact_person') and request.POST.get( 'address') and request.POST.get('ph_no') and request.POST.get('tele') and request.POST.get( 'mail') and request.POST.get('is_active') and request.POST.get('last_update'): print('get') insertstvalues = Company() # insertstvalues.company_id = request.POST.get('company_id') insertstvalues.name = request.POST.get('name') insertstvalues.contact_person = request.POST.get('contact_person') insertstvalues.address = request.POST.get('address') insertstvalues.ph_no = request.POST.get('ph_no') insertstvalues.tele = request.POST.get('tele') insertstvalues.mail = request.POST.get('mail') insertstvalues.is_active = request.POST.get('is_active') # insertstvalues.last_update = request.POST.get('last_date') print('values') cursor.execute( "insert into Company values ('" + insertstvalues.name + "','" + insertstvalues.contact_person + "','" + insertstvalues.address + "','" + insertstvalues.ph_no + "','" + insertstvalues.tele + "','" + insertstvalues.mail + "','" + insertstvalues.is_active + "')") print('execute') cursor.comit() print('record added') return render(request, 'addRecord.html') else: print('Rerun') return render(request, 'addRecord.html') this is the functions i have in views.py.connections and cursor strings are all working. here is the html code for the from to take in the values so when i run the app this is what i see cmd terminal after i click the insert button basically as far as i can see is that the program never runs the second if statement. I want to add data to my table so i am open to any … -
How to update primary key, what have foreign keys pointing to, without "ON UPDATE CASCADE"
I have PostgreSQL database created with Django with lots of tables. Also there are multiple foreign keys between tables. I need to change id (primary key) field of users_user table, but there are a lot of tables that are pointing to it. Of course ideal solution is to add "ON UPDATE CASCADE" to all of the foreign keys. But in my case its impossible during long sequence of reconciliations, making agreements with other teams about such database model changes. So, I need a way of changing primary key and all the foreign keys automatically without manually specifying other tables, because there are a lot of. -
why i cant save student data in database using Django
when I'm trying to save the attendance of students but is not saving data in the database. it's giving an error in of else which I coded in the views.py file. I have taken name,rollnumber from studentProfile, and status from studentAttendance and trying to save in the database but I'm getting an error message which I have coded in views.py. views.py from django.contrib import messages from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import * from .models import * def studentAttendanceView(request): student_status = studentProfile.objects.all() if request.method == "POST": studentData = studentAttendanceForm(request.POST) if studentData.is_valid(): cd = studentData.save() cd.author = request.user cd.save() cd.refresh_from_db() name = studentData.cleaned_data.get('name') messages.success(request, f'Attendance submitted for {name} ') else: messages.error(request, 'Please check An Error occurred') else: studentData = studentAttendanceForm() return render(request, 'attendance.html', {'studentData': studentData, 'student_status': student_status}) forms.py from django import forms from .models import * class studentAttendanceForm(forms.ModelForm): class Meta: model = studentAttendance fields = ['name', 'status'] class studentProfileForm(forms.ModelForm): class Meta: model = studentProfile fields = '__all__' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.studentProfileView, name='studentProfile'), path('attendance/', views.studentAttendanceView, name='studentData'), ] models.py from django.db import models class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class … -
How to import vue component in Django template script
according to the following component document https://talkhabi.github.io/vue-persian-datetime-picker/#/installation Need to import import VuePersianDatetimePicker from 'vue-persian-datetime-picker' But I do not know how to address to read the file from static files How do I address? 'vue-persian-datetime-picker' -
Implementing push notification in flutter with django channels and django REST framework
I'm working on a flutter based chat app of an existing web app built in Django. I'm using django channels for the messaging and notifications in website. I've successfully implemented messaging using websockets in mobile app but unable to implement push notifications when app is closed i.e. no websocket connection established. How to implement this? Thanks in advance :) -
JsonResponse print dictionary instead of return to ajax success function in django
here i want to give a Javascript alert when data is insert into database. data is successfully into database, but JsonResponse not return dictionary to ajax success function and print data of dictionary into webpage. here i put only ajax part of my html file HTML File $.ajax({ type: 'POST', url: '{% url 'Patient:add' %}', data: info, dataType: 'json', success: function (data) { console.log("Received") if (data.saved === 1) { alert("Data Saved"); } } }); This is my view.py code def add_patient(request): if request.method == 'POST': name = request.POST['name'] gender = request.POST['gender'] birthdate = request.POST['birthdate'] add = Patient(name=name, gender=gender, birthdate=birthdate) add.save() data = {'saved': 1} return JsonResponse(data) else: return render(request, 'Patient_template/add_patient.html') here i call ajax function on form submit event using javascript, when i fill all filed and submit the form it redirect to the web page, which show {'saved': 1}. screenshot of page after submit the form here -
Django - export excel make it faster with openpyxl
I am using Django restframework and I am trying to export excel. My issue is the process is take a lot of time till it generates the excel file. The final file have about 1MB with 20k lines and the generation time is about 8 minutes and this does not seem right. here is the view: class GenerateExcelView(APIView): filename = 'AllHours.xlsx' wb = Workbook() ws = wb.active ws.title = "Workbook" data = Report.objects.all() row_couter = 2 for line in data: first_name = line.employee_id second_name = line.employee_name age = line.description ... ws['A{}'.format(row_counter)] = first_name ws['B{}'.format(row_counter)] = second_name ws['C{}'.format(row_counter)] = age ... row_counter +=1 response = HttpResponse(save_virtual_workbook(wb), content_type='application/ms-excel') response["Content-Disposition"] = 'attachment; filename="' + filename + '"' return response There are few more columns... Is it possible to change the process so it is a bit faster? -
How to create an overview API for statistics with the Django REST framework
Currently, I have such a view and serializer, but how can I create an overview API for statistics? serializers.py class ExampleSerializer(serializers.ModelSerializer): total = serializers.SerializerMethodField() class Meta: model = Example fields = '__all__' def get_hms(self, obj): return Example.objects.count() views.py class ExampleViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] serializer_class = ExampleSerializer def get_queryset(self): return self.request.user.example.all() def perform_create(self, serializer): serializer.save(user=self.request.user) total = serializers.SerializerMethodField() is used to display the number of Examples, but with this code, only one is needed since it is originally an overview, but the total is displayed as many as there are models. How can I create a View and Serializer that is not associated with a model? I would appreciate it if you could tell me more. -
Displaying several rows of text from a view in Django
I am working on a Django application that displays information recorded in user logs. This specific one is designed to tell which users share an IP. My Code looks like this: users = logs.username.unique() UsedUsers = [] print('Shared IPs:') print() for user in users: UsedUsers.append(user) for otherplayer in users: if otherplayer not in UsedUsers: Userlogs = logs[logs.username.isin([user]) UserIP = Userlogs.IP.unique() OtherPlayerlogs = logs[logs.username.isin([otherplayer]) OtherPlayerIP = OtherPlayerlogs.IP.unique() SharedIPs = set(UserIP).intersection(OtherPlayerIP) print(user, 'shares these IPs with', otherplayer, ":") print(*SharedIPs, sep = "\n") print() Naming conventions are probably pretty bad. This is more of my learning project. My issue is that I can get this code to work in Juypter Notebook, but when I switch it to a view in Django I am not sure how to store it to pass it into a .html -
Python get max price sum 3 top records
I have a table where data like : Id price date user_id type __________________________________________________________________ 1 120 2021-03-05 1 credit 2 120 2021-03-05 1 credit 3 120 2021-03-08 2 credit 4 120 2017-06-20 3 credit 5 140 2017-06-20 4 debit 6 120 2017-06-20 1 credit 8 120 2021-03-09 2 credit 9 130 2017-06-20 2 credit 10 120 2021-03-05 1 debit 11 160 2021-03-05 5 debit 12 210 2021-03-05 5 credit what i actually want is i want distinct user according to userid and created_at between 2021-03-05 to 2021-03-11 with type credit 3 top price users with price sum . 3 top user which have max price sum according to this filter. i am stuck here can anyone please help me related this ?? -
How to get request obj in @reciver post_save in django?
@receiver(post_save, sender=Enrollment) def update_cert_qual_progress(sender, instance, created, **kwargs): if not created and "progress" in instance.changed_fields: if instance.certification_id: certification_progress = Enrollment.objects.filter( user=instance.user, certification=instance.certification ).aggregate(Avg("progress")) CertificationUser.objects.filter( user=instance.user, certification=instance.certification ).update(progress=certification_progress["progress__avg"]) if instance.status == "completed": certification = course_user_item.course.uuid get_or_create_user_certification_certificate(request, certification) if instance.qualification_id: qualification_progress = Enrollment.objects.filter( user=instance.user, qualification=instance.qualification ).aggregate(Avg("progress")) QualificationUser.objects.filter( user=instance.user, qualification=instance.qualification ).update(progress=qualification_progress["progress__avg"]) i have to call below function in above code,but for that i need request object .But i am not able to fetch request object . def update_cert_qual_progress(sender, instance, created, **kwargs): if not created and "progress" in instance.changed_fields: if instance.certification_id: certification_progress = Enrollment.objects.filter( user=instance.user, certification=instance.certification ).aggregate(Avg("progress")) CertificationUser.objects.filter( user=instance.user, certification=instance.certification ).update(progress=certification_progress["progress__avg"]) if instance.status == "completed": certification = course_user_item.course.uuid get_or_create_user_certification_certificate(request, certification) if instance.qualification_id: qualification_progress = Enrollment.objects.filter( user=instance.user, qualification=instance.qualification ).aggregate(Avg("progress")) QualificationUser.objects.filter( user=instance.user, qualification=instance.qualification ).update(progress=qualification_progress["progress__avg"]) Please suggest something how to solve this and help me. -
modal window in django template using HTMX
I have a template and a modal window inside it. Normally (with JS only) I would have some code in the template that toggles the modal: {% include "testapp/modal/test_modal.html" %} <button class="..." data-toggle="modal" data-target="#testModal"></button> and add a test_modal.html file in my templates folder which contains the modal window: <div class="modal ..." id="testModal" aria-hidden="true"> .... <button id="test_submit" type="submit"></button> <!-- submit modal --> </div> A simple JS line would select what happens on pressing the button: document.querySelector('#test_submit').addEventListener('click', event => { $('#testModal').modal("hide") const dlwindow = window.open(`/test/${testvar}`, "_self"); which would trigger some view defined in the urls.py by django: path(r"test/<testvar>", views.TestView.as_view(), name="test") So far, so good. Now I want to create the same setup using HTMX and when following the HTMX modal exmaple I come to the point where the example says: <button hx-get="/modal" hx-target="#modals-here" hx-trigger="click" class="btn btn-primary" _="on htmx:afterOnLoad wait 10ms then add .show to #modal then add .show to #modal-backdrop">Open Modal</button> <div id="modals-here"></div> This button uses a GET request to /modal when this button is clicked. The contents of this file will be added to the DOM underneath the #modals-here DIV. This is exactly where I am stuck: The GET request should point to a urls.py entry, aka a view of some … -
Expose page alias in wagtail API
Wagtail recently gained support for page aliases (the same page in another part of the tree). The API returns these pages as if they are "normal" pages. I'd like the API to tell me that the page is an alias of another page. The reason for this is to be able to add a rel="canonical" link. I'd also like to be able to (optionally) return the list of aliases for the original page using the API. This way I can build a list of "this page is also available here". It seems that it is possible to detect an aliases by inspecting the alias_of ForeignKey: https://github.com/wagtail/wagtail/blob/c5f49274c8730ce04ca76df1ceef96d5cc83fac0/wagtail/core/models.py#L843 But I'm unsure on how to make this work with the Wagtail API and DRF serializers.