Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The other route to doing this is to put the save behaviour on the form itself.</p> <pre><code>class NewPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ('title', 'post_body') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(NewPostForm, self).__init__(*args, **kwargs) def save(self): obj = super(NewPostForm, self).save(commit=False) obj.user = self.user obj.pub_date = timezone.now() obj.save() return obj </code></pre> <p>This nicely encapsulates the logic in a more reusable way outside of the view.</p> <p>You'd need to override <code>get_form_kwargs</code> on the view to pass the user in, or use the <code>UserFormKwargsMixin</code> class from <a href="https://github.com/brack3t/django-braces" rel="nofollow"><code>django-braces</code></a> in order to ensure <code>user</code> gets passed by the view when initializing the form.</p> <p>Note that <a href="https://github.com/brack3t/django-braces" rel="nofollow"><code>django-braces</code></a> also provides a <code>UserKwargModelFormMixin</code> that you can use on the form instead of overriding <code>__init__()</code>. If you take the braces approach, you'd end up with something like this:</p> <p><strong>forms.py</strong>:</p> <pre><code>class NewPostForm(UserKwargModelFormMixin, forms.ModelForm): class Meta: model = BlogPost fields = ('title', 'post_body') def save(self): obj = super(NewPostForm, self).save(commit=False) obj.user = self.user obj.pub_date = timezone.now() obj.save() return obj </code></pre> <p><strong>views.py</strong>:</p> <pre><code>class NewPostView(UserFormKwargsMixin, generic.edit.CreateView): model = BlogPost form_class = NewPostForm </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload