Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset not returning data
I am trying to return only the notes of the currently logged in user. Here is my queryset: def get_queryset(self): qs = Note.objects.select_related().filter(user=self.request.user) return qs I have tried every thing just to return the notes of the logged in use, os maybe queryset is not the right solution. My question is two fold: What is the best way to return the notes of the logged in user. If it is query set, what is the best way to form the queryset. thank you. MODEL User = get_user_model() class Note(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) title = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) text = models.TextField(blank=True, default='') text_html = models.TextField(editable=False, default='', blank=True) created_at = models.DateTimeField(auto_now=True) Views class NoteList(ListView): model = Note def get_queryset(self): qs = Note.objects.select_related().filter(user=self.request.user) return qs -
Use different serializer depending on the authentication method in django rest framework
I'm trying to implement a user profile in django rest framework. Users should be able to request the profile of other users; however, since profiles contain sensitive information, I want to limit the information returned to non-owners and non-authenticated users when they request a profile. I'm looking for a test that I can run inside my view methods that will determine which serializer to use for that request. How can I do this? # models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile') bio = models.CharField(max_length=100) # dob is sensitive and should be protected... dob = models.DateTimeField(blank=True, null=True) My serializers would look like this: # serializers.py # Only for the owner... class ProfileOwnerSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.id') first_name = serializers.ReadOnlyField(source='user.first_name') last_name = serializers.ReadOnlyField(source='user.last_name') class Meta: model = Profile fields = ( 'url', 'id', 'dob', #sensitive 'user', 'first_name', 'last_name', #sensitive ) #For logged in users... class ProfileSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.id') first_name = serializers.ReadOnlyField(source='user.first_name') class Meta: model = Profile fields = ( 'url', 'id', 'bio', 'user', 'first_name', ) #For everyone else... class NonAuthProfileSerializer: ... And I would try to distinguish between them here... # views.py class ProfileDetail(APIView): """ Retrieve a profile instance. """ # Can't user permission_classes bc I want to cater to different classes... … -
exceptions unit testing in django
I am writing unit tests for this code and I was wondering how would someone test any of the exceptions of the code below. thanks. class ExpiringTokenAuthentication(TokenAuthentication): """ Extends token auth with inactivity expiration mechanism. """ model = ExpiringToken def authenticate_credentials(self, key): try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') if not token.user.is_active: raise exceptions.AuthenticationFailed('Invalid user') if token.has_expired(): raise exceptions.AuthenticationFailed('Token has expired') token.last_activity = timezone.now() token.save() return token.user, token -
Setting a parents value in a childs object's model form in Django?
I wish for one of a parent's variables to be pre-populated in a child's model form specifically a serial number. I have managed to get the serial number as part of the URL but would like to figure out how it can be implemented as a variable on the form page. Models.py class Product(models.Model): serial_number = models.CharField(unique=True, max_length=15) class ProductInstance(models.Model): serial_number = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) Views.py class ProductInstanceCreate(CreateView): model = ProductInstance template_name = 'myapp/edit_productinstance.html' form_class = GunInstanceForm def get_success_url(self): return reverse_lazy ('product-detail', kwargs={'pk': self.object.serial_number.pk}) Forms.py class ProductInstanceForm(forms.ModelForm): class Meta: model = ProductInstance fields = '__all__' templates/myapp/product_detail.html ... <a href="{% url 'productinstance_create' serial_number=product.serial_number %}">New</a> ... urls.py urlpatterns += [ url(r'^productinstance/(?P<serial_number>[-\w]+)/create/$', views.ProductInstanceCreate.as_view(), name='productinstance_create'),] templates/myapp/edit_productinstance_form.html {% extends "base_generic.html" %} {% block content %} <h2>Serial Number: {{ serial_number }}</h2> </br> <form action="" method="post"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit" /> </form> </br> <a href="">Back</a> {% endblock %} So currently I can create a URL such as: productinstance/D1430913/create/ I now need to know: How to use it as a variable for the title? How to set the the forms default value to it? -
passing a custom queryset to a serializer django rest framework
I have looked at this submission and there is so much clutter in the code I am having a hard time following it: Pass a custom queryset to serializer in Django Rest Framework Now currently, I am trying to write a serializer that returns a list of all the cities in my table of venues. There may be many venues in each city, but I only want to return the city name once. I know I need to create a custom model manager for this to modify the queryset, but I am unsure how to pass it to the serializer. I am rather lost in documentation and example. Do I need to write sql do I not? This is why not having a mentor really is a pain. -
Django which is the correct way to store discussion inside db?
I use django 11 with postgresql db. I know how store and retrive data from a db but I don't find an example to which is the correct way to store and to retrieve an entire discussion from two users. This is my simple idea: A user connect to 127.0.0.1 and in this page there is a text-area form. The two user can write into the text-area and by press a button they post their content. The page will reload and now all message are display. What I want to know is if the correct way to store and retrive is like: "one db row"="single message user", so if the two user exchange for example 15 messages, into the the db will store 15 row and to make a univocal discussion I can put another column into the db something like "id" discussion, so 15 row with the same id and why not also the username: db row1 ---> "pk=1, message=hello there, user=Mike, id=45") db row2 ---> "pk=2, message=hello world, user=Jessy, id=45") When the page reload clearly in django will be something like discussion=Discussion.objects.all().filter(id=45) to retrieve the discussion. If this is the correct way to store and retrive from the … -
Upload Cropped Image with AJAX in Django
I am trying to upload an image using a image cropper and ajax. When I run locally it works, but in AWS I got an error from form.is_valid(). What could be different locally and in AWS except setting.py? Views.py if request.user.is_authenticated(): if request.method == 'POST': formPhoto = PhotoUploadForm(request.POST, request.FILES) if str(request.user.id) == str(carer_id): if formPhoto.is_valid(): profile = get_object_or_404(Profile, user_id=carer_id) profile_id = profile.id m = Profile.objects.get(pk=profile_id) m.profile_photo = formPhoto.cleaned_data['profile_photo'] m.save() return HttpResponseRedirect('/edit_profile/') Template $('#upload_photo_button').click(function(e){ e.preventDefault(); var b64Data = $image.cropper('getDataURL').replace(/^data:image\/(png|jpg);base64,/, ""); var byteCharacters = atob(b64Data); var byteNumbers = new Array(byteCharacters.length); for (var i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); var blob = new Blob([byteArray], { type: "file"}); var file_name = $('#inputImage').val().split('/').pop().split('\\').pop(); var formData = new FormData(); formData.append('profile_photo', blob, $('#inputImage').value ); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ url: "/{{ user_id }}/upload_photo/", type: 'POST', data: formData, cache: false, contentType: false, processData: false, enctype: "multipart/form-data", success: function(data){ $('#photo').load(document.URL + ' #photo'); $('#photo_profile').load(document.URL + ' #photo_profile'); alert('ok'); }, error : function(xhr,errmsg,err) { alert('{{ csrf_token }}' + ' ' + blob + $('#inputImage').value); // Display the key/value pairs alert('erro'); } }); //done -
Python: is it faster to query clean string value from a db column or cleanup the string on the view/template?
I have a City model and fixture data with list of cities, and currently doing cleanups for URL on view and template before loading them. So I do below in a template to have a URL like this: http://newcity.domain.com. <a href="http://{{ city.name|lower|cut:" " }}.{{ SITE_URL}}"> The actual city.name is "New City" Would it be better if I stored already cleaned data (newcity) in a new column (short_name) on MySQL db and just use city.short_name on templates and views? -
Can I combine {% include %} with custom filter in django 1.11?
First I have created custom filter that makes autoindentation: templatetags/indent.py from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter(name='indent') @stringfilter def indent(value, arg): import re regex = re.compile('^', re.M) return re.sub(regex, ' ' * int(arg), value) and I want to include subtemplate that will be indented by certain number of spaces (eg. 8): Is this allowed in django's templates: {% load indent %} {% include "footer.html"|indent:"8" %} -
After installing OSQA it does not load css and cannot open other pages
I installed OSQA on windows server 2012 using HeliconTech stack. Out of the box it doesn't install properly. Have to change the requirements.txt file to downgrade and/or upgrade some modules. After this, it installs and deploys to IIS. However, when I try to browse the start page it shows the page with no css loaded and request for any other page lands a 404 error. I followed some posts online and tried to setup Django handlers in IIS and also configure static directory. Now, I always get a 404 error when I try to load the start page or any other page. What am I missing ? Any help would be greatly appreciated. If you need more specific details please add in the comments and i would be happy to provide. -
Connecting an external mysql database to django application and querying it
I need to pull data from an external MYSQL database to my application. I have added the below lines to my databases dictionary in settings.py file. 'cust': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cust_data', 'HOST': '', 'USER': '', 'PASSWORD': '' } Is the engine name right? I have added all other details. Now is this it? How can I get the data from this database now? can I simply use an sql query in my applications views.py? Now when I enter shell using below command python manage.py shell When I execute a query to the mysql database, it doesn't work. I am sure I am missing something here. I am struck here, What am I doing wrong here? How can I run a command to access data from a particular table in the above DB. Any help will be appreciated. Thank you. -
Accessing a two dimensional array in Django template
I am building a betting app where users can bet on different games. I want to show users' bets for different games in a table such as one as below: game # | user 1 | user 2 | user 3 game 1 | XXXX | XXXX | XXXX game 2 | XXXX | XXXX | XXXX game 3 | XXXX | XXXX | XXXX ... here's my view users = User.objects.all() games = Game.objects.all() bets = Bet.objects.all() user_bets = [[] for i in range(len(games))] for i, game in enumerate(games): game_bets = bets.filter(game=game) for usr in users: user_bet = game_bets.filter(user=usr)[0] user_bets[i].append(user_bet) data = {'games', games, 'users', users, 'user_bets': user_bets} return render(request, 'bets.html', data) But I don't know how to fill in the table using the 2d array user_bets. Any suggestions? Or if I'm doing the whole thing wrong any best practice to pass such data to template in Django? Cheers -
Why to extend Django User model? + Using One-To-One Link With a User Model (Profile)
this is my first question here, nevertheless S.O. is my main point of reference and support while developing my coding skills with Django. Thanks on advance to all people who is part of SO! My main question is: Under your experience, in which situations you needed to extend User Model? is it a common thing to do? ... all tutorials and blogs I have read says ... "for example, if you want to use an email insted a username". But this doesn't sound like a real reason to me, I haven't found other reasons than this. If I want to use email as username I can create a user-creation form with a field to get username and allowing only emails. This will perfecly solve the problem right? In my case I followed Django official recommendation: it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises. So I did this: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I'm ready, but ready for what? Please enlight me. The second … -
Elasticsearch start error
Elasticsearch version: v5.4.1 OS version: windows 10 Steps to reproduce: Ran elasticsearch from the command prompt LOGS(if needed): [2017-06-21T11:50:11,185][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [] uncaught exception in thread [main] org.elasticsearch.bootstrap.StartupException: java.lang.IllegalStateException: plugins directory [C:\elasticsearch\plugins] not found at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:127) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:114) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:67) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:122) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.cli.Command.main(Command.java:88) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:91) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:84) ~[elasticsearch-5.4.2.jar:5.4.2] Caused by: java.lang.IllegalStateException: plugins directory [C:\elasticsearch\plugins] not found at org.elasticsearch.bootstrap.Spawner.spawnNativePluginControllers(Spawner.java:72) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:167) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:350) ~[elasticsearch-5.4.2.jar:5.4.2] at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:123) ~[elasticsearch-5.4.2.jar:5.4.2] ... 6 more I installed elasticsearch from zip and started with .\bin\elasticsearch.bat -
Django Grapelli add autocomplete lookups on InlineAdmin
I have this 3 models: class MyFile(models.Model): file = models.FileField(upload_to="files/%Y/%m/%d") def __unicode__(self): """.""" return "%s" % ( self.file.name) class ExampleModel(models.Model): attached_files =models.ManyToManyField(MyFile) main_model = models.ForeignKey(MainModel) class MainModel(models.Model): attached_files =models.ManyToManyField(MyFile) And my admin.py as follows: class ExampleModelAdminInline(admin.TabularInline): model = ExampleModel extra = 2 class MainModelAdmin(admin.ModelAdmin): inlines = [ExampleModelAdminInline] Im using django-grapelli because it offer autocomplete lookups for many to many fields. However, Im not sure how to add this autocomplete lookup to a tabularinline admin. Can anyone explain me how to set up the attached_files field to have automplete lookups? -
Django CustomAuth ValueError on user.save
I was trying to make a Custom Authentication model for my project. I have apps called Employee and Department which contains Department and Employee models respectively which are given as: Department(models.py) from django.db import models class Department(models.Model): name = models.CharField(max_length=200) shift_start_time = models.TimeField() shift_end_time = models.TimeField() SHIFT_CHOICES = ( (1,'5 Days Working'), (2,'6 Days Working'), (3, 'Alternate (1-3-5 off)'), (4, 'Alternate (2-4 off)'), ) working_days = models.IntegerField(choices = SHIFT_CHOICES) allowedIP = models.GenericIPAddressField(blank=True, null=True) sick_leaves_allowed = models.IntegerField() casual_leaves_allowed = models.IntegerField() annual_leaves_allowed = models.IntegerField() Employee(models.py) from django.db import models # @author - nickzuck_007 import department # from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class EmployeeManager(BaseUserManager): def create_user(self, collegedunia_email, password) : if collegedunia_email and password: user = self.model( self.normalize_email(collegedunia_email), password = password) user.set_password(password) print (user) user.save(using = self._db) return user def create_superuser(self, collegedunia_email, password): return self.create_user(collegedunia_email, password) class Employee(AbstractBaseUser): employee_id = models.IntegerField(unique = True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) gender = models.CharField(choices = GENDER_CHOICES, max_length=10) personal_email = models.EmailField() joining_date = models.DateField() birthday = models.DateField() anniversary = models.DateField(blank=True) contact_no = models.CharField(max_length=500) address = models.CharField(max_length=500) EMPLOYEE_STATUS_CHOICES = ( ('Full Time', 'Full Time'), ('Intern', 'Intern'), ('Full Time Trainee', 'Full Time Trainee') ) employee_status = models.CharField(choices= … -
Difference between this two generic view
from django.views.generic import CreateView 2.from django.views.generic.edit import CreateView Whats the difference between them ? -
django not identifing ajax, and not able to post
Found on questions on is_ajax- Django request.is_ajax returning false - but that does not solve anything for me. I'm working around this by using 'ajax' in the GET... I'm also trying to post through AJAX, but I can't find the results. My AJAX handler is this: function getContent(pageGet,method,post,target) { if (typeof(post) ==='undefined') post = ""; if (typeof(method) ==='undefined') method = "GET"; if (typeof(target) ==='undefined') target = "body"; pageGet = '/?ajax=home/'+pageGet.replace('?','&'); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { var body = document.getElementById(target); if (this.readyState == 4) { if (this.status == 200) { body.innerHTML = this.responseText; var scripts = body.getElementsByTagName("script"); var script_amount = scripts.length; for( var i = 0; i < script_amount; ++i) eval(scripts[i].innerHTML); } else if (this.status == 0) { getContent('main.html'); } else { body.innerHTML = "Failed with "+this.status; } } }; xhttp.open(method, pageGet, true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(post); return false; } As, I said this never registers in is_ajax, but AJAX is working fine. This is the value of pageGet: /?ajax=home/forms/genericForm.html&form=UserForm and this the value of post: username=sdf&password=dfs&=Submit& Obviously method="POST". This gets to my view.py, and the request.GET is populated properly with 'ajax' (my workaround for the other problem), and 'form'. But request.POST is empty, as well as request.body … -
Django-- Display a message if there is no content in the page
I want to display some text message on the page if there are no content on it. For e.g if the User doesn't have any favorites and the User clicks the my favorite page, I want to display something like "you don't have any favorites" on the my favorite page. This is my model favorite: class Favorite(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) content_id = models.ForeignKey(ContentItem, on_delete= models.CASCADE) Now, if I had OneToOneField instead of Foreignkey, I could have done the following in favorites.html {% if not user.favorite %} <H2>Oops, You don't have any Favorites </H2> Please visit <a href="{% url 'index' %}">our page</a> to make some favorites {% endif %} but it can't be OneToOneField because of course one User can have many favorites. Thanks in advance -
Django order_by on a nested json field
My models are something like this. class Foo(): bar = models.ForeignKey('Bar', related_name='bar') payload = JSONField() class Bar(): candy = models.ForeignKey('Candy', related_name='candy') class Candy(): payload = JSONField() My queryset looks something like this # I want to order by a name on the json field queryset = [ { "id": 1, "payload": {"age": 10, "company": "ccc"} "bar": { 'id': 1, "candy": { "payload": { "names": ["text":"abc", "tag":"foo"], ["text":"abb", "tag":"bar"] } } } }, { "id": 2, "payload": {"age": 12, "company": "aa"} "bar": { 'id': 2, "candy": { "payload": { "names": ["text":"aaa", "tag":"bar"], ["text":"bbb", "tag":"bart"] } } } }] foo = Foo.objects.all() #now I want to order foo by "names.text" This is what I have tried so far foo = foo.order_by(RawSQL("payload->>%s", ("age",))) #this works!! foo = foo.order_by(RawSQL("bar.candy.payload->>%s", ("names[0].text",))) #does not work The second statement does not work. I got inspiration to use RawSQL from here Django 1.9 JSONField order_by I cannot figure out how to navigate to that particular class and then execute the query. What is the best way to do this? -
Deploy Django on AWS Elastic Beanstalk cannot connect to sql server
I'm trying to deploy django on to AWS EB. I have a RDS linked to the instance and database is migrated without any problem. When I log onto the server using ssh and try to create a superuser, I run into following errors. I used the same setup for several other django site, didn't have the same problem. The only difference this time is in the view I'm using native sql, I wonder if the connection.cursor() is causing this problem. In settings I have: if 'RDS_HOSTNAME' in os.environ: print "live site server connection: ", os.environ['RDS_HOSTNAME'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'new_dash', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } /opt/python/run/venv/bin/python manage.py createsuperuser Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check … -
Integrate djngo-spirit in a already django project
i am currently working in an django project and I want to use Spirit as a forum application. I searched for documentation and i found this https://github.com/nitely/Spirit the official django release on github. In its documentation it shows how to run Spirit as a standalone django project, but not exactly what i want as i want to connect it to my already project. I tried to copy the settings from the Spirit folder to my main settings file, create a url to communicate with spirit and create a variable in INSTALLED_APPS. However this doesn't work! Any suggestions, instructions, documentation, tutorial something? Thanks in advance -
How to generate hash in django 1.9 like Invitation Link
I want to send the email to the user that will contains url+hash like this bleow www.mywebsite.com/user/verify/121#$%3h2%^1kj3#$h2kj1h%$3kj%$21h and save this hash against the user in the Database like this ID | Email |Hash 1 | youremail@gmail.com |121#$%3h2%^1kj3#$h2kj1h%$3kj%$21h When the user received the email it should check and compare the hash with it and perform the action as per situation. My question is simple how to generate a unique hash for each user and how to store them in the Database. -
Gunicorn workers are unable to restart after timeout
I have gunicorn serving a django application. Nginx is used as a reverse proxy. And supervisord is used to manage gunicorn. This is the supervisord config: command = /opt/backend/envs/backend/bin/gunicorn msd.wsgi:application --name backend --bind 13.134.82.143:8030 --workers 5 --timeout 300 --user backend --group backend --log-level info --log-file /opt/backend/logs/gunicorn.log directory = /opt/backend/backend user = backend group = backend stdout_logfile = /opt/backend/logs/supervisor.log redirect_stderr = true Sometimes gunicorn workers time out. After that, I expect gunicorn to automatically reload the dead ones. However, the strange thing is under heavy load, some workers cannot get back up saying: Can't connect to ('13.134.82.143', 8030) I think that the workers that timed out are left as a zombie and occupying the ports. What can I do in such cases? -
Django: Update browsable api not updating
I'm overriding the perform_update method in rest_framework.mixins.UpdateModelMixin. I added code to save data from the old object locally, but this query makes the data in the browsable api not update until I reload the page again or make another query. Interestingly, the raw data at the bottom of the page (in the editor) is actually accurate! So only the displayed data in the main content is inaccurate until page reload. The Culprit def perform_update(self, serializer): old_obj = MyModel.objects.get(id=serializer.data["id"]) # new code obj = serializer.save() # ... logic to compare old_obj to obj later Can anybody tell me why the browsable api main content doesn't update but the raw data does?