Piaume
Piaume

Reputation:

Django : save a new value in a ManyToManyField

I gave details on my code : I don't know why my table is empty (it seems that it was empty out after calling save_model, but I'm not sure).

class PostAdmin(admin.ModelAdmin):
    def save_model(self, request, post, form, change):
        post.save()

        # Authors must be saved after saving post
        print form.cleaned_data['authors'] # []
        print request.user # pg
        authors = form.cleaned_data['authors'] or request.user
        print authors # pg
        post.authors.add(authors)

        print post.authors.all() # [<User: pg>]

        # But on a shell, table is empty. WTF ?! : 
        # select * from journal_post_authors;
        # Empty set (0.00 sec)

Upvotes: 0

Views: 2001

Answers (3)

user166648
user166648

Reputation:

I found the solution. I've just changed the value in cleaned_data and it works :

if not form.cleaned_data['authors']:
    form.cleaned_data['authors'] = [request.user]

Thank for helping me. :)

Upvotes: 1

Jiaaro
Jiaaro

Reputation: 76918

I don't know what kind of field you're using, but shouldn't there be one of these in there somewhere? (or something similar)

author = form.cleaned_data['authors']
User.objects.get(id=author)

Upvotes: 0

af.
af.

Reputation: 1668

You need to save the post again, after the post.authors.add(authors).

Upvotes: 2

Related Questions