Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get saved object of a model form in Django?

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?

like image 860
orhanodabasi Avatar asked Feb 04 '17 02:02

orhanodabasi


People also ask

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What does form Save () do in Django?

form. save() purpose is to save related model to database, you are right. You're also right about set_password , for more info just read the docs. Django knows about model and all it's data, due to instance it's holding (in your case user ).


1 Answers

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)
like image 133
trixn Avatar answered Sep 30 '22 18:09

trixn