Alan Weng
Alan Weng

Reputation: 656

Model field not updating in admin page even if value changes

I apologize for my confusing title but I hope the code explains it better. In my views.py file I have the follow view

def create_view(request):
     context = {}

     form = CreateForm(request.POST)

     if request.method == "POST":
         if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            instance.author.profile.participating_in = Post.objects.get(
                title=instance.title
            )
            instance.save()
            print(instance.author.profile.participating_in)

     context["form"] = form
     return render(request, "post/post_form.html", context)

when I print out the value of instance.author.profile.participating_in it shows up in my terminal however when I check the admin page it doesnt update at all. I'm sure I messed up somewhere silly but I cant seem to find it. Thanks!

Upvotes: 1

Views: 365

Answers (1)

NKSM
NKSM

Reputation: 5854

participating_in is the profile model field, but you are not calling the save() method for profile anywhere.

You have to do it like the following:

profile = instance.author.profile
profile.participating_in = Post.objects.get(title=instance.title)
profile.save()

If participating_in is ManyToManyField then we can do it like this:

post = Post.objects.get(title=instance.title)
instance.author.profile.participating_in.add(post)

Note that add(), create(), remove(), clear(), and set() all apply database changes immediately for all types of related fields. In other words, there is no need to call save() on either end of the relationship.

Look at Related objects reference

Upvotes: 1

Related Questions