0

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)
  • The django admin views happen in a transaction, which are rolled back if an exception is thrown. Does the result page renders normally ? Another possibility could be some mistake we all happen to make : do you query the right database in the shell session ? Is the database writable by the django process ? – vincent Aug 31 '09 at 21:56

3 Answers3

2

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

af.
  • 1,648
  • 1
  • 11
  • 11
  • no you don't - I suspect that `form.cleaned_data['authors']` is a string when it should be a user object – Jiaaro Aug 31 '09 at 14:46
  • 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 Aug 31 '09 at 17:47
  • save_m2m is a ModelForm method, not a model method http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method – vincent Aug 31 '09 at 21:40
1

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

0

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
  • 74,485
  • 42
  • 169
  • 190
  • 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 Aug 31 '09 at 17:54