views:

466

answers:

3

Hi,

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)
+1  A: 

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

af
no you don't - I suspect that `form.cleaned_data['authors']` is a string when it should be a user object
Jiaaro
I'm pretty sure af is correct here, post.authors will not be saved to the database unless post.save() is called (which will, in turn, call save_m2m()).
tghw
save_m2m is a ModelForm method, not a model methodhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
vincent
A: 

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)
Jiaaro
Assuming he's using some sort of multi-select widget from the forms, the values coming back in form.cleaned_data['authors'] should be the user ids, so he wouldn't need another call to the database. In either case, his comments make it clear that form.cleaned_data['authors'] is empty, so he's appending the user from the request instead (authors = form.cleaned_data['authors'] or request.user), so it's kind of a moot point.
tghw
A: 

Hi, 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. :)

Piaume