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?
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
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.
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 ).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With