Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the field value from django orm
I am trying to get the field value of a joined table. This is the generated sql of ORM query. SELECTsubnets_subnetoption.id, subnets_subnetoption.subnet_id,subnets_subnetoption.value_id, subnets_subnet.id,subnets_subnet.parent_id, subnets_subnet.base_address,subnets_subnet.bits, subnets_subnet.bcast_address,subnets_subnet.is_physical, subnets_subnet.name,subnets_subnet.responsible, subnets_subnet.building_floor,subnets_subnet.comments, subnets_subnet.vlan_common_name,subnets_subnet.creation_date, subnets_subnet.modification_date,subnets_subnet.sec_level, subnets_subnet.confid,subnets_subnet.access_type, subnets_subnet.zone_type,options_value.id, options_value.content,options_value.comment, options_value.option_id,options_option.id, options_option.name,options_option.required, options_option.scope_id,options_scope.id, options_scope.nameFROMsubnets_subnetoptionINNER JOIN subnets_subnetON (subnets_subnetoption.subnet_id= subnets_subnet.id) INNER JOINoptions_valueON (subnets_subnetoption.value_id=options_value.id) INNER JOIN options_optionON (options_value.option_id= options_option.id) INNER JOINoptions_scopeON (options_option.scope_id=options_scope.id) WHERE subnets_subnetoption.subnet_id` = 1 SubnetOption.objects.select_related().filter(subnet_id=subnet['id']).query I need only options_value.content and options_option.name, but query set i giving the subnetoption table values only. How can I get the joined tables values. I am new to django -
Django Error Logging: Adding request header, body and user information
Looking for a way to add header, body and a user's email address in my error log along with the stack trace of the exception in my views.py After scouring the web for hours, many suggested to write my own middleware and some suggested to log that sort of information into a separate log. However, knowing where your code went wrong solves one part of the problem, identifying which poor soul it affected and what request data was sent during that exception goes a long a way in rectifying the issue. Having that information in the same log file just makes sense to me. Currently in my views.py, I have this simple setup: from django.db.models import Min, Max, Q, F, Count, Sum from django.db import connection from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect from myapp.models import * import logging logging.basicConfig(filename="errors.log", level=logging.ERROR, format='%(asctime)s: %(message)s') def random_view(request): if request.user.is_authenticated() and request.user.is_active: # generic view code goes here. else: return HttpResponse(status=401) This setup worked well for a while. Every time there was an exception, it would log out the time, the exception error message and the stack trace. How can I also add in request.META, request.user.id and request.body along with stack … -
Custom model for authentication in django restframework instead of default user model
I want to do some custom auth for my users with username or email with password. At the first time of logging with email and password the api should return me the respective user token. For all other operations with the api I need to make use of token, which I get at time of login. And I need a custom model to store all user info like username, password, phone, email, token etc. How to achieve this in django restframework. Please guide me to achieve this. Thanks in advance. -
Caching in Django - don't quite understand what's happening
I've an eCommerce platform and it's the usual List and Detail style website where the main page lists all the products and if you click on each one it'll bring you to the page with that product's details. The thing is now when I update a product on the backend, strangely only the Detail pages get updated but the main shop List page never gets updated anymore. This is happening even when I tried deleting an item, the item still appears on the main page but when I try to navigate to the item, the detail page throws a 404. I scoured through the code and made sure there were errors in the code. My questions are: Is this a caching issue? If so, why is it only happening now and not previously? I'm not fully aware of how caching works with HTML pages, would it have something to do with the fact that I've more products on the site now and the increasingly bloated size of the shop List page caused certain issues? Any tips to point me in the right direction would be greatly appreciated! -
Django getting dictionary value for template:
I am creating a form for which I am displaying several text boxes with data pre-populated from the database. If I edit the fields and leave one of them blank, I am sending a dictionary of current values from my view to the template and then while displaying the boxes, I want to get the most recent value of the text boxes from the dictionary if the id matches the ones in the dictionary. I created a template tag as follows: @register.filter def get_item(value, arg): value.get(arg) and them I am doing the following in the template for the input value {% with choice_id=choice.id %} {% with box_text=dict|get_item:choice_id%} value='{{ box_text|default:option.text }}' {% endwith%} {% endwith%} where option is the model object I have verified that dict is indeed a dictionary by iterating through the items and printing key value pairs. But I get the error str' object has no attribute 'get' at {% with box_text=dict|get_item:choice_id%} Why is it considering my dict as a string? Is there a better way to do this? -
Iterating over a list of django created objects in Javascript, is it possible? Template language in Javascript
My site can't run a successful for-loop created in django for a list model that I have sent to a page. I was going based off of Derek's answer in this stackoverflow question and some other things I found. But right now... It seems that my browser (Google Chrome if that helps) can't seem to render the {% for %} loops that I attempt to run in javascript on my html file. I have two python/django created two list models, booklist_greek and booklist_latin that are sent to my textlist.html file. These lists contain sorted 2-tuples, each tuple having the title of a book as the first element and the type of the book as a second element. Using template-language in html to run a for loop works just fine at two parts in my html file. There's a point in my code where I would like to filter booklist_greek and booklist_latin based on the booktype of each book, and use that to populate a <select> element. This filtering and populating needs to happen when a user clicks buttons. So I assumed javascript would be necessary... But I also needed template language to somehow filter the lists. I approached it like … -
Django 1.11: post form data to database
I am making a super-minimalistic blogging application as a first project. I'm having trouble getting my form's CharField to show up on the page, and I'm having trouble finding a concise explanation as to how I'd put that form data into my database. forms.py: 1 from django import forms 2 3 class ContentForm(forms.Form): 4 form_post = forms.CharField(widget = forms.TextInput) views.py: 1 from django.shortcuts import render 2 from django.http import HttpResponse 3 from .forms import ContentForm 4 from .models import Post 5 6 def post(request ): 7 #testvar = "TEST VARIABLE PLZ IGNORE" 8 post_list = Post.objects.order_by('id') 9 10 return render(request, 'posts/main.html', 11 {'post': post_list}, 12 ) 13 14 def content_get(request): 15 16 if request.method == 'POST': 17 18 form = ContentForm(request.POST) 19 20 return render(request, 'main.html', {'form':form}) main.html: 1 <head> 2 <h1>Nanoblogga</h1> 3 4 </head> 5 6 <body> 7 {% for i in post %} 8 <li>{{ i }}</li> 9 {% endfor %} 10 11 12 <form action = '/' method = 'post'> 13 {% csrf_token %} 14 {{ form }} 15 <input type = 'submit' value = 'Submit' /> 16 </form> 17 </body> I appreciate your input. -
pycharm recnoizes import yet still ValueError: Attempted relative import beyond toplevel package django project on make migrations
look at this photograph... (everytime I do it makes me laugh.... lol I had to what a terrible band..anyway) I am trying to import the views.py file from my venue directory into the urls.py file in the suitsandtables directory which is on the same level as my venue directory. Each one of these directories has a __init__.py file which is empty. Pycharm is all happy yet I still get the ValueError: Attempted relative import beyond toplevel package error. Which is starting to drive me insane. Can we fix this nonsense? Gracious -
Updating a csv file by overriding admin save method django
This is the admin.py file class AddFeatureAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): with open('features.csv', 'w') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(obj.Feature) obj.save() admin.site.register(AddFeature,AddFeatureAdmin) models.py class AddFeature(models.Model): Feature = models.CharField(max_length = 100) With every feature value added in admin, I want to write it to a csv by clicking the admin save button. -
Fetch API for Django POST requests
I'm trying to remove jQuery from a React/Redux/Django webapp and replace the $.ajax method with the Fetch API. I've more or less got all my GET requests working fine and I seem to be able to hit my POST requests, but I cannot seem to format my request in such a way as to actually get my POST data into the Django request.POST object. Every time I hit my /sign_in view, the request.POST object is empty. My entire app's backend is built around using Django forms (no Django templates, just React controlled components) and I would really like to not have to rewrite all my views to use request.body or request.data. Here is all the code I can think that would be relevant, please let me know if there's more that would be helpful: This is the curried function I use to build my full POST data and attach the CSRF token: const setUpCsrfToken = () => { const csrftoken = Cookies.get('csrftoken') return function post (url, options) { const defaults = { 'method': 'POST', 'credentials': 'include', 'headers': { 'X-CSRFToken': csrftoken, 'Content-Type': 'application/x-www-form-urlencoded' } } const merged = merge(options, defaults) return fetch(url, merged) } } export const post = setUpCsrfToken() This … -
How to overcome host not repond and url error in django?
I have follow this tutorial http://web.stanford.edu/~zlotnick/TextAsData/Web_Scraping_with_Beautiful_Soup.html but I still fail to get output. Below is my code in view.py def index(request): #html="a" #url= requests.get("https://www.python.org/") #page = urllib.request.urlopen(url) #soup = BeautifulSoup(page.read()) #soup=url.content #urllib3.disable_warnings() #requests.packages.urllib3.disable_warnings(InsecureRequestWarning) #url=url.content #default_headers = make_headers(basic_auth='myusername:mypassword') #http = ProxyManager("https://myproxy.com:8080/", headers=default_headers) r = urllib.request.urlopen('http://www.aflcio.org/Legislation-and-Politics/Legislative-Alerts').read() soup = BeautifulSoup(r) url= type(soup) context={"result":url,} return render (request, 'index.html',context) Output: urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond -
uWSG and DjangoI: No module named 'wsgi.py'; 'wsgi' is not a package
I was having an issue with this resulting in No Module named 'encodings'', but I resolved that by instead of just usinguwsgito run it, by specifying it explicitly in my virtualenv/home/dev/.venvs/app/bin/uwsgi. Now the server actually runs but I get the500 - Internal Server Error`. I think this is related to my directory structure, which isn't an issue with Django's dev server, but now is becoming one that I am referencing wsgi.py. I followed the "Two-Scoops" preferred method, so my directory structure is this: app-demo app config settings base.py dev.py staging.py wsgi.py manage.py I am testing it on a CentOS server and have wsgi.py as os.environ.setdefault("DJANGO_SETTINGS_MODULE, "settings.staging"). The staging.py just imports base.py. These are some snippets that I have in the base.py that are probably the most relevant: import os import sys from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(3) ROOT_URLCONF = 'config.urls' WSGI_APPLICATION = 'config.wsgi.application' Just not quite sure the best way to resolve the issue. Oh and this is the bash that I run to activate it: /home/dev/.venvs/app/bin/uwsgi --http :8000 --home /home/dev/.venvs/app --chdir /home/dev/app-demo/app/config -w wsgi.py -
Testing Django Channels background task end-to-end
I am trying to perform end-to-end tests of my Django app which uses Channels and Websockets. In my case a request triggers a complex background calculation and I would like to observe the effects of it. As far as I understand, in the Django test suite there is no way of running workers, which will consume the background tasks of Django Channels. Is there any way of triggering however the background tasks with the right parameters? Do I have to modify my code to make it testable? The following is simplified skeleton of my setup: views.py def calculation(request): # doing some simple calculation depending on request simple_result, parameter = simple_calculation(request) # trigger complex asynchronous calculation depending on parameter Channel('background-calculations').send({ "parameter": parameter, }) # return results of simple calculation return render(request, 'simple_reponse.html',{'simple_result': simple_result}) routing.py channel_routing = [ route("background-calculations", run_background_calculations), route("websocket.connect", ws_connect), route("websocket.receive", ws_message), ] consumers.py def run_background_calculations(message): # perform complex calculation depending on parameter from simple calculation result = complex_calculation(message) # update frontend via websocket Group("frontend-updates").send({ "text": json.dumps({ "result": result, }) }) @channel_session def ws_connect(message): message.reply_channel.send({"accept": True}) Group("frontend-updates").add(message.reply_channel) @channel_session_user def ws_message(message): message.reply_channel.send({ "text": message.content['text'], }) When I try to access the view with a client (e.g. REST APIClient) I do receive … -
How to Fix Code Smell in These Django Models?
I have some Django models that don't feel right to me and I'm not sure how to fix the problem. What I'm doing is creating a promotion code form for a website. When a prospective to member to the site signs up for an account, if they enter a valid promotional code and I haven't met my membership drive goal, their membership will be extended an additional number of days. If the promotion code is valid but I've already met my membership drive goal, I'll extend their membership by a smaller number of days. If the promotion code is not a valid code, I'll print an error message on the Enter Promotion Code form. Some promotions are goal-based and some are time-based, meaning that I either want to allocate promotion codes to the first X members who sign up or allocate a code good for anyone who signs up during a given time period. Here are my models: # models.py class Promotion(models.Model): """A promotion""" type = models.ForeignKey('PromotionType') description = models.CharField(max_length=128) goal = models.IntegerField(default=0, null=True, blank=True) met_goal = models.BooleanField(default=False) end_date = models.DateField(null=True, blank=True) still_running = models.BooleanField(default=False) extra_days = models.IntegerField(default=0) alt_extra_days = models.IntegerField(default=0) class PromotionType(models.Model): """A type of promotion Events ('event') - … -
Django - Create a new List of running totals from existing list
How would I go about creating a new list of running totals from another list? Let's say I have the following query: sumbl4 = LaborDetail.objects.filter(businessunit='Birmingham').filter(endofweek__gte=datetime.date.today()-datetime.timedelta(days=60)).values_list('endofweek').annotate(hours__sum=Sum('hours')).order_by('endofweek') sumbl3 = json.dumps(list(sumbl4), cls=DecimalJSONEncoder) And my data is in this format (sumbl3): [["2017/04/23", 972.5], ["2017/04/30", 1076.5], ["2017/05/07", 1162.5], ["2017/05/14", 1055.5], ["2017/05/21", 981.0], ["2017/05/28", 945.5], ["2017/06/04", 912.0], ["2017/06/11", 1106.0], ["2017/06/18", 1059.0]] So my new list would look like: [["2017/04/23", 972.5], ["2017/04/30", 2049],... Note: I am using Python 2.7 -
Django cannot retrieve url parameter
I'm trying to retrieve a url parameter as part of a simple query within Django but calling kwargs from within the view.py seems to return an empty value (e.g. self.kwargs[name] returns a blank/empty value), it seems Im not picking up the 'name' parameter from the url? Im pretty new to Django so expect I'm doing something dumb? my code: URL pattern - works fine. urlpatterns = [ url(r'^contacts/$', ContactList.as_view()), url(r'^contacts/search_name/(?P<name>\w{0,50})$', ContactDetail.as_view()),] view: class ContactDetail(generics.ListAPIView): serializer_class = ContactSerializer def get_queryset(self): return Contact.objects.filter(name=self.kwargs['name']) -
how will i get data from template form
i create a form in the template with html, i suppose i must use formset, but i cant handle it for days. i want to these values to a text which will save the database like str(value1)+str(value2)+str(value3)+str(value4)+str(value5) there is no code in forms.py, i couldnt figure what will i write, probably it must be formset but i cant. views.py @login_required def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.ders_bilgileri) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Bilgileriniz başarıyla güncellendi!')) else: messages.error(request, ('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.ders_bilgileri) kac_ders_var=request.user.ders_bilgileri.dersler.split() return render(request, 'uyelik/detay.html', { 'form': profile_form,'kac_ders_var':kac_ders_var }) detay.html (template) {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} <script src="{% static 'js/buton.js' %}"></script> {% block body %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <form id="demo"> <input name="prefix-INITIAL_FORM_COUNT" value="1" type="hidden"> <input name="prefix-TOTAL_FORM_COUNT" value="3" type="hidden"> <fieldset disabled class="empty-form" style="display: none"> <fieldset> <label for="id_prefix-__prefix__-name">Ders</label> <input type="text" name="prefix-__prefix__-name" id="id_prefix-__prefix__-name"> <button type="button" data-formset-remove-form> delete </button> </fieldset> </fieldset> <fieldset class="forms"> {% for i in kac_ders_var %} <fieldset> <label for="id_prefix-{{ forloop.counter0 }}-name">Ders</label> <input type="text" name="prefix-{{ forloop.counter0 }}-name" id="id_prefix-{{ forloop.counter0 }}-name" value={{i}}> </fieldset> {% endfor %} </fieldset> <fieldset class="controls"> <button type="button" data-formset-add-form> add field </button> <br> <button type="submit" name="emptylayerbtn">Save</button> <br> </div></div></div> {% endblock%} javascript function … -
How to fix NoReverseMatch at/blog/ Django 1.8 Url
I cant figure it out how my code doesnt work, trying to display post_detail.html, NoReverseMatch at /blog/ Reverse for 'post_detail' with arguments '(2,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/$post/(?P\d+)/$'] Here my code: blog.views.py def post_list(request): posts =Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'blog/post_list.html', {'posts':posts}) def post_detail(request, post_pk): post = Post.objects.get(pk=post_pk) return render(request, 'blog/post_detail.html', {'post': post}) blog.urls.py app_name='blog' urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<post_pk>\d+)/$', views.post_detail, name='post_detail'), ] urls.py urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/$', include(blog_urls, namespace='blog')), ] post_list.html {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} < -- here is the error <h1><a href="{% url 'blog:post_detail' post.pk %}">{{post.title}}</a></h1> <p>published by: {{ post.published_date }}</p> <p>{{post.author}}</p> <p>{{post.text|linebreaksbr}}</p> {% endfor %} {% endblock%} -
Django Models: Using DateField to set parameters in FileField
Background: I'm am creating Django app to manage receipts. The user will create a new Receipt, fill out some fields with information on the receipt (i.e. cost, items, date purchased, etc.), and upload a copy of the receipt for storage. Problem: I want to store the receipt *.pdf files in a folder based on the purchase date the user enters, however, I do not have access to self.date.strftime('%Y %B') until after instantiation. Example Code: class Receipt(models.Model): date = models.DateField() item = models.CharField(max_length=128) scan = models.FileField(upload_to='scans/{d}/'.format(d=date.strftime('%Y %B')), max_length=100) Research: This SO question needs to do something similar, but for a different reason. The answer that he got, was this it was not possible without overriding the save() method. How would that work with file uploads? What are my work-around options? -
Modify field on related model in django rest serializer
I'm trying to extend the user model with a profile using the method in this answer. My idea is to only send the profile object whenever a request about a user is made to the api. I have accomplished this as follows: # views.py class ProfileDetail(APIView): """ Retrieve or update a profile instance. """ permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) ... def get(self, request, pk, format=None): ... # Only allow owners to update a profile def put(self, request, pk, format=None): profile = self.get_object(pk) if request.user != profile.user: raise PermissionDenied serializer = OwnerProfileSerializer( profile, data=request.data, context={"request": request}, ) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And my serializer looks like this: #serializers.py # Serializer for the owner of profile object class OwnerProfileSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.id') first_name = serializers.ReadOnlyField(source='user.first_name') last_name = serializers.ReadOnlyField(source='user.last_name') email = serializers.(source='user.email') class Meta: model = Profile fields = ( 'url', 'id', 'dob', 'bio', 'town', 'gender', 'image', 'user', 'first_name', 'last_name', 'email', ) I would like the owner to also be able to modify user object fields, such as first_name, last_name, email, etc. However I have not found a (e.g.) ReadWriteField in the DRF serializers docs. How could I accomplish this? If possible I want all the modification to be carried … -
Django, JWT Tokens encoded without using SECRET_KEY?
I have a SECRET_KEY defined in my settings.py However, every token my system generated is easily decoded on public services like: http://jwt.calebb.net/ or https://jwt.io/ How is that possible? -
Looping through form fields in django with select multiple
class form(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user') u = User.objects.get(user=user) super(form, self).__init__(*args, **kwargs) self.fields['phone'].queryset = Phone.objects.filter(user=u) class Meta: model = MyModel fields = ["name", "description", , "phone"] This form pre-populates the field phones with phones that belong to the currently logged in user. I got the template to display using {{ form.as_p }}, but I dont know how to manually display the fields with the pre-populated phone names to be chosen, in an html template. I tried the snippet below as part of the bigger form, but it did not work. <select multiple="multiple" id="id_phone" name="phone" required> {% for p in phone %} <option value="{{ p.id }}">{{ p.name }}</option> {% endfor %} </select> Also, how can I allow a user to choose multiple phones at once with this pre-population method. I tried to use ModelMultipleChoiceField but it did not work. -
Module not found error while in django
File "C:\Users\Aditya\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_shop-0.10.2-py3.6.egg\shop\models\product.py", line 12, in <module> from polymorphic.manager import PolymorphicManager ModuleNotFoundError: No module named 'polymorphic' I am trying to make a online shop project using certain instructor's video.I am newbie to django and dont know what seems to be the problem.My models.py file looks like this. I am using the command python manage.py makemigrations from django.db import models # Create your models here. from django.core.urlresolvers import reverse class Category(models.Model): name=models.Charfield(max_length=200, db_index=True) slug=models.Slugfield(max_length=200, db_index=True, unique=True) class Meta: ordering=('name',) verbose_name='category' verbose_name_plural='categories' def__str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) Class product(models.Model): category=models.ForeignKey(Category, related_name='products') name=models.CharField(max_length=200, db_index=True) slug=models.SlugField(max_length=200, db_index=True) image=models.ImageField(upload_to'product/%Y/%m/%d',blank=True) description=models.TextField(blank=True) price=models.DecimalField(max_digits=10, decimal_places=2) stock=models.PositiveIntegerField() available=models.BooleanField(default=True) created=models.Datetimefield(auto_now_add=True) updated=models.DatetimeField(auto_now=True) Class Meta: ordering=('-created',) index_togetther=(('id','slug'),) def__str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id,self.slug) -
Efficiently retrieving and sorting an object list according to external parameters (Django)
In a Django project, I have two lists of tuples. Each tuple in both lists comprises a (user_id, epoch_time_of_joining) pair. The first list is a list of all users. The second list is a list of new users, only containing ids who joined in the past 24 hours. FYI, the list of all users contains new users too, and both lists are sorted according to epoch_time_of_joining (they're actually Redis sorted sets). E.g.: all_users = [('16', 1489044722.035625), ('5', 1489561316.306984), ('104', 1498151886.155885), ('3', 1498158931.476488), ('2', 1498158953.978909)] new_users = [('3', 1498158931.476488), ('2', 1498158953.978909)] The task is to get a unified object list of all user objects via the Django ORM, such that it's sorted by the newest users first. I also have to paginate the results when they swell beyond 100. Lastly, I have to keep track of the newest users in this unified list, so that I can display a "new" label in front of them in the interface. What would be the most efficient to accomplish the aforementioned task? I haven't been able to entirely wrap my head around doing it efficiently. I am currently trying: # COMBINE THE TWO LISTS, DROP TIME, BUT KEEP SORTING INTACT combined_users = [] for … -
mptt and django, name not appearing in admin
http://django-mptt.github.io/django-mptt/models.html Hi there I'm following the tutorial above, I'm not sure how to get Node Object to show its name instead of just Node object, there is a side by side comparison of what I'm aiming for (on the right) with what I have on the left. Side by side comparison of problem Below is the code from admin.py, if you the problem lies elsewhere let me know and I can share. Thank you, Nicky from __future__ import unicode_literals from django.contrib import admin from mptt.admin import MPTTModelAdmin class CustomMPTTModelAdmin(MPTTModelAdmin): model = Node mptt_level_indent = 20 list_display = ('name', 'parent', 'level',) admin.site.register(Node, MPTTModelAdmin)