Get saved object of a model form in Django?
Asked Answered
F

1

8

I just want to access model details just after posting it with model form in Django. This guy also had asked the same thing but when i try the accepted answer, it returns none type value.

Here is my code in 'views.py':

if request.method == 'POST':
    if request.user.is_authenticated():
        form = PostStoryForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.author = request.user
            new_post = obj.save()
            print(new_post)

The Code above saves the form to the database successfully but 'new_post' variable is 'None'. For example when i tried to access 'new_post.title' which is a field in my model, it returns 'AttributeError' which says 'NoneType' object has no attribute 'title'

what am i doing wrong?

Fortis answered 4/2, 2017 at 2:21 Comment(2)
I think we need to save your form too.Crean
The models save() does not return the instance as the forms save() method does.Inhibition
I
10

The models save() method does not return the instance

obj.author = request.user
obj.save() # this does not return anything. It just saves the instance it is called on.

Your instance already has the author set.

To access auto populated fields that haven't been set yet, you will have to fetch it from the database again after saving. This is the case, when the instance you called save() on did not already exist before.

new_obj = MyModel.objects.get(id=obj.id)
Inhibition answered 4/2, 2017 at 2:35 Comment(4)
The instance is obj. You can try print(obj.title), which should work fine.Tripe
Actual model has 3 more fields like 'modification date' or 'creation date' or 'url' -which i can access by 'get_absolute_url' method and these fields are saved database automatically: "modified = models.DateTimeField(auto_now=True)". Without saving form model, i cant access these extra fields. So i cant access 'modified' field like this: 'obj.modified', because it hasnt been created yet. is it clear?Fortis
Yes, but the save() method does not return the instance and it also doesn't update the fields on the instance it is called on. If you want to access these fields you have to fetch the object from the db again.Inhibition
But in your case where you created the object already through the save method of your form these fields should already have been populated.Inhibition

© 2022 - 2024 — McMap. All rights reserved.