3

Is there any documentation on this? I couldn't dig any up.

I have a custom ModelForm for creating articles. Whenever I use this form, I pass in an article instance so that I can automatically set the author:

    article = Article(author=req.user)
    form = ArticleForm(req.POST, instance=article)

How do I access this instance/article variable from inside form.save()?
Is there anything else I need to be aware of when writing this method? Or does it just need to return an article and that's pretty much it?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 1
    similar question: http://stackoverflow.com/questions/817284/overriding-the-save-method-in-django-modelform – miku Dec 07 '09 at 19:54
  • I guess the answer I'm looking for is: `article = super(ArticleForm, self).save(commit=False)`. – mpen Dec 07 '09 at 20:01
  • 1
    Post the answer and accept it... it'll help everyone else, and give you a badge probably :) – John Weldon Dec 07 '09 at 20:07
  • Ok... I'll accept it after the mandatory 2 day waiting period, but in the meantime, is there a way to check if `save()` is updating an existing article, or creating a new one? – mpen Dec 07 '09 at 20:15
  • @mark it creates a new one unless you pass an instance. if you pass an instance, it does an update – Jiaaro Dec 07 '09 at 20:39
  • @Jim: Yes... but how do I check which case it is inside the `save()` method? Is checking if `article.id` is set a reliable method? – mpen Dec 07 '09 at 21:31
  • 1
    You could use: article, created = Article.objects.get_or_create(whatever_field=whatever_value, defaults={'whatever_field' : whatever_value}), which will get or create a new article object using the supplied values and tell you whether or not it created a new object. Reference: http://docs.djangoproject.com/en/1.2/ref/models/querysets/#get-or-create – Brandon Taylor Mar 17 '11 at 19:04

1 Answers1

7

I guess the answer I'm looking for is:

article = super(ArticleForm, self).save(commit=False)
mpen
  • 272,448
  • 266
  • 850
  • 1,236