Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unresolved Imports in VS Code Django Project
I want to open a folder at the level above a Django project directory (project_parent below) in VS Code and have the linter correctly resolve the Django project imports: | project_parent | -- | django_project_dir | -- | -- | manage.py If I do this, the linter is confused and I get a bunch of warnings on imports from the Django modules in the project: unresolved import 'module.models' Python(unresolved-import) If I open VS Code at the the Django project folder level, the linter resolves all of the imports. This isn't ideal though because I have to close and re-open VS Code at the level above to see other related code (Ansible, bash scripts, etc.) My question is how to update VS Code settings to add the Django project directory to the linter path? Env: VS Code: 1.40.1 Python: 3.7.2 Django: 2.2.1 Related question: Pylint "unresolved import" error in visual studio code the solution here is just to open the project at the level of the Django project dir which I don't want to do. my issue is not related to "python.pythonPath" setting, the python path is fine and all of the package level imports are resolved by the linter. -
Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[^/]+)/$']
I am Django newbie and learner, just follow the tutorial and got stuck. When I add a SlugField in django models.py and make a get_absolute_url but the reverse error is coming in navbar. Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P[^/]+)/$'] models.py from django.db import models from django.urls import reverse from django.conf import settings # Create your models here. # Choices CATEGORY_CHOICES = ( ('S','Shirt'), ('P','Pants'), ('J','Jacket'), ('W','Watches'), ('E','Electronics'), ('SO', 'Shoes'), ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger'), ) class Item(models.Model): title = models.CharField(max_length=200) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES,max_length=3) image = models.ImageField(upload_to='images/') slug = models.SlugField() label = models.CharField(choices=LABEL_CHOICES, max_length=1) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:product', kwargs={"slug": self.slug}) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) def __str__(self): return self.item class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() orderd = models.BooleanField(default=False) def __str__(self): return self.user.username -
Django Edit Profile - 'bool' object is not callable
So I just followed this tutorial to create a profile for a user and allow them to edit it but I get this error when I go and visit the edit page 'bool' object is not callable File "C:\Users\...\account\userprofile\views.py", line 64, in profile_edit_view if request.user.is_authenticated() and request.user.id == user.id: TypeError: 'bool' object is not callable models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings class UserProfile(models.Model): user = models.OneToOneField(User, related_name="user", on_delete=models.CASCADE) photo = models.ImageField(upload_to = "account/userprofile/photos", verbose_name="Profile Picture", max_length=255, null=True, blank=True) location = models.CharField(max_length=100, default='', blank=True) website = models.URLField(default='', blank=True) bio = models.TextField(default='', blank=True) @receiver(post_save, sender=User) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm class ProfileEditForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] views.py def profile_edit_view(request, pk): # querying the User object with pk from url user = User.objects.get(pk=pk) # prepopulate UserProfileForm with retrieved user values from above. user_form = ProfileEditForm(instance=user) # The sorcery begins from here, see explanation below ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('location', 'website', 'bio')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: … -
how can I remove hyphen from confirmation links in django?
I am new with django , but I am trying to remove - from the confirmation links however when I tried to apply over models it doesnt work as I want to do it, on the other side the links keeps the same every link. I also tried to save token instead of saving the instance , but the same views def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): with transaction.atomic(): user = form.save(commit=False) user.is_active = False user.save() email_subject = 'Next Step: Activate Your Account' current_site = get_current_site(request) html_message = render_to_string('email/activate.html', { 'user': user, 'domain': current_site.domain, 'token': account_activation_token.make_token(user), }) mail = EmailMessage(email_subject, html_message, to=[form.cleaned_data.get('email')]) mail.content_subtype = "html" mail.send() return JsonResponse({'message': 'success'}) else: return JsonResponse({"message":form.errors}) models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(post_save, sender=User) def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') instance.save() tokens from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() urls http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 13 min http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 20 min http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 45 min http://127.0.0.1:8000/account/activate/5bn-755ea8cee1faa6a91c2b/ # one hour ago -
Bulk insert to mongo DB using threadpool inside a celery task
When I tried bulk insert to mongoDB collection inside threadpool mongoDB memory goes on increase. What is the best way to implement this in a celery task? -
debugging django apps and printing values
Being new to django , I am trying to debug few things and print their values . This is my views.py for the app and here is the code .I tried to print the customers but I get some response which i couldn't understand . class CustomerViewSet(viewsets.ModelViewSet): serializer_class=CustomerSerializer def get_queryset(self): active_customers=Customer.objects.filter(active=True) import pdb; pdb.set_trace() print('active_customers',active_customers) return active_customers I tried the method of importing pdb and printing active_customers in the terminal and here is the response . <QuerySet [<Customer: >, <Customer: >, <Customer: nsxns xn dsnc d>]> Where can I print the values that is sent as response .What are some good ways to trace the flow of data in the django rest framework ? -
Eclipse error 'Tcl_WaitForEvent: Notifier not initialized' Django server stops after hitting a breakpoint 2nd time
Use Eclipse to start django webserver in debug mode, and set a break point. The following sequence with cause Eclipse to unload (webserver stop) the server. Eclipse version: Eclipse Java EE IDE for Web Developers. Version: Neon Release (4.6.0) Build id: 20160613-1800 Sequence: 1) Load a page to hit break point. The page is loaded. 2) Load same page and server will stop. Error in Eclipse console: Tcl_WaitForEvent: Notifier not initialized If not setting breakpoint, all works fine. How to solve the problem? -
Basic tag system using ManyToManyField
I'm writing a simple Django powered notetaking app, and currently I'm implementing basic tagging system for my notes. The requirement is to have a Tag model with added_by field on it as a ForeignKey to User. First I have tried to modify django-taggit source, as well as extend its Tag model, however haven't had any success. So, I decided to implement my own tagging system from scratch. For this purpose I'm using a ManyToManyField: class Note(models.Model): slug = models.SlugField() title = models.CharField(max_length=255) [...] tags = models.ManyToManyField(Tag) This is my form: class NoteForm(forms.ModelForm): class Meta: model = Note fields = [ 'title', 'description', 'notebook', 'tags' ] widgets = { 'tags': forms.TextInput() } Everything renders nicely, but when I try to submit the create form, I get an error: So, inside that TextInput is a comma separated string. I assume that's not what Django expects, but I don't know how to convert that into something Django would accept. I have tried to debug this, but it seems that my form_valid isn't getting executed at all. I have also tried to put some debug statements in clean_tags in my ModelForm, which is also not getting executed. How can I overcome the issue? -
I want help in creating a function for adding items in cart without logging in
I am trying to make a website like any other eCommerce sites and I want add if any user is not logged in then also he/she should be able to add items to the cart. Any help regarding this will be grateful! thank-you very much... -
one more stupid question about django, django templates and django-stars-ratings module
i'm trying to implement a rating system for my Django project I have two models rn, Article and Comment. I'm using Django-stars-rating app (here's the docs: https://django-star-ratings.readthedocs.io/en/latest/) Currently i print ratings for each instance of Article without any issue via {% rating article 10 10 True %} In the docs they say that we can override template via template_name argument in {%%} command, but i don't have any idea how to do this. I've tried this {% rating article 10 10 True widget_custom.html %} but it's now working. By the way, i have comments form for Articles. i want to have opportunity for users to rate article right in comment form, but when i simple add {% ratings e %} to form, user can vote, but score immediately recounts. I'm stucked there for a three days. Help, please. P.S. If anybody knows any solution for creating such a system, please give links, i'll be very grateful. Thanks in advance. -
Include field in form but not model django
In Django I have a modelForm with several text fields and a checkbox field for front-end only use. However, I do not want to add the checkbox field's value to the database with the text field's values when I submit the form. Is there a way to "ignore" a field in a model? -
Django 2.2 Breaking Change with runserver command
Somewhere in the upgrade from 2.1.0 to 2.2.0, the Django command: manage.py runserver begins to require the notebook module, which is a part of the jupyter package. It's unknown why it is needed, and very little documentation exists to justify its inclusion. To move past this issue, we've added jupyter to the requirements, but it is suggested that we find a way to not install jupyter on our production and staging servers. Note: This breaks when upgrading from Django 2.1.14 to 2.2.0 Note: This does not affect the operation of openscout_uwsgi or supervisor Note: This seems to be linked directly with the runserver manage.py command, and by association or inheritance, the runsslserver command Note: This can also be corrected by pip installing the jupyter package, and immediately uninstalling the jupyter package. Uninstalling the jupyter package leaves behind some directories, and a binary executable Note: Our assumption is that it is a django issue, between 2.1 and 2.2, howevver, we can't be certain. It may be an issue buried in dependency list. I.e., Django 2.2 requires package X version Y, which does not correctly require jupyter. The following is the error produced by the ./manage.py runserver command: Traceback (most recent call … -
Foreign key reference disappears on save
In a simple model structure like that: class News(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('News', on_delete=models.CASCADE) I'm having a problem when assigning ForeignKey "parent" field. Its value disappears when I'm trying to save an object: >>> news = News(name='TestNews') >>> book = Book(name='TestBook', parent=news) >>> news.save() >>> str(book.parent) 'News object (2)' >>> book.save() Traceback (most recent call last): File "...\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "...\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: sample_book.parent_id It's there right before saving, but it's gone on save. It works fine when (re)assigning parent after saving the first object, but in the actual project I need to call bulk_save or at least use transaction.atomic >>> news = News(name='TestNews') >>> news.save() >>> book = Book(name='TestBook', parent=news) >>> book.save() >>> book.parent <News: News object (3)> The strangest thing is that I'm sure that it worked the other day with the bulk_save and there is a lot of similar examples in the docs. -
Django prefetch_related
I have a relational model set that has 5 tables each with a one to many relationship. I'm having trouble accessing model information after the 2nd table. ex. class TableA(models.Model): pass class TableB(models.Model): tablea = models.ForeignKey(TableA, oncascade...) class TableC(models.Model): tableb = models.ForeignKey(TableB, oncas...) class TableD(models.Model): tablec = models.ForeignKey(TableC, ...) class TableE(models.Model): tabled = models.ForeignKey(TableE, ...) In my views.py i'm using the prefetch related method on TableA: from . models import * data = TableA.objects.all().prefetch_related('tableb_set__tablec_set__tabled_set') I can't seem to access information from TableC, TableD or TableE. for a in data: print(a.id) for b in a.tableb_set.values(): print(b['id]) for c in b.tablec_set.values(): #This is where I get an error message stating the model doesn't have a relatedmanager How can I access model information 2+ tables deep into the prefetch_related relationship? Thanks in advance -
Can you run a raw MySQL query in Django without a model?
I am still learning Django and I'm just now getting into connectors to MySQL. What I'm trying to figure out is how I would go about querying a db/table that I am not creating with a model in Django. Do I have to recreate the table as a model in order to have it talk to Django? If so, would that basically mean just recreating my structure with a model then importing my data to the new table? Sorry if this is a goofy question, I appreciate any help you can give! -
Are Django Sessions Completely Unique?
I am using Django Sessions to store price for Stripe based on a form input (if this is bad please advise). if form.is_valid(): srv = form.cleaned_data['service'] if srv == 'Silver': request.session['price'] = 999999 else: request.session['price'] = 100000 return redirect('pay-now') Now, obviously, the price is going to be variable, I want to know if sessions are completely unique to each individual, and I won't encounter any errors in terms of people being charged the wrong price based on a previous session store etc. Thanks in advance! -
i am trying to send data through postman and it takes one field null. So anyone can help me in that. And also i am beginner to django
this is the error django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (6, MBBS, Orenburg University, 2019, null). My models is: class Educations(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='edu_user') doctor_degree = models.CharField(max_length=25) university = models.CharField(max_length=25) passing_year = models.IntegerField() def str(self): return self.doctor_degree here the user is for doctor and i'am taking its foreign key in education model and its viewset is: class EducationViewSet(viewsets.ViewSet): def list(self,request): eduss=Educations.objects.all() edu_data_list=[] for edu in eduss: edu_data_list.append({ "doctor_degree" : edu.doctor_degree, "university" : edu.university, "passing_year" : edu.passing.year, "doctor_name" : edu.user.full_name, "doctor_mobile_number": edu.user.mobile_number, "doctor_date_of_birth": edu.user.date_of_birth, "doctor_blood_group": edu.user.blood_group, "doctor_email": edu.user.email }) return Response({"eduss":edu_data_list}) def create(self,request): doctor_degree = request.data.get('doctor_degree') university = request.data.get('university') passing_year = request.data.get('passing_year') user = request.user education = Educations() education.doctor = user education.doctor_degree = doctor_degree education.university = university education.passing_year = passing_year education.save() return Response("successfully saved") -
Django / FactoryBoy - Overriding lazy_attributes
I'm working on a Django project for which I've created the following factory: class PurchaseFactory(factory.DjangoModelFactory): class Meta: model = 'core.Purchase' amount = decimal.Decimal(random.randrange(100, 100000) / 100) ( .... ) user = factory.SubFactory(UserFactory) @factory.lazy_attribute def date(self): if not self.date: return timezone.now() else: return self.date For which I'm running the following test: class TestGetBalanceForPeriod(TestCase): def setUp(self) -> None: self.user: User = UserFactory() self.purchase_1: Purchase = PurchaseFactory( user=self.user, date=timezone.datetime(2019, 11, 1), amount=10 ) def test_test_setup(self) -> None: self.assertEqual(self.purchase_1.date, timezone.datetime(2019, 11, 1)) As you can see I've overridden the date field on the PurchaseFactory with an lazy_attribute. However, in this specific test I'm attempting to set the date myself. I imagined factoryboy would override all values with the values provided by the users, but the test fails with the following error: AssertionError: datetime.datetime(2019, 11, 22, 16, 15, 56, 311882, tzinfo=<UTC>) != datetime.datetime(2019, 11, 1, 0, 0) The first date is the results of the timezone.now() call and not the date that I provided as an input. So far I've been able to override all values on the many factories in our project without problems - but I'm unable to solve this problem. Does anyone know what I am doing wrong? -
using AWS Elastic search with VPC endpoint django haystack
I want to use AWS Elastic-search service with my django application which is running on EC2 instance. For that I use the settings - HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'https://vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com:9200/', 'INDEX_NAME': 'haystack', 'INCLUDE_SPELLING':True, }, } I am not even able to set the connection. Here I am getting this error - raise ConnectionError('N/A', str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError((, 'Connection to vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com timed out. (connect timeout=10)')) caused by: ConnectTimeoutError((, 'Connection to vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com timed out. (connect timeout=10)')) I have updated the access policy to allow the user for edit and list, also in security group add the port 9200 TCP rule. How to connect ec2 with elastic search using VPC. -
Various issues running gunicorn with django app
I'm new to Django. Trying to get my app running under Nginx+gunicorn but running into a few issues. If someone has some insight, I'd appreciate it. I've found a few things to try on google, but gunicorn still seems hosed. 1) I've rsync'd my Django project from my dev box to the Nginx host. If I try launch using the dev server, it doesn't work unless I use Python 3. What have I got messed up? I've googled the ...from exec error below and found I could get it working if prefixed with python3. Seems like a workaround for a larger issue though since this way of starting it isn't mentioned in any of the tutorials I've been following. This bombs: (venv) $ python manage.py runserver 127.0.0.1:8777 File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax This works: (venv) $ python3 manage.py runserver 127.0.0.1:8777 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 22, 2019 - 15:46:59 Django version 2.2.7, using settings 'auth.settings' Starting development server at http://127.0.0.1:8777/ Quit the server with CONTROL-C. [22/Nov/2019 15:47:27] "GET /accounts/login/ HTTP/1.0" 200 1229 ^C(venv) $ 2) Above, I can run the app fine … -
Testing Django Rest Framework: how to test hyperlink relations?
I'm trying to create a true unit test for a customized DjangoRestFramework Hyperlinked related field. But I cannot seem to get around this error: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "relatedtestmodel-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. And here is the unit test, stripped down to simplify the example: from django.conf.urls import url from django.test import TestCase, override_settings from api_tests.models import APITestModel, RelatedTestModel from api_tests.serializers import APITestModelSerializer def dummy_view(request, pk): pass urlpatterns = [ url(r'^relatedtestmodel/?P<pk>[a-zA-z0-9]/$', dummy_view, name='relatedtestmodel-detail') ] @override_settings(ROOT_URLCONF='tests.test_relations') class HyperlinkedRelatedFieldTestCase(TestCase): def setUp(self): self.parent = APITestModel.objects.create() self.child = RelatedTestModel.objects.create(parent=self.parent) assert self.child.parent.id == self.parent.id def test_to_internal_value_correct_error_message(self): queryset = APITestModel.objects.all() serializer = APITestModelSerializer(queryset, many=True, context={'request': None}) expected = [{'foo': 'bar'}] self.assertEqual(serializer.data, expected) I more or less lifted the test from https://github.com/encode/django-rest-framework/blob/master/tests/test_relations_hyperlink.py, because I figured who knows best how to unit test DRF than the makers of DRF? But as it stands, my test refuses to run. Notice in particular that I override the settings with a custom urlpatterns (which is this same file, hence the urlpatterns at the top). So I don't understand why DRF thinks that url name doesn't exist - … -
Django, use Subqueries instead of filtering on QuerySet converted to list
I have two related models: class Execution(models.Model): name = models.CharField("Test Suite Name", max_length=1024) <...> class TestCase(models.Model): name = models.CharField("Test Case Name", max_length=1024) result = models.CharField("Test Case Result", max_length=32) execution = models.ForeignKey(Execution, on_delete=models.CASCADE) <...> I need to compare two executions, devising a list of test-cases which have result discrepancies. My approach feels pythonic enough and works reasonably fast, but I'm pretty sure this can be improved with Django Subqueries (or may be Exists()?) Here is the code I have: execution1 = Execution.objects.get(id=id1) # Executions retrieval (irrelevant to the question) execution2 = Execution.objects.get(id=id2) execution1_testcases = execution1.testcase_set.all() execution1_testcases_names = [testcase.name for testcase in execution1_testcases] for testcase2 in execution2.testcase_set.order_by('-result', 'name'): if testcase2.name in execution1_testcases_names: # TODO: this most likely can be improved with Subqueries result1 = list(filter(lambda testcase1: testcase1.name == testcase2.name, execution1_testcases))[0] else: result1 = None if result1 != testcase2.result: <...> # discrepancy processing -
GraphQL response error message from DRF serializer
I can make CRUD in GraphQL using Django as a backend. My Mutation is meta class is based on DRF serializer. I had search with term DRF, GraphQL, serializer, ... etc. Most of the will be topic related to make the endpoint, but it does not go to detail of response the error message. And most of the time I found DRF without GraphQL answer class Question(models.Model): question_text = models.CharField(max_length=50) class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ( 'id', 'question_text', ) class QuestionSerializerMutation(SerializerMutation): class Meta: serializer_class = QuestionSerializer model_operation = ['crated', 'update'] lookup_field = 'id' class Mutation(graphene.ObjectType): xxx = QuestionSerializerMutation.Field() Body mutation{ xxx(input: {questionText: "a;lsfjkdsajfdsjf;sjfsajdfkd;lsafjl;asfdsjf;lajflsadjf;alsjf;lasfsj"}){ id questionText } } Expected result: GraphQL return the error message from Serializer because my payload is exceed 50 characters As is: No error message raises { "data": { "xxx": { "id": null, "questionText": null } } } Question: How response with serializer.error in GraphQL? -
API view is empty when Filtering django rest framework view by PK in urls.py
I am trying to filter my APIListView by a PK value specified in the url. The code runs however my API is empty even though i know it has data at the PKs that i am testing. Any Ideas? Models.py class Item(models.Model): Description = models.CharField(max_length=20) Price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.Description Serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk', 'Description', 'Price') Views.py (API) class SingleItemAPIView(generics.ListAPIView): serializer_class = ItemSerializer def get_queryset(self): item = self.request.query_params.get('pk', None) queryset = Item.objects.filter(pk=item) return queryset Urls.py urlpatterns = [ path('<int:pk>/',SingleItemAPIView.as_view(), name='single_object_view') ] DRF Output GET /api/1/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [] -
Django Categories and Breadcrumbs Issues
Everything works normally on the admin side. However, I could not show the categories and breadcrumbs on front site. I'd appreciate it if you could help me. models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Post(models.Model): title = models.CharField(max_length=120) category = TreeForeignKey('Category',null=True,blank=True) content = models.TextField('Content') slug = models.SlugField() def __str__(self): return self.title class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name admin.py from mptt.admin import MPTTModelAdmin admin.site.register(Post,PostAdmin) admin.site.register(Category, DraggableMPTTAdmin) settings.py MPTT_ADMIN_LEVEL_INDENT = 20 #you can replace 20 with some other number urls.py path('category/<path:hierarchy>.+', views.show_category, name='category'), views.py def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') parent = None root = Category.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug = slug) try: instance = Category.objects.get(parent=parent,slug=category_slug[-1]) except: instance = get_object_or_404(Post, slug = category_slug[-1]) return render(request, "post/detail.html", {'instance':instance}) else: return render(request, 'post/categories.html', {'instance':instance}) templates/categories.html {% extends 'base.html' %} {% load static %} {% block head_title %} {{ instance.name …