0

I have the following view:

from django.views.generic.edit import CreateView

from news.forms import CreateNewsStoryForm
from news.models import NewsStory


class CreateNewsStoryView(CreateView):
    model = NewsStory
    form_class = CreateNewsStoryForm

All you need to know about the NewsStory model, is that it has an author foreign key field to User. When a new NewsStory is created through the form, I want the new model's author attribute to be set to the current user. How do I hook into the CreateView's flow to set this up?

I'm certain it must be somewhere in the view, since the form doesn't have access to the request.

This seems like it would be a very common use case, but I can't seem to figure out the correct keywords to search for this, so excuse me if it has been asked before.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
bigblind
  • 12,539
  • 14
  • 68
  • 123
  • 1
    Do remember to add a [python] tag. It'll help you get more views on your question. Regards. – Bhargav Rao Mar 21 '16 at 20:06
  • @ Alasdair I think this question is phrased in a sufficiently different way that it could be useful to people looking for the answer. – bigblind Mar 21 '16 at 20:07
  • 1
    Eeek, bigblind. You pinged me. The right way to ping @Alasdair is like this. – Bhargav Rao Mar 21 '16 at 20:08
  • Thx @BhargavRao (And I'm sorry for pinging you again if this frustrates you :)). – bigblind Mar 21 '16 at 20:09
  • Heh, Nope. I'm a lonely guy, you can ping me all day. But note that a question being phrased *in a sufficiently different way* doesn't warrant opening of a duplicate. Do(es) the answer(s) in the other post answer your query? – Bhargav Rao Mar 21 '16 at 20:11
  • 2
    Your question is a pretty common one on Stack Overflow, [here is another example](http://stackoverflow.com/questions/10382838/how-to-set-foreignkey-in-createview). The question I chose has the advantage of being written by Russell, the guy who added CBVs to Django. Even if your answer is worded differently, it can still be marked as a duplicate. Future visitors who find this page can click through. – Alasdair Mar 21 '16 at 20:18
  • 1
    @Alasdair Ah yes, that makes sense. Also, I thought about closing in the wrong way. This is exactly the reason why SO has the closing mechanism. The way the question is phrased may add value, but the content shouldn't be duplicated. Deleting the dupe would remove value from the site. – bigblind Mar 21 '16 at 22:10

0 Answers0