Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: run a function before accessing the media through url
I am writing a django project. In my project, there will be pictures that is not stored in the database, but on the media folder. Everyone can just type http://mywebsite/media/pictures.jpg to view the pictures. What should I do if I want to run a function first before user access to the media url? Scenario: User type http://mywebsite/media/pictures.jpg and press enter Run a python function in backend, for example simply print out the username Print the username User can finally go to the url to view the picture without knowing there is a function just ran -
Django editing data and showing info as form field in my model
I am trying django and stuck here. by the way i am new to django So when i want to click on Edit button which is in table next to a person's record I want to pass id to access info of that person which I click to my model and show info as values in form fields.I am using form in a model. I am trying to edit a person's info. How can I do it I am using simple ORM. I am not using a Model form. Sorry I am not allow to add pics yet. -
How to access ImageField Object and display it to template
I'm having trouble accessing the data from db that should have images. How can I access them and then render them to the template. #models.py class Pic(models.Model): image = models.ImageField(upload_to='cover/pdfs', null=True, blank = True) #forms.py class ImageForm(forms.ModelForm): class Meta: model= Pic fields= "__all__" #views.py def dash(request): try: _id = request.session['client']['id'] except: return redirect("/loginPg") userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id'])) theUploads = Pic.objects.all() print("This image object -", theUploads) #for pic in theUploads: #print("MyPc", pic["image"]) content = { "title" : userBio.title, "qA" : userBio.quoteA, "qB" : userBio.quoteB, "desc" : userBio.desc, "authorA" : userBio.authorA, "authorB" : userBio.authorB, "pictures" : theUploads } return render(request, "GoEnigma/dashboard.html", content) I have heard of Pillow and seen the documentation. I am confused on how that would assist the problem. If there is any ideas on this, I would gladly take them. -
How to get Wagtail/Django to add my relationship table for many-to-many relationship
I'm running Django, Wagtail, Puput to set up a basic blog. I'm trying to set up a many-to-many relationship between the blog pages and documents, so that each blog page can have an unlimited number of attachments. I believe I've set everything up correctly. I added a class for the table: # models.py class AttachmentEntryPage(models.Model): attachment = models.ForeignKey( Document, related_name="+", verbose_name=_("Attachment"), on_delete=models.CASCADE, ) page = ParentalKey("puput.EntryPage", related_name="entry_attachments") panels = [DocumentChooserPanel("attachment")] def __str__(self): return str(self.document) I added an inline field to a class that replaces the puput blog entry page abstract: # models.py class IPDEEntryAbstract(EntryAbstract): body = RichTextField(verbose_name=_("body")) tags = ClusterTaggableManager(through="puput.TagEntryPage", blank=True) date = models.DateTimeField( verbose_name=_("Post date"), default=datetime.datetime.today ) header_image = models.ForeignKey( get_image_model_path(), verbose_name=_("Header image"), null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) categories = models.ManyToManyField( "puput.Category", through="puput.CategoryEntryPage", blank=True ) attachment = models.ManyToManyField( "wagtaildocs.Document", through="ipdesite.AttachmentEntryPage", blank=True, ) excerpt = RichTextField( verbose_name=_("excerpt"), blank=True, help_text=_( "Entry excerpt to be displayed on entries list. " "If this field is not filled, a truncate version of body " "text will be used." ), ) num_comments = models.IntegerField(default=0, editable=False) video_url = models.URLField( null=True, blank=True, help_text=_(f"Paste a YouTube link."), ) And I added a content panel to allow the document to be chosen: # models.py content_panels = [ MultiFieldPanel( [ … -
I can not display the number of comments
I want to display the number of comments (count) on the main page (index page) for articles. I have two models: comments, post and views post_detail, post_list. models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True, db_index=True ) slug = models.SlugField(max_length=200, unique=True, ) def get_absolute_url(self): return self.slug class Comment(models.Model): post=models.ForeignKey(Post, on_delete=models.CASCADE) content= models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post).order_by('id') return render(request, {'post': post, 'comments':comments, }) class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 On the article page (post_detail), using tag {{comments.count}} the number of comments I receive successfully . But trying to get the number of comments on posts on the index page (postList), nothing comes of it. I tried {{post.comments.count}} - nothing worked. -
TypeError: create() takes 1 positional argument but 2 were given; Django REST Framework
I'm encountering a problem when trying to create a model instance from deserialized/validated data. As shown, a TypeError is raised when the implementation of self.create() is invoked when within Serializer.save(). I can't figure out what the second argument would be that is causing the error. Here is the validated_data argument passed to the function... {'gender': {'MALE'}, 'size': {'LARGE', 'MEDIUM'}, 'age': {'ADULT', 'BABY'}, 'user': <User: Mock>} File "C:\...\rest_framework\serializers.py", line 191, in save self.instance = self.create(validated_data) TypeError: create() takes 1 positional argument but 2 were given tests.py class TestSetUserPreferences(TestCase): '''Verify that an User receives a 201 status code when setting preferences on their profile.''' @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( username="Mock", password="secret" ) cls.credentials = b64encode(b"Mock:secret").decode("ascii") cls.user_settings = json.dumps({ "gender": ["MALE"], "size": ["MEDIUM", "LARGE"], "age": ["BABY", "ADULT"] }) cls.factory = APIRequestFactory() def test_user_preference_settings_success(self): request = self.factory.post( reverse("user-pref-settings"), data=self.user_settings, content_type="application/json", headers = { 'HTTP_AUTHORIZATION': f"Basic {self.credentials}" } ) force_authenticate(request, self.user) response = SetUserPrefView.as_view()(request) self.assertEqual(response.status_code, 201) views.py class SetUserPrefView( GenericAPIView, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin): queryset = UserPref.objects.all() serializer_class = UserPreferenceSerializer def post(self, *args, **kwargs): import pdb; pdb.set_trace() self.create(self.request, *args, **kwargs) def perform_create(self, serializer): return serializer.save(user=self.request.user) serializers.py class UserPreferenceSerializer(serializers.Serializer): gender = serializers.MultipleChoiceField(choices=USER_PREF_DOG_GENDER) size = serializers.MultipleChoiceField(choices=USER_PREF_DOG_SIZE) age = serializers.MultipleChoiceField(choices=USER_PREF_DOG_AGE) def create(self, **validated_data): user = UserPref.objects.create(**validated_data) -
Modify Django's QueryDict to Proper Python Dictionary
I am trying to convert Django's Querydict to a normal python dictionary but it's not working perfectly. I tried with json.loads() but at someplace where there's no value, it is considering there also as value exists. -
Reverse for 'login' not found. 'login' is not a valid view function or pattern name error no matter what url I try to visit
I am trying to reuse an account app(manages signup/login/registration using class-based views) I created in one project, to another project. account/urls.py: from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'account' urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name = 'login'), path('logout/', auth_views.LogoutView.as_view(), name = 'logout'), path('password_change/', auth_views.PasswordChangeView.as_view(), name = 'password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name = 'password_change_done'), # reset password urls: path('password_reset/', auth_views.PasswordResetView.as_view(), name = 'password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(), name = 'password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name = 'password_reset_complete'), ] If I try to access any of those URLs, the error will be the following: NoReverseMatch at /account/<url>/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. In template /Users/justinobrien/Desktop/recipeSite/website/templates/base.html, error at line 12 The only line that changes is the NoReverseMatch at /account/<url>/. I do not mention the login view in my very primitive base.html, so I am not sure where that is coming from (file at project_root/templates/base.html): {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Website</title> {% block head %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> </html> Other files I think may be important: project_root/urls.py: from django.conf.urls import … -
Unit Test Page That's Only Accessible By Redirect
Ive made a series of pages which I need users to access sequentially. The enforce this I used the following logic which will send a user back if they try to skip pages (possibly by entering the url into the address bar). if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page_two'))): return redirect('page_two') This works fine. Prior to adding this constraint I had unit tests such as this def test_logged_in_user_uses_correct_template(self): user = User.objects.create_superuser('username') self.client.force_login(user) response = self.client.get(reverse('page_two')) self.assertTemplateUsed(response, 'example/page_two.html') self.assertEqual(response.status_code, 200) But these tests are now failing because the unit tests fail the test and are redirected. My question is how can I unit test these pages by accessing them as if they were redirected from a certain page (so they will pass this code) if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page_two'))) Thank you. -
djangosaml authentification fails (certificate error)
I'm trying to implement a shibboleth login for a django app with djangosaml2. As soon as I try to log in, I get an 'Authentication Error'. The log file contains an xmlsec error: 'unable to get local issuer certificate'. Do you have any idea what causes this error? If any additional config files or logs are needed, i will gratefully provide them. -
How do I resolve IntegrityError: NOT NULL constraint failed?
I try to let user add comments to blog post am making... When I run makemigrations and migrate, everything seemed fine . The form displayed well but shows the following error when I fill the form and click on the submit button. Django.db.utils.IntegrityError: NOT NULL constraint failed: blog_comment.author_id Am new to Django and following a tutorial. The tutorial doesn't have users except the super user. I learnt about users and so I let user register to use the blog. The tutorial provided a name field in the form so commenter can enter their name. Here, I want to use the current user for this field(see my models.py below to see how I have done this). Any help to solve this will be appreciated. models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) comment = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.author} on {self.post}' forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) views.py login_required def post_detail(request, post, pk): post = get_object_or_404(Post, id=pk, slug=post, status='published') comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = … -
Why does Django 3.0.6 generate the urlpatterns variable using the url() function instead of the path() function
After creating and checking I am running a Python 3.6.1 virtual environment and have Django 3.0.6 installed, I created a project. Within this project the urls.py file is as shown: from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] However, the Django 3 documentation says the following: "urlpatterns should be a sequence of path() and/or re_path() instances."(https://docs.djangoproject.com/en/3.0/topics/http/urls/#syntax-of-the-urlpatterns-variable) Can anyone explain this? From my understanding the url() function is outdated/will be depreciated. I believe I am supposed to be using path() but I am not sure. -
How do I resolve this error "message": "Endpoint request timed out" when deploying a Django application to AWS via lambda?
I'm deploying my Django application (backend) to AWS via lambda, but each time I deploy and get the live link, I get the error below: { "message": "Endpoint request timed out" } I have configured the VPC. I have also set the "timeout_seconds": 900, which is the max time that AWS Lambda supports. But the error persists. How can I resolve this, please? -
Django is not showing media files in development but it is in production
The users profile pictures are loading fine on https://rossdjangoawesomeapp2.herokuapp.com/ but when I use http://localhost:8000/ none of them are loading. The problem only occurred when I uploaded my site to Heroku / AWS. I tried un doing some of the changes to the code. I tried getting it back to a state where localhost was working fine. But then I ended up coming into more error messages. I found this Django is not serving static and media files in development but it is serving in production but unfortuntely it didn't help me. And my difficulty now is I don't really know where to begin looking for advice on how to fix the issue. Settings.py """ Django settings for django_project3 project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') #SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on … -
__str__ returned non-string (type ImageFieldFile)
I am trying to print the db to see if the image saved properly when submitting the upload of an image. I get this error, str returned non-string (type ImageFieldFile), when printing the db. I have already looked at other problems on the platforms, they don't seem to match the fix for this problem. What am I missing for correctly submit this image to the db? Here's the code. #models.py class Image(models.Model): image = models.ImageField(upload_to='cover/pdfs', null=True, blank = True) def __str__(self): #forms.py from .models import Image from django import forms class ImageForm(forms.ModelForm): class Meta: model= Image # "__all__" takes all the fields. please helps with the exception error fields= "__all__" return self.image #views.py def upload(request): context = {} userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id'])) if request.method == 'POST': dataBinder = ImageForm(request.POST or None,request.FILES or None) if dataBinder.is_valid(): dataBinder.save() pics = Image.objects.all() context = { "imageFeed" : pics } print("RIght here.. ", pics) else: print("Not a valid input from form....") context = { "imageFeed" : "There was an error" } print("There was an error") return render(request, "GoEnigma/dashboard.html", context) This goes below my urlpatterns #urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Define my root for media #settings.py MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, … -
Django 3, the simplest mistake. Error in the template, how to fix?
I have ajax processing through data I pass id and I want to pass this id to url. but I get this error enter image description here <div class="review_delete text-danger"></i><a href="{% url 'news:delete_review' `+data['id_comment']+` news.id %}" class="text-danger"><i class="fas fa-trash-alt mr-2"></i>Видалити</a></div> If you simply squeeze into the tag <p> + data ['id_comment'] + </ p>, then everything works fine -
Stripe Security Concern on Django
Is there a security issue created by having the clientSecret of Stripe's PaymentIntent API stored in plaintext in the client-side HTML? I'm new to web development and integrated Stripe's PaymentIntent API by following this tutorial: https://stripe.com/docs/payments/accept-a-payment. Unfortunately, they didn't have a guide that was Django specific. The guide was for flask. I did my best improvisation, but I didn't want to go through the trouble of making a specific endpoint for passing PaymentIntent's clientsecret. Instead, I defined a clientSecret variable that I store in plaintext on the client-side via {{ clientsecret}}. To provide some background, I'm using Django 3.0 with django-oscar 2 and python 3.6. The Stripe guide states, "The client secret should still be handled carefully because it can complete the charge. Do not log it, embed it in URLs, or expose it to anyone but the customer." I don't believe I'm doing this, but I'm afraid that by defining it as a variable that the webpage is given by Django, there is some sort of logging. I'm using https so I believe there are some boundaries against the contents of the webpage being exposed, and it's definitely not exposed in the URL itself. Let me know what you … -
Django project media working with s3 locally, but not on Heroku
I've been struggling with this issue for over 2 days now--and it's driving me insane. I'm storing static files (css/js) and user profile images for my app covidgapyears.com in a covid-gap-years s3 bucket and using that to serve both my local and production builds. When I pg:pull the data from production and run it locally, the static files and media files (images) work just fine, including adding images through the app and having them sent to the bucket. However, in production whenever you log in as a user you cannot see your profile photo. Not even the default.jpg is showing up, just an empty placeholder showing there's been an error. Last time the src for the production image was s3.../bucket-name/picture-name_weirdextrastuf2n23au.jpg?... and with some changes to settings.py now it is... "unknown". I have read several SO posts on this including this and this, to no avail, as I don't think it's the same problem. The relevant code is below, but I should add I really don't understand what STATIC_ROOT, STATIC_URL, MEDIA_ROOT, MEDIA_URL, STATIC_LOCATION, MEDIA_LOCATION even do in this context--despite reading all the docs, and have really been blindly filling those bits in via trial-and-error. settings.py # AWS ACCES INFORMATION FOR S3 … -
Is there a specific way to reference templates for widgets in django?
I created my own widget which inherited from the Widget class which functions much like a Select widget. Only it was causing the page to take ages to load. Thus started a debugging session which has resulted in the following discovery. When my form uses the native Select widget - which I've copied into one my own python modules so i can change it - it loads fast. According to the django debug-toolbar the page load is about 500ms. But when I change the template_name and option_template_name to my own templates which have been changed to include exactly the same code it takes ages again like my original custom widget, about 5500ms. # Here is the beginning of the Select Widget class which i've copeied into my own widgets.py module. class Select(ChoiceWidget): input_type = 'select' template_name = 'django/forms/widgets/select.html' option_template_name = 'django/forms/widgets/select_option.html' add_id_index = False checked_attribute = {'selected': True} option_inherits_attrs = False Then i make two changes only - as outlined above. class Select(ChoiceWidget): input_type = 'select' #template_name = 'django/forms/widgets/select.html' #option_template_name = 'django/forms/widgets/select_option.html' add_id_index = False checked_attribute = {'selected': True} option_inherits_attrs = False # input_type = 'select' template_name = "purchases/input_with_dropdown.html" option_template_name = "purchases/dropdown_options.html" # option_inherits_attrs = False # checked_attribute = {'data-selected': … -
Using Ajax and Django - right way to pass json back to the template page
I'm new to anything javascript and ajax, Python and Django, I can usually do the simple stuff to show model data on a web page, and fill forms etc. I'm just trying to figure out how Django, python and javascript work together and thought I would try to use jvectormap as a learning example. When the mouse moves over the map, Ajax sends the country code and the country name to the view, and the view updates the model and records where the user clicked. Then below the map the country code and country name is shown. That works. I want also send the animals in that country that was clicked back to template and show them below the map. I use the country code filter the National_Animals model. The queryset can be more than one animal for a country and convert that to a list into json. My confusion is how to send that information (the json list of animals) back to the template. In the script in the template page, I have the 'search_term' and 'the_name' listed in the ajax data. Do I need to list all the keywords for the animals I want to send back? Or … -
Dynamic content not updating after form submission in JavaScript
It shows after I hit the save button again, so basically it's a step behind, it updates the database but loads after second click. Something is definitely wrong with my code : const fetchTweets = async () => { let tweets = await axios.get(url); return tweets.data.response; } Then a function which is being called on page load: const showTweets = async () => { let tweets = await fetchTweets(); let list = '' let tweetsElement = document.querySelector('#tweets') for(let tweet of tweets) { list += tweetFormat(tweet); } tweetsElement.innerHTML = list; } showTweets() But when I submit handle the form using this, it won't update the page even though I am calling showTweets() function: const tweetFormElement = document.querySelector('#tweet-create-form'); document.addEventListener('submit', (event) => { event.preventDefault(); const formData = new FormData(event.target); const url = event.target.getAttribute('action'); const method = event.target.getAttribute('method'); axios({ method: method, url: url, data: formData }).then((res) => { console.log(res); }) showTweets() // <-- calling it here }); The data shows on the page when I click submit again, but then it updates the database TWICE. Please if someone could help. -
Creating Products with Stripe API in Django
Creating my first proper website and trying to connect Stripe for payments. Their API doesnt seem very dynamic(im probably reading wrong tho). Trying to integrate their checkout page. Im confused on how to make multiple products at once. Tried to loop through my OrderItems: def checkout(request): customer = request.user.customer order = Order.objects.get(customer=customer) items = order.orderitem_set.all() for item in items: stripe.Product.create( name = item.name description= item.desc ) stripe.Price.create( product= product.id, unit_amount=int(order.get_cart_total), currency='gbp', ) But was stuck on how to declare the product ID for Price.create Was also confused on this part of their API: session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price': '{{PRICE_ID}}', 'quantity': 1, }], mode='payment', success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='https://example.com/cancel', Ive not hosted my site on anything yet so what can I set the URLs to? and where does Checkout_session come from? Cant find any info thats up to date on this so I apologise for asking whats probably not a great question but not sure what to do. Thank you! -
Creating a list of CustomUserModel
I want to create a list in a template of my CustomUserModel which has a OnetoOne field with a model called customer as shown below class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Customer(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = … -
Move Django Admin/Auth to SQL Server with custom schema
I am using the default Django authentication, session, and admin backend. However, I want to migrate to my own SQL Server set up. Seems simple, right. Well, this has already been done once in the current database. I don't want to override those tables and mess up another project. I would like all of these new tables that are going to be added to have a schema pre-fix. So instead of the standard dbo.auth I would have myschema.auth. I would love help on how to migrate from the standard SQLite with Django to SQL Server while specifying a schema for these admin/auth, etc. tables. Thanks! -
get root node in Django model with foreign key
I would like to get the root node of the tree in the model below: # model.py class Note(models.Model): note_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) parent_note = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, related_name='subnotes') Note_1 Note_2 Note_3 Note_4 So if select e.g. Note 3, I would like to get Note 1 like this: n3 = Note.objects.get(pk=3) n3.get_root() result should be: <QuerySet [<Note: Note_1>]> Code below returns all parent nodes of a given node. I need only root (highest) # models.py ... def get_parents(self): if self.parent_note is None: return Note.objects.none() return Note.objects.filter(pk=self.parent_note.pk) | self.parent_note.get_parents()