Django object not saving even after "save" call

django update model field
django save data to database
django model validation
django model get field value
django delete object
django update object
django get id after save
save in django not working

I'm really at a loss because this makes no sense at all. I call save/create an object, and it dosn't show up in the admin site. I even checked the SQLite database with a SQLite Viewer program, which again showed that the item had not been saved.

This is the code that saves the Data object:

        data = Data(represents=field, for_entry=entry, value="This can be anything")
        # field is a DataField db object and entry is a Entry db object (see model below and paragraph)
        print("B4", data) #<---- Shows that Data has not been assigned an ID/pk
        print("8ER: ", data) #<--- Shows that Data has been assigned an ID/pk

As you can see from my comments, I know that the Data object is assigned an ID after the save call, which I would think meant that it worked. No error is thrown anywhere. field, and entry are all both. Each one seems to be ok, as in they have the right IDs, were retrieved with [table name].objects.get(id=...), and I can save/edit them and their saves change.

Even strange, this exact code in a function that is called right before this one works.

This is my (I took out some functions to make it shorter):

class Entry(models.Model):
    parent = models.ForeignKey('Entry', blank = True, null = True, default=None) #  The entry this subs. Is left blank for top level entries.
    id_number = models.CharField(max_length=20)
    visible = models.BooleanField()
    data_field = models.ForeignKey('DataField', default=1)  # The field that this entire entry falls under. REDUNDANT BUT NECISSARY

    def __str__(self):
        return str( "-" + str(self.id_number) 

class DataField(models.Model):
    parent = models.ForeignKey('DataField', related_name='parent field', null=True, blank=True, default=1)
    order = models.IntegerField()
    multiple_entries = models.BooleanField(default=True)
    DATA_TYPES = (('t', 'Text'), ('d', 'Date'), ('l', 'List'), ('o', 'Option'), ('b', 'Boolean'), ('f', 'Foreign Key'), ('r', 'Root'), ('bb', 'Branch'), ('i', 'Image'), ('ff', 'File'), ('h', 'Holder'), ('bt', 'Big Text'))  # A number means it is a foreign key. Should go off title.
    foreign_source = models.ForeignKey('DataField', null=True, blank=True) #  Points to DATA FIELD WHO'S MATCHING DATA WILL MAKE UP THE OPTIONS
    data_type = models.CharField(max_length=2, choices=DATA_TYPES, default='t', null=True, blank=True)
    title = models.CharField(max_length=100, null=True, blank=True)
    visibility = models.BooleanField(default=False)

    def __str__(self):
        return str( + "-" + str(self.title)

    def __eq__(self, other):
        if not isinstance(other, DataField):
            return False
        if self.data_type == 'h':
            return self.title == other.title
        return ==

class Data(models.Model):
    represents = models.ForeignKey('DataField')
    for_entry = models.ForeignKey('Entry', null=True)
    value = models.CharField(max_length=1000000)

    def __str__(self):
        return self.represents.title + "-" + str( + "-" + str(self.value) + "-" + str(

It's possible that I'm missing something obvious, or maybe you need way more information than I can provide to fix it. If there is not enough information, please comment and request more info, or just list possible issues that could be happening.

I had a similar issue doing a unit test and encountered an error where it appeared the save method wasn't working --> was as follows

p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, value) 
myfunc()  # Code that changed the same object p is referencing
self.assertEqual(p.my_attr, new_value)

The above failed even though I changed the object being referenced to the new value and then did .save() on the object.

To fix the issue, I had to reassign p to the MyModel object. My fixed code in the unit test looked something like this.

p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, value) 
myfunc()  # Code that changed the same object p is referencing
p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, new_value)

It appears to be an issue with the variable pointing to an old location in memory, but I only started programming 5 months ago so I'm in a little over my head :) I would really appreciate feedback if anyone can explain why this is happening as I'm still stumped.

If you REALLY don't think the save method is executing, you can do a sanity check by overwriting the save method and add a print statement. It might look similar to the following:

class MyModel(models.Model):
    attr = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        print('Did this attribute update? (attr):', self.attr)
        print('Save method executed!')

EDIT: Inline with the memory location theory, I made this simple example:

In [3]: a = 1
In [4]: b = a
In [5]: hex(id(a))
Out[5]: '0x100240280'
In [6]: hex(id(b))
Out[6]: '0x100240280'
In [7]: a = 2
In [8]: b
Out[8]: 1
In [9]: hex(id(a))
Out[9]: '0x1002402a0'
In [10]: hex(id(b))
Out[10]: '0x100240280'

Would still love to hear anyones thoughts.

#27017 (Why doesn't Django's save only the dirty , I've noticed that will update all fields by default, which can Calling save() on a new model instance without a PK (when inserting a record for the  To save an object back to the database, call save(): Model. save ( force_insert=False , force_update=False , using=DEFAULT_DB_ALIAS , update_fields=None ) ¶ If you want customized saving behavior, you can override this save() method.

Try a manual commit. I don't know what else to suggest.

from django.db import transaction

def viewfunc(request):

Model instance reference | Django documentation, validFrom.__class__ <type 'str'>. And here it is obvious that the object stores the DateField as string, even after saving. Now let us investigate it after retrieving it  You can find out about the full API in How to use sessions (Django docs). Saving session data. By default, Django only saves to the session database and sends the session cookie to the client when the session has been modified (assigned) or deleted. If you're updating some data using its session key as shown in the previous section, then you

Use django refresh_from_db() function in the object you need to be updated.

#12401 (DateField/DateTimeField is not instantiated with Python , The form field's label is set to the verbose_name of the model field, with the first If it's not supplied, save() will create a new instance of the specified model: > Depending on how the form is rendered, the problem may not even be visible on​  The same invalidation happens if the client storing the cookie (e.g. your user’s browser) can’t store all of the session cookie and drops data. Even though Django compresses the data, it’s still entirely possible to exceed the common limit of 4096 bytes per cookie. No freshness guarantee

I had the same issue. I solved it by assigned the object to a new variable, making my changes and saving the new variable:

    location = self.location  # self.location is set by other methods
    location.is_active = True

Creating forms from models | Django documentation, If you assign auto-primary-key values manually, make sure not to use an When you save an object, Django performs the following steps: report that a row was updated even if the database contains a row for the object's primary key value. Django object not saving even after “save” call. Ask Question Asked 6 years, 11 months ago. Active 1 month ago. Viewed 4k times 4. I'm really at a loss because

save - django - Python documentation, .save() is not working for me either with models or with forms in after you call save()? If yes, have you tried adding code after the save() to retrieve the object by pk? added to Table mytable, even though Sequences id table Getting Python Django 'SERVER_PROTOCOL' TypeError: 'NoneType' object is not subscriptable Django form not saving even after everything seems all right does not work django view but works in python , I am attempting to geocode an address and save the results to the model using django's save method. The method is being called, but any  m2m_changed ¶ django.db.models.signals.m2m_changed¶ Sent when a ManyToManyField is changed on a model instance. Strictly speaking, this is not a model signal since it is sent by the ManyToManyField, but since it complements the pre_save / post_save and pre_delete / post_delete when it comes to tracking changes to models, it is included here.

Model save() method not saving changes to database · Issue #1421 , Basic data access Once you've created a model, Django automatically provides a high-level Python API for working with those models. At this point, p1 is not saved to the database yet! # Now it is. from django.db import models  I'm new to Django and Django CMS, but I'm developing a plugin for displaying uploaded images with some text. The plugin works well, but I would like for the user to upload an image and then have actions performed on it before it is stored (specifically, to modify the image size and resolution to create uniform file sizes on the server without relying on frontend css).

  • Is AUTOCOMMIT set to false by chance and the other function is doing an explicit commit?
  • Please provide a code that you're executing i.e. the snippet where the save() method fails. It'd be easier if we could see what exactly parameters for save() are.
  • @pkacprzak Unfortunately, they're set in a completely different part of the program (that interacts with several other parts. So, probable 60+ lines of code). From every test I've been able to do, it seems that they are valid database objects of the DateField and Entry class. The last argument (the value) can be a basic string and it still will not work.
  • My advise is to enable logging and check the log file as every SQL statements generated can be logged there. Then you can see how Django is attempting to save.
  • That doesn't make sense. Did you check the logs? What is the statement that is being generated? Are you saying it's not being generated or not being sent to the database?
  • Thanks for all your help. I just ended up uninstalling and reinstalling django to a new vertualenv with the latest version of python (I WAS using python3.2). Then I copied over all of my code. I don't know why, but it worked. Maybe I messed something up in the settings file. Thanks again!
  • Hmm, I'm just glad it worked for you. Guess we'll never find out why it wasn't working...
  • Format your code and describe more so your answer be more clear