Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Missing css in Django admin
I'm used nginx + unicorn + Django and absence css only in Django admin. I'm not understand the reason. Static is shown on all a pages besides admin. In terminal is see 200code: http://joxi.ru/KAxLRZEi4kdQYA In console missing error: http://joxi.ru/12M6KL0i4jpO9A P.S. I make collectstatic settings INSTALLED_APPS = [ 'homepage', 'info', 'login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Django HTML Post wrong button value
POST is sending me the wrong button value, it seems that it send the id of the last student. Instead of assigning each button with unique student_id. {% for student in student_list %} <tr> <td>{{ student.firstname }}</td> <td>{{ student.lastname }}</td> {% if student.id in resource_list %} <td><a href="#" class="btn btn-danger" role="button">Details</a></td> {% else %} <td><form name="book" method="post" action="{% url 'site:booking' %}"> {% csrf_token %} <input type="hidden" name="student_id" value="{{ student.id }}" /> <input type="submit" class="btn btn-success" value="Book Student"> </td> {% endif %} </tr> {% endfor %} -
In Python, how to open a string representing HTML in the browser?
I'd like to view a Django template in the browser. This particular template is called in render_to_string, but is not connected to a view, so I can't just runserver and navigate to the URL at my localhost. My idea was to simply call render_to_string in the Django shell and somehow pass the resulting string to a web browser such as Chrome to view it. However, as far as I can tell the webbrowser module only accepts url arguments and can't be used to render strings representing HTML. Any idea how I could achieve this? -
Forbidden You don't have permission to access / on this server on Ubuntu server
I am trying to deploy me Django application on Ubuntu server by using this My stack is: Python 2.7 Djagno 1.8 Server: Ubuntu 16.04.3 LTS /etc/apache2/sites-available/000-default.conf file after changes: Alias /static /root/enoticerepo1.2/etenderprj/static <Directory /root/enoticerepo1.2/etenderprj/static> Require all granted </Directory> <Directory /root/enoticerepo1.2/etenderprj/etenderprj> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess etenderprj python-path=/root/enoticerepo1.2/etenderprj python-home=/usr/bin/python2.7 WSGIProcessGroup etenderprj WSGIScriptAlias / /root/enoticerepo1.2/etenderprj/etenderprj/wsgi.py I have given all required permision to required user recursively(-R) : drwxr-xr-x 4 www-data www-data 4096 Jan 21 08:48 ./ drwx------ 13 root root 4096 Apr 3 20:37 ../ drwxr-xr-x 9 www-data www-data 4096 Jan 21 08:48 etenderprj/ drwxr-xr-x 8 www-data www-data 4096 Mar 14 18:06 .git/ -rwxr-xr-x 1 www-data www-data 46 Jan 21 08:48 .gitignore* -rwxr-xr-x 1 www-data www-data 565 Jan 21 08:48 README.md* After doing all this, still it is give me Forbidden error. Please look into this. Thanks in Advance. -
Formatting date 2018-04-03T14:10:00-07:00 to any readable date/time in Python
2018-04-03T14:10:00-07:00 is there a built in python method? Or something in Django? I am only used to working with javascript/node and I can't figure this out -
i want to show one image with individual post in my index.html
i am having problem in my posts,i want to show one image related to every post on my index.html and for that i am using jquery image slider and i want to show just one image from multiple post images but it shows either all images or nothing,please do help me...i am using query.postpicture_set.all to show pictures and grabbing first picture of every post to show with the post here's my code <html> <head> <meta charset="utf-8"> <title>Online Vehicles</title> <style> .mySlides {display:none;} </style> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384- BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body style="background-color:white;"> {% for obj in context %} <div class="container" style="padding-left:240px; padding-right:0px; width: 78%; margin-bottom:30px;"> <div class="well" style=" background-color: rgb(220, 220, 220);"> <div class="media"> <div class="media-body"> <div class="list-group"> <div class="d-flex w-100 justify-content-between"> <h1 class="media-heading" style="margin-top:20px; margin- bottom:20px; color: black;">{{ obj.title }}</h1> {% for img in obj.postpicture_set.all %} <div class="w3-content" style="max-width:800px"> {% if img.image %} <img style="margin-bottom:30px; float: right" class="mySlides" src="{{ img.image.url }}" width="200" height="180"> {% endif %} </div> {% endfor %} <p> {{ obj.details }} </p> <ul class="list-inline list-unstyled"> <li><span><i class="glyphicon glyphicon-calendar"></i> {{ obj.date }} </span></li> <li>|</li> <span><i></i> {{ obj.brand }} </span> <li>|</li> <span><i></i> {{ obj.city }} </span><br> {% else %} {% endif %} </ul> </div> </div> </div> </div> </div> … -
using django urls in react
On back-end I have Django and on front-end, I run react.js. Now my react is serving in Django, I build (npm run build) react and then tell Django where it can find static files. So, now I want to create a registration, I know that I could do it with JWT but it is a bit difficult for me so I decided to leave it. Again, I want to make a registration, I thought that after I served react.js in Django I can use /signup URL (that I had created before), in react smth like: ` <Route> <Router path="signup"> </Route> Is it real to Django reg. via django and just link to it throught react-router? -
Django : how to give user/group permission to view model instances for a specified period of time
I am fairly new to Django and could not figure out by reading the docs or by looking at existing questions. I looked into Django permissions and authentication but could not find a solution. Let's say I have a Detail View listing all instances of a Model called Item. For each Item, I want to control which User can view it, and for how long. In other words, for each User having access to the Item, I want the right/permission to view it to expire after a specified period of time. After that period of time, the Item would disapear from the list and the User could not access the url detailing the Item. The logic to implement is pretty simple, I know, but the "per user / per object" part confuses me. Help would be much appreciated! -
Unable to parse JSON string in JavaScript
I'm sending JSON string from Django view to javascript file named idbop.js at the client side. I'm using the serializer in Django to convert query result in Django to JSON. Here is my code in views.py of Django def index(request): template='posts/index.html' results=feed.objects.all() jsondata = serializers.serialize('json',results) context={ 'results':results, 'jsondata':jsondata, } return render(request,template,context) At client side, I'm accessing jsondata in javascript as follows: var jsondata="{{jsondata}}".replace(/&quot;/g,"\""); Here jsondata is in string format. If I try to parse it using, var data = JSON.parse(jsondata); It is throwing an error:SyntaxError: JSON.parse: bad control character in string literal at line 1 column 344 of the JSON data I'm having whitespace at 344 in jsondata but that whitespace is inside the string of value. Here is my JSON string: [ { "model": "posts.feed", "pk": 1, "fields": { "author": "J Watson", "title": "Service Worker", "body": "A service worker is a type of web worker. It&#39;s essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages. Because workers run separately from the main thread, service workers are independent of the application they are associated with. This has several consequences:" } }] -
Django celery add second worker
I am currently running django celery and im having trouble adding a second worker. I am running django on a windows environment so I dont know where the config file for celery is. I also cannot find out how to add another worker in my settings.py For example: BROKER_URL = 'my_url' CELERY_ACCEPT_CONTENT = ['pickle', 'json'] CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'America/New_York' **CELERYD_NODES = "w1 w2"** CELERY_IMPORTS = ( 'MyImports' ) CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' import django django.setup() import djcelery djcelery.setup_loader() I do not want to start a worker from the command line because I want it to start up each time the server starts or reloads. I was able to create a new worker on my linux environment by setting CELERYD_NODES="w1 w2" in /etc/default/celeryd. But again, this is a windows environment and I cannot find where to change these options in it. Thanks in advance -
Deploying a Geodjango Application on AWS Elastic Beanstalk
I'm trying to deploy a geodjango application on AWS Elastic Beanstalk. The configuration is 64bit Amazon Linux 2017.09 v2.6.6 running Python 3.6. I am getting this error when trying to deploy: Requires: libpoppler.so.5()(64bit) Error: Package: gdal-java-1.9.2-8.rhel6.x86_64 (pgdg93) Requires: libpoppler.so.5()(64bit) How do I install the required package? I read through Setting up Django with GeoDjango Support in AWS Beanstalk or EC2 Instance but I am still getting problems. My ebextensions currently looks like: commands: 01_yum_update: command: sudo yum -y update 02_epel_repo: command: sudo yum-config-manager -y --enable epel 03_install_gdal_packages: command: sudo yum -y install gdal gdal-devel packages: yum: git: [] postgresql95-devel: [] gettext: [] libjpeg-turbo-devel: [] libffi-devel: [] -
Django Serializer object has no attribute
I have expanded off the django auth_user to create a profile off of that. When I try to use a serializer to post to the new profile model I keep getting the following error. Error instance.userid = validated_data.get('user_id', instance.userid) AttributeError: 'User' object has no attribute 'userid' It seems like a pretty straight forward message but I am not sure why it is happening and how to fix it. Model class UserProfile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=True) start_date = models.DateTimeField last_active_date = models.DateTimeField alias_name = models.CharField(max_length=30) city = models.CharField(max_length=30) state = models.CharField(max_length=30) zipcode = models.CharField(max_length=5, null=True) view def user_profile_list(request, user_id): try: userid = user_id except userid.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': uprofile = UserProfile.objects.all().values() list2 = list(uprofile) return JsonResponse(list2, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) user = User.objects.get(id=userid) serializer = UserProfileSerializer(user, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) serializer class UserProfileSerializer(serializers.Serializer): class Meta: model = UserProfile def create(self, validated_data): return UserProfile.objects.create(**validated_data) def update(self, instance, validated_data): instance.id = validated_data.get('id', instance.id) instance.userid = validated_data.get('user_id', instance.userid) instance.save() return instance POST { "user_id": "1", "start_date": "2018-03-20 21:04:55.633487-06", "last_active_date": "2018-03-20 21:04:55.633487-06", "alias_name": "FooName", "city": "Denver", "state": "CO", "zipcode": "80000", } -
Django returning unicode value for a queryset
Models.py from datetime import datetime from zomato import utils from django.db import models class Outlet(models.Model): title = models.CharField(max_length=120) cuisine = models.CharField(max_length=120) order_1 = models.CharField(max_length=120) order_2 = models.CharField(max_length=120) foodie = models.CharField(max_length=120, default="admin") slug = models.SlugField(blank=True , null=True) created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title utils.py [Using this the generate unique random slug] import random import string from django.utils.text import slugify def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug Working on the above code to produce random slug, getting error on trying below query. obj = Outlet.objects.get(title='subway') obj.title u'Subway' print(utils.unique_slug_generator(obj.title)) Traceback (most recent call last): File "", line 1, in File "/home/sagar/WORK/DJANGO/virtual_envs/project_2_env/src/myzomato/zomato /utils.py", line 22, in unique_slug_generator slug=slug, AttributeError: type object 'unicode' has no attribute 'objects' -
How to display an added field from the auth_user table in django admin
I added a new 'country' field on the auth_user table via Postgres. I would like in the admin interface, display this new field. I do not want to go through either AbstractUser or Extend the Existing User Model. -
django read dynamic csv file error
I wrote Django python csv reader but not working properly. I can see that file is uploaded to the system but I can't read it and getting the below error: Exception Type: AttributeError Exception Value: 'str' object has no attribute 'read' data = csv.reader(open('tmp/tmp.csv'), delimiter=";") When I am using as per above statically it's working but I need dynamic one that I am receiving via file upload. Needing your help cause I am out of options to solve. I know that decoded_file,io_string and data variables are not working correctly but can't fix it. def upload_csv(request): if request.method == 'POST' and request.FILES['csv_file']: myfile = request.FILES['csv_file'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) decoded_file = filename.read().decode('utf-8') io_string = io.StringIO(decoded_file) data = csv.reader(io_string, delimiter=';', quotechar='|') for row in data: -
Create records for one model using a form in another models template
I have the following models class Alert(models.Model): date_time = models.DateTimeField(default=now) class Response(models.Model): alert = models.OneToOneField('alerts.Alert', related_name='response', on_delete=models.CASCADE) user = models.ForeignKey(User) #Django User Model is_false_positive = models.BooleanField() response_type = models.ForeignKey(ResponseType) #phonecall, sms, email, etc. In the alerts template there's a table with rows for each alert, and each alert has two buttons: One is to create a false positive response, where the response_type field will be empty, And the other one is to create a response where the user must choose the response_type. If the response is a false positive, then it shouldn't be any form (a modal form), otherwise the user show see a modal form to choose the response_type. All the other fields should be filled automatically. I think one way is to create a form for each row and the other way is to create one form and the attribute form="form" for the buttons, but I'm struggling to implement it. What's the best practice to solve this problem? I don't know much about js and ajax but I'm open to other solutions. -
Django+Heroku: compilemessages works but not MY translation file.
I find myself in a very weird situation: I do not have my .mo files committed into my repo. I plan to generate them after I deploy I installed the gettext buildpack availabe at https://github.com/piotras/heroku-buildpack-gettext.git So this are the steps I did: Deploy to heroku. Run heroku run python manage,py compilemessages This is being outputted: processing file django.po in /app/.heroku/python/lib/python3.6/site-packages/django/contrib/redirects/locale/ru/LC_MESSAGES processing file django.po in /app/.heroku/python/lib/python3.6/site-packages/django/contrib/redirects/locale/cy/LC_MESSAGES processing file django.po in /app/prometheus/locale/zh_hans/LC_MESSAGES processing file django.po in /app/.heroku/python/lib/python3.6/site-packages/django/contrib/gis/locale/sk/LC_MESSAGES List one of files: heroku run ls /app/.heroku/python/lib/python3.6/site-packages/django/contrib/redirects/locale/zh_Hans/LC_MESSAGES RESULTS: django.mo django.po List our file: heroku run ls /app/prometheus/locale/zh_hans/LC_MESSAGES/ RESULTS: django.po django.mo is missing. I ran python manage.py shell to see if I have some variables wrong: heroku run python manage.py shell In [1]: from django from django.conf import settings In [3]: print(settings.BASE_DIR) /app/prometheus In [4]: print(settings.LOCALE_PATHS) ('/app/prometheus/locale',) So i have no idea why my django.mo file is not being generated. Any guesses? -
Django select_for_update(nowait) not working on gunicorn
I am running an atomic transaction using the ORM like so (on a postgres db): with transaction.atomic(): my_model_instance = MyModelClass.objects.select_for_update(nowait=True).get(id=site_id) <do some stuff> <some other method calls> my_model_instance.save() Ok so when I run this without using gunicorn (just manage.py runserver 8001 using Django runserver command) it works as expected. When I send in 2 requests at the same time with the same site_id, I get the error I need because for one of those requests, the row is locked. But when I run this on gunicorn with multiple workers, I don't get the error any more. In fact, the nowait seems to have no effect and my requests just waits for the table row to stop being locked. My Question: Is there a difference in running it on multiple workers? Is there another property I need to pass in? Thanks in advance! -
Django-Rest-Framwork 'str' object has no attribute 'id'
I am creating a call in DRF to POST to the site. I am a bit confused why I get this error. I do not understand why this expects it to be a str. I know there are similiar posts but they still elude be to the solution. Error AttributeError: 'str' object has no attribute 'id' [03/Apr/2018 10:55:12] "POST /api/user/UserProfile/1/ HTTP/1.1" 500 83982 serializer.py looks like and if I remove instance.id i get the same error but just for the next line. from rest_framework import serializers from api.models import UserProfile from django.contrib.auth.models import User class UserProfileSerializer(serializers.Serializer): # id = serializers.UUIDField() class Meta: model = UserProfile def create(self, validated_data): return UserProfile.objects.create(**validated_data) def update(self, instance, validated_data): instance.id = validated_data.get('profile_id', str(instance.id)) instance.user_id = validated_data.get('user_id', instance.user_id) instance.save() return instance View @csrf_exempt def user_profile_list(request, user_id): try: userid = user_id except userid.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': uprofile = UserProfile.objects.all().values() list2 = list(uprofile) return JsonResponse(list2, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = UserProfileSerializer(userid, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) urls.py url(r'^api/user/UserProfile/(?P<user_id>[0-9]+)/$', userprofile.user_profile_list), -
Django form not storing values on validation fail
I can't get Django to retain entered form values when validation fails. I have created a test page and used the code in the Django guide, and it still doesn't work. From the Django guide: We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required. And here is my code: #views.py def test(request): if request.method == 'POST': form = NewAwardForm(request.POST) if form.is_valid(): return redirect('/test/') else: form = NewAwardForm() print(form) return render(request, 'test.html', {'form': form}) test.html <form action="/test/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> forms.py class NewAwardForm(forms.Form): recipient_email = forms.EmailField(label='Recipient Email', max_length=100) Can anyone spot my mistake? -
Django: How to filter foreign key in admin detail view
core/models.py from django.db import models from django.db.models.signals import post_save class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30) class Company(models.Model): name = models.CharField(max_length=100) class Entity(models.Model): is_person = models.BooleanField(default=True) person = models.ForeignKey(Person, on_delete=models.PROTECT, null=True) company = models.ForeignKey(Company, on_delete=models.PROTECT, null=True) name = models.CharField(max_length=30) def __str__(self): return self.name @property def title(self): return self.name class Meta: verbose_name_plural = 'entities' def post_save_person_receiver(sender, instance, created, *args, **kwargs): if created: entity, is_created = Entity.objects.get_or_create(is_person=True, person=instance, company=None, name=instance.last_name) # noqa post_save.connect(post_save_person_receiver, sender=Person) def post_save_company_receiver(sender, instance, created, *args, **kwargs): if created: entity, is_created = Entity.objects.get_or_create(is_person=False, person=None, company=instance, name=instance.short_name) # noqa post_save.connect(post_save_company_receiver, sender=Company) class Group(models.Model): name = models.CharField(max_length=20) is_individual = models.BooleanField(default=True) members = models.ManyToManyField(Entity, through='Membership') class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.PROTECT, null=False) entity = models.ForeignKey(Entity, on_delete=models.PROTECT, null=False) class Meta: unique_together = ("entity", "group") For every Company and Person created, an Entity is automatically created where Entity.is_person=True if it's a Person. An Entity can then become a member of a Group such as 'Employee', 'Supplier' and 'Customer' through a ManyToMany relationship in the Membership Model. How do I filter Membership.entity in Admin View (for add and update) that when the Group selected is an 'is_individual=True', such as 'Employee', Entity Field only shows 'is_person=True' Persons in the Entity combobox? Admin … -
AWS EC2 Django runserver problems with port 8000
So I am running an EC2 instance, and I am having a bit of problems. As of right now, the website is functioning, but not properly. Django is listening on 0.0.0.0:8000, and I have port 8000 exposed, and the ports are defined 8000:8000 by default. My EC2 security group has 8000 open for incoming, and I can telnet connect from my EC2. However, when I type my domain name in, domain.com, it does not connect. It connects on domain.com:8000. But I obviously do not want to have that happen, the website should jump right to port 8000. So in the ports setting of my django project, I remapped 80:8000 so that you connect from port 80 client side and that is mapped to port 8000 server side. It is working now, as domain.com connects. However I plan on adding SSL certs and this is most likely not going to work, and this is just not good practice. Are there ways to run multiple manage.py runserver and collectstatic commands as well? Should I be using nginx or is the manage.py runserver 0.0.0.0:8000 command enough? Thanks! -
Altering response in Django Rest
I have a ListAPIView that returns the json response below: [ {'name': 'Andrew'}, {'name': 'Daniel'}, ] I want to alter it so that the response would look like: { "Users": { [ {'name': 'Andrew'}, {'name': 'Daniel'}, ] } } How could I do that? -
Unzipping file submission without storage in Django
I'm currently building an application that will be used and maintained by another developer shortly in the future. What I want is the ability to upload a zip file, unzip and process the contents, and discard the file without ever actually storing it in the Django file storage system. These are the relevant parts of what I have right now: views.py: def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] if str(myfile.name).endswith('.zip'): ## THIS STORES THE FILE -- NOT WHAT I WANT #fs = FileSystemStorage() #filename = fs.save(myfile.name, myfile) uploaded_file_url = str(myfile.name) return render(request, 'webapp/upload.html', { 'uploaded_file_url': uploaded_file_url }) file_error = "There was an error processing the file" return render(request, 'webapp/upload.html', { 'file_error': file_error }) return render(request, 'webapp/upload.html') upload.html {% extends "./base.html" %} {% block content %} <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} {% if file_error %} <p>There was an error in the file submission.</p> {% endif %} </body> {% endblock %} I know that checking if a file ends with .zip is not necessarily indicative of whether it's actually a zip file or not … -
Conditional expressions and subqueries that evaluate to a Boolean (using Exists)
I have hard times figuring out how to use Case, When and Exists in a more complicated query. I have an existing application that I'm working on, so I'm not able to redesign the models. The application uses the contentypes framework, multitable inheritance and django-treebeard. Here are the stripped down models that I have: from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.fields import JSONField from django.db import models class BasePage(models.Model): path = models.CharField(max_length=255) depth = models.IntegerField() numchild = models.IntegerField() slug = models.CharField(max_length=255) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE ) class RootPage(BasePage): translations = JSONField() class ChildPage(BasePage): translations = JSONField() In essence, RootPage and ChildPage inherit both from BasePage using multitable inheritance. The special thing is that both classes have a translations JSON field that stores - in this simple case - a translated slug. What I have to achieve is generating a query that searches for a slug that can be stored in BasePage.slug, RootPage.translated->>'slug' or ChildPage.translated->>'slug'. The thing is that it should return a BasePage queryset instance, no matter if the slug was found in ChildPage or RootPage. Pretty weird, I know. I have fiddled with this raw SQL construct that works so far (and is the code that I'd like to …