Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix "WhiteNoise configuration is incompatible"
How to fix this. I try to re config the setting and wsgi. It still had the same Error. -
How to Paginate auto-generated schema endpoint in Django?
from django.conf.urls import url from rest_framework.permissions import AllowAny from rest_framework.schemas import get_schema_view # API schema url(r"^schema/$", get_schema_view(title="API Schema", permission_classes=(AllowAny,))) How would I go about paginating this endpoint? In the official DRF docs here, it states: You can also make the pagination controls available to the schema autogeneration that REST framework provides, by implementing a get_schema_fields() method. This method should have the following signature: get_schema_fields(self, view) The method should return a list of coreapi.Field instances. Im not sure what that means. Im familiar with adding pagination in a View but this is different. djangorestframework==3.8.2 Django==2.2.2 pyton==3.6.8 -
In Django View to template, my date always comes out as Abbreviated month, DD, yyyy yet datepicker makes MM/DD/YYYY
I have a simple view function: def booking_request_list(request): #filter between dates... #or filter if new bookings.. (is booked = false) AND A DATE room_list = Room.objects.all() object_list = HousingRequest.objects.all() return render(request, 'housing/housing_requests_lists.html', {'booked_list':object_list, 'room_list':room_list}) Then in my template I just display the pieces like this: <table class="table"> <tr> <th>Check In Date</th> </tr> {% for hou in not_booked_list %} <tr value={{hou.pk}}> <td> {{hou.checkin_date}} </td> <td><input type="text" value="{{ hou.checkin_date}}" name="checkin_date_{{hou.pk}}" data-date-format="M/dd/yyyy" class="datepicker form-control dateinput form-control" tabindex="6" autocomplete="off" required id="id_checkin_date_{{hou.pk}}" bid="{{hou.pk}}"></td> </tr> {% endfor %} </table> The displayed date for example is: Nov. 11, 2019 In the database it is stored as YYYY-MM-DD The definition of the model is: class HousingRequest(models.Model): objects = models.Manager() room = models.ForeignKey('Room', null=True, blank=True, on_delete=models.CASCADE) user = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) checkin_date = models.DateField('checkin date') This works great when the form first loads, but when the users clicks on the datepicker and selects a date then inside the input box it puts: MM/DD/YYYY I tried above to set the format of the date picker via the data tag and it doesn't seem to take. I also don't know how to just force the date from django in the view to be MM/DD/YYYY (making it work like the date picker since … -
Render Markdown to HTML while preserving headers, newlines, etc.?
Happy New Year! I have started out my new year by making a resolution to get Markdown rendering to HTML working for my Django blog. I came across Django Markdownify and it is pretty OK! I managed to get my markdown file rendered, via get_context_data as described below in installation and usage: views.py class MarkDown(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): markdowntext = open(os.path.join(os.path.dirname(__file__), 'templates/test.md')).read() context = super(MarkDown, self).get_context_data(**kwargs) context['markdowntext'] = markdowntext return context index.html {% load markdownify %} {{ markdowntext|markdownify }} Although basic rendering works, there are some major drawbacks. Including: Inability to recognize headers (e.g. ### in ### My Header gets stripped completely) Poor handling of new lines (whitespace is not respected in any form, but blockquotes work for newlines (>)) These two issues alone are enough to give me pause and seek out an alternative solution for Markdown to HTML in Django. I did open an issue for the header problem and I'll wait to hear back. Until then, if anyone can recommend some Django specific workarounds I'd greatly appreciate it. -
Connecting django to mysql with python 3.6.9
I am trying to connect to mysql with python 3.6.9 and django 3.0.1 on linux lubuntu mysql Ver 14.14 Distrib 5.7.28, for Linux (i686) using EditLine wrapper Currently I'm getting this error message when I run the django server although I have tried to install a mysql client: django.core.exceptions.ImproperlyConfigured: Error loading >MySQLdb module. Did you install mysqlclient? dpkg --get-selections | grep mysql libmysqlclient20:i386 install mysql-client-5.7 install mysql-client-core-5.7 install mysql-common install mysql-server install mysql-server-5.7 install mysql-server-core-5.7 install python-mysqldb install MySQLdb is not it seems supported for python 3 according to this: https://pypi.org/project/MySQL-python/ Is mysql not supported for Django/python 3 yet? I am struggling to find relevant info. after much searching, I have seen many questions on stack overflow about similar issues but with earlier versions of all the software. I have installed pymysql which successfully connects to mysql and retrieves data, but this doesn't seem to be useful for Django. -
Disable or hidden the date options once selected django
Contents: time slots (example: select box or calendar box) Task: ability to book one of the time slots and after submitting the page it should be gone. example:- I want to click on the 'submit' button after the dates are selected. The form submits and redirects back to the same page again but this time not showing up or disable those fields which were selected previously already. After a long research I've come to a solution which can be done via multi-step form. But I have no idea how its done. Kindly need your suggestion on this. How would I approach such problem considering django. If anybody can just help me with the flow. Thank you in Advance -
I get this error when printing pdf in django, the error states like this module "'urllib.request' has no attribute 'splithost'"
I want to print/display pdf from html file in django. I did what I could but i ended up getting an error which i struggled to resolve but couldn't. I need help in resolving this. It states like this " 'urllib.request' has no attribute 'splithost' " My url pattern path('pdf/<int:id>/', views.pdf.as_view(), name='pdf') The views.py is like this: class pdf(View): def get(self, request, id): try: single_record = get_object_or_404(sales, id = id) selling_price = single_record.sales_name.selling_price_per_each * single_record.quantity except: Http404('Content Not Found') context = { 'sales': single_record, 'total_amount': selling_price } sales_pdf = renderPdf('istock/pdf.html', context) response = HttpResponse(sales_pdf, content_type = 'application/pdf') return response The resources (resources.py) file included in views looks like this: from import_export import resources from .models import sales class salesResource(resources.ModelResource): class Meta: model = sales Also the require.py file looks like this: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def renderPdf(template, context = {}): t = get_template(template) send_data = t.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(send_data.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type = 'application/pdf') else: return None and the html file (pdf.html) looks like this: <!DOCTYPE html> <html lang="en"> <head> {% load staticfiles %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta … -
ValueError: The view student.views.stud didn't return an HttpResponse object. It returned None instead
enter image description here ValueError: The view student.views.stud didn't return an HttpResponse object. It returned None instead. In the upper code i am getting the error what should i do?????? -
Return 'initial' after Post method worked - Django
What I want to do: is do my get_initial() to create a model object, then extract data from Post. Conceptually, code does it right, but in reality initial doesnt return and object doesnt creates class StartGame(PermissionRequiredMixin, CreateView): model = Author fields = {'date_of_death'} permission_required = 'catalog.can_mark_returned' def get_initial(self,req): # Get the initial dictionary from the superclass method print("GET INITIAL") initial = super(StartGame, self).get_initial() # Copy the dictionary so we don't accidentally change a mutable dict initial = initial.copy() print(initial) return initial def post(self, request, **kwargs): print("POSTTTT 1") print(self.get_initial()) print("POSTTTT 2") print(kwargs) bb_object = BigBlind.objects.create(bb_sum=request.POST.get('bigblind')) bb_object.save() return HttpResponseRedirect(reverse('catalog:index')) -
Use signup firstname in html profile page
I would like to show a user's firstname on their profile after they successfully signup and create a profile. This is what I have tried in my profile.html page <div class="sidebar-block"> <div class="profile"> <a href="#"> <img src="{% static 'second/images/people/110/guy-6.jpg' %}" alt="your picture" class="img-circle width-80" /> </a> <h4 class="text-display-1 margin-none">{{ Mentor.firstname }}</h4> </div> </div> This is my models.py file #mentor model class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=100) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) linkedin = models.URLField(max_length=200,null=True,blank=True) phonenumber = models.IntegerField(null=True,unique=True) and forms.py class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) firstname = forms.CharField(max_length=100) lastname = forms.CharField(max_length=100) phonenumber = forms.IntegerField(required=True) linkedin = forms.URLField(max_length=200) class Meta(UserCreationForm.Meta): model = User def save(self, commit=True): self.instance.is_teacher = True user = super().save() mentor = Mentor.objects.create( user=user, email=self.cleaned_data['email'], firstname=self.cleaned_data['firstname'], lastname=self.cleaned_data['lastname'], phonenumber=self.cleaned_data['phonenumber'], linkedin=self.cleaned_data['linkedin'] ) return user I know that if I write {{user.username}} I will get the username used to signup but cannot seem to get any other information -
Django value error. model field must be an instance
I get an error when testing address model. This user is suppose to enter address information before getting billed, but it produces a value error that states that the billing field in address model must be an instance of the billing model. This shouldn't be because i already associated the billing model to address model by foreign key. For clarity, here the names for the actual models: BillingProfile and Addresses here is the error produced: ValueError at /cart/checkout/address/create Cannot assign "(<BillingProfile: romeo@gmail.com>, False)": "Address.billing_profile" must be a "BillingProfile" instance. Here is my address view. Error at line 24. from django.shortcuts import render, redirect from .forms import AddressForm from billing.models import BillingProfile from django.utils.http import is_safe_url def checkout_address_create(request): form = AddressForm(request.POST or None) context = { 'form':form } next_post = request.POST.get('next') redirect_path = next_post or None if form.is_valid(): print(request.POST) instance = form.save(commit=False) billing_profile = BillingProfile.objects.new_or_get(request) print(billing_profile) address_type = request.POST.get('address_type', 'shipping') if billing_profile is not None: instance.billing_profile = billing_profile # Value error at billing instance.address_type = address_type instance.save() print('Form saved') else: print('Error: NO billing profile') return redirect('cart:checkout') if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect('cart:checkout') return redirect('cart:checkout') Here are the address and billing models. Address: from django.db import models from billing.models import … -
How to update Django query object in a for loop
I know you can update all Django records matching a filter by using: myQuery = myModel.objects.filter(fieldA = 1, FieldB = 2) myQuery.update(fieldA = 5, FieldB = 6) But if I want to iterate through the query results and only update certain values, how can I do this? I have tried: myQuery = myModel.objects.filter(fieldA = 1, FieldB = 2) for item in range(myQuery.count()) if (myQuery[item].fieldC) == 10: myQuery[item].update(fieldC = 100) This returns AttributeError: 'myModel' object has no attribute 'update' -
Dango 2.2 Reverse for 'activate' with keyword arguments
I have a problem with creating an account and activating it with the link sent in the email. The application is written in Django version 2.2. After clicking the activation link, I receive a message: Reverse for 'activate' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[^/]+)/(?P<token>[^/]+)/$'] Code in urls.py path('activate/<uidb64>/<token>/', account.activate, name='activate'), Code in views.py, code for sign up and activate link. Signup is like a CBV and activate is like a FBV. class Signup(View): def get(self, request): form = SignUpForm() return render(request, 'account/signup.html', {'form': form}) def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Spotted account' message = render_to_string('account/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) user.email_user(subject, message) return redirect('account_activation_sent') return render(request, 'account/signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return render(request, 'account/account_activation_email.html') else: return render(request, 'account/account_activation_invalid.html') In account/account_activation_email.html: {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: … -
Gcloud with cloudbuild and Django Postgres cause psycopg2 ImportError
I am building a Django based application on App Engine. I have created a Postres CloudSql instance. I want to make the CD (conintous delivery) part easy so I created a cloudbuild.yaml file with a Cloud Build Trigger. django = v2.2 psycopg2 = v2.8.4 GAE runtime: python37 The cloudbuild.yaml: steps: - name: 'python:3.7' entrypoint: python3 args: ['-m', 'pip', 'install', '-t', '.', '-r', 'requirements.txt'] - name: 'python:3.7' entrypoint: python3 args: ['./manage.py', 'migrate', '--noinput'] - name: 'python:3.7' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: "gcr.io/cloud-builders/gcloud" args: ["app", "deploy"] timeout: "3000s" The deploymnet is going alright, the app can connect to the database. But when I try load a page I get the next error: "...import psycopg2 as Database File "/srv/psycopg2/__init__.py", line 50, in from psycopg2._psycopg import ( # noqa ImportError: libpython3.7m.so.1.0: cannot open shared object file: No such file or directory" Another interesting thing is if I deploy my app with 'gcloud app deploy' (not through Cloud Build), everything is alright I am not getting the error above, my app can communicate with the database. I am pretty new with gcloud, so maybe I missed some basic here. But my questions are: -What is missing from my cloudbuild.yaml to make it … -
Getting Not Found: / while trying to access Django server from other device in LAN
I am trying to access Django server from outside the device but within LAN. I have exposed my port 8000 for same and then ran - python manage.py runserver 172.30.xxx.xxx:8000 Now, while trying to connect from other device using link http://172.30.xxx.xxx:8000 , I end up getting "The connection was reset" in browser. In the Django console it shows "Not Found: /". But if I try to access the same link from the device where server is running I am able to access. What might be the possible glitch here? -
Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<slug>[-\\w]+)/$']
Using Django 1.11| Having this issue, I thought it was because I copied some urls and views from another project, but even after deleting, the issue reappeared. I just was trying to remove my PostImg field and add a the image field as a FileField, but got issues for not having the postImg field even after deleting the database and all migrations etc. This issue only occurs when I have no posts (not object of the model Post) in my database. I can log into admin no problem, then create a post, and then it works. I think it's because I', displaying all posts with template tags and somehow these tags can't handle it if there are no objects. Note: I had trouble adding slugs, but I found a nice way (I will not have any duplicate blog titles). However, this issue occured even before I added slugs. base.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <script src="//cdn.jsdelivr.net/medium-editor/latest/js/medium-editor.min.js"></script> <link rel="stylesheet" href="//cdn.jsdelivr.net/medium-editor/latest/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <title> Base working </title> <head> <body> <div class="container"> <img class="top_logo" src="https://electrek.co/wp-content/uploads/sites/3/2018/08/SX3Semi-Family-e1534526883239.jpg?quality=82&strip=all&w=1600"> </div> … -
str has no object add in django
Getting this error message when running manage.py AttributeError at /accounts/signup/teacher/ 'str' object has no attribute 'add' This is the code I have written-> forms.py class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) firstname = forms.CharField(max_length=100) lastname = forms.CharField(max_length=100) phonenumber = forms.IntegerField(required=True) linkedin = forms.URLField(max_length=200) class Meta(UserCreationForm.Meta): model = User def save(self, commit=True): user = super().save(commit=False) user.is_teacher = True if commit: user.save() mentor = Mentor.objects.create(user=user) mentor.email.add(*self.cleaned_data.get('email')) mentor.firstname.add(*self.cleaned_data.get('firstname')) mentor.lastname.add(*self.cleaned_data.get('lastname')) mentor.phonenumber.add(*self.cleaned_data.get('phonenumber')) mentor.linkedin.add(*self.cleaned_data.get('linkedin')) return user models.py #mentor model class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=100) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) linkedin = models.URLField(max_length=200,null=True,blank=True) phonenumber = models.IntegerField(null=True,unique=True) and views class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('teachers:app-instructor-dashboard') I get this error message when I try and login as a mentor/teacher. Which should then redirect me to app-instructor-dashboard -
How to use django timezone.now() for the client user
I'm building a journal app, and would like to check if a user posted an entry yesterday when they log in. If they didn't, I'd like to redirect them to the entry page. Here's the code I'm using in my views: if self.request.user.is_authenticated: YESTERDAY = timezone.now() - timezone.timedelta(days=1) try: yesterdays_entry = Entry.objects.get(user=self.request.user, date=YESTERDAY) except Entry.DoesNotExist: return redirect('entry_create_page') In settings.py, I have this set: TIME_ZONE = 'America/Los_Angeles' USE_TZ = True The issue I'm having is when it's checking the time, it's using UTC not the logged in user's timezone. What am I doing wrong here? -
Format django forms using materialize
I have exactly the same problem as in this post. The difference is that I am using django and my form looks like: <form action="/your-name" method="post"> {% csrf_token %} <label> {{ form }} </label> </form> the problem is that the output in html (automatically created) is <li><label for="id_transport_0"><input type="radio" name="transport" value="walking" required id="id_transport_0"> Walking</label> So since the name is not wrapped in <\span> the css does not work. Since that HTML part is created automatically by django, I can't wrap "walking" into <span>...</span> how can I tell django to do it? -
Django List Of ValidationError's Do Not Render Proper HTML
I'm attempting to append errors to a list and raise them in a single ValidationError in Django. I'm looping through "invalid" instances (my custom model) and trying to append the admin_url of each to a list of ValidationErrors (Custom method that returns an anchor tag leading to the change URL of the instance). when the page is loaded, the HTML is not displaying like it should when mark_safe is used. for typ in invalid: errors.append(forms.ValidationError( message=_(mark_safe("Task Type: '%(task_type)s' contains a zero duration task type config and may not be used on a scheduler instance.")), params={ 'task_type': typ.admin_url } ) ) Which results in the following: Task Type: '<a href="/admin/tasks/tasktype/3/change/">Bad Task Type 2</a>' contains a zero duration task type config and may not be used on a scheduler instance. The result I'm looking for is: Task Type: Bad Task Type 2 contains a zero duration task type config and may not be used on a scheduler instance. And here's the admin_url function. @property def admin_url(self): return mark_safe( '<a href="{url}">{display}</a>'.format( url=reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=(self.pk,)), display=self.name or text_type(self.pk) ) ) -
Do I have to run collectstatic every time to serve images when they are uploaded by user?
I have a web app that takes uploaded images and displays it to the user after registration. I have the media and static files separated in respective folders. When I run the app with debug as True, the images are served up to be displayed, but when debug is off, the images don't show. I have tried having the media folder under the static folder and running collectstatic and the images show. But when new images are uploaded, they are not served until the collectstatic is run again. Do I have to keep running collectstatic or there is better to have these folders separated and the images still show?? -
How to Pass Objects to the Main Template in Django?
While its straightforward to pass objects to individual templates that extend my main template, I don't understand how to pass them to my main.html file. Would this require a context processor and/or middleware? Thanks for any tips. -
Django - Custom crispy-forms widget to select from or add-to list
I'm looking for a crispy forms version of this: Django form with choices but also with freetext option? Models.py class Animals(models.Model): animal_id = models.AutoField(primary_key=True) animal_name = models.CharField(max_length=100, verbose_name='Animal Name') forms.py from django import forms from django.forms import ModelForm from .models import Animals class CustomSelection(Field): template = 'custom_selectbox.html' class AnimalsForm(ModelForm): class Meta: model = Animals fields = [ 'animal_name', ] def __init__(self, *args, **kwargs): super(AnimalsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.layout = Layout( Div( Fieldset(CustomSelection('animal_name')) FormActions( Button('submit','Submit') ) ) ) So if I have: custom_selectbox.html {% load crispy_forms_field %} <div class="form-group"> {{ field.label_tag }} {% crispy_field field 'class' 'custom-select' %} </div> this renders a box OK, which is the first thing I want. Next, I would like to know if it's possible to somehow inject all of the existing animal_names, something like this: {% load crispy_forms_field %} <input list="options" name="test-field" required="" class="form-control" id="test-field-add"> <datalist id="options"> {% for option in field.subwidgets %} <option value="{{ option.choice_label }}"/> {% endfor %} </datalist> but with support for crispy-forms. Essentially I want the user to be presented with a list of existing CharField entries - but if the thing they're looking for isn't around, then I want them to be able to add … -
Many to Many: Customize add, set methods prior to save
I have two models: Groups Employees I would like to fill in a potentially blank field on the through (many-to-many) table prior to the execution of add and set. For the bulk_create/bulk_update methods, I can create a custom manager and override those function calls, but when I try doing the same for add and set, my function doesn't get called. I've seen discussion about m2m_changed signals (docs, stackoverflow) but if I understand correctly, signals are only helpful after the save. -
Access serialized_data from Django reversion.Version model using ORM
I am using the Django Reversion library to handle rollbacks to previous state in my project. This has worked great for some years, however, I now have a major app/model name change which breaks the ability to rollback to previous reversion history. In the reversion_version PSQL table, there is a text column serialized_data, which contains a value like: [{"model": "old_app_name.old_model_name", "fields": {"username": "johnny", "first_name": "John", "last_name": "Doe", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2016-10-05T18:10:40.204Z", "groups": [1, 4, 6, 7, 12], "user_permissions": [768, 769, 388], "password": "*****", "email": "john.doe@example.com", "date_joined": "2014-07-28T14:58:49Z"}, "pk": 86}] This causes deserialization to break when trying to restore the old state to "new_app_name.new_model_name". I want to update the json string in reversion_version.serialized_data using the ORM in a django migration. When I try: from reversion.models import Version obj = reversion.Version.objects.first() obj.serialized_data I get <django.db.models.query_utils.DeferredAttribute at 0x7f440441e290>. I tried the following: obj.serialized_data.model #'DeferredAttribute' object has no attribute 'model' obj.serialized_data[0].model # 'DeferredAttribute' object does not support indexing How do I access the json in DeferredAttribute so that I can do something like obj.serialized_data.model or obj.serialized_data['model']?