How to get user ID and ID of newly created record in a CreateView?

249 views
Skip to first unread message

Daniel Grace

unread,
Oct 10, 2014, 2:03:49 PM10/10/14
to django...@googlegroups.com
Hi, I am using a CreateView.  I want to create some related data on a table ("Log" model), so I need the ID of the record being created for the related field (see "flow" below).  Also I need the ID of the user creating the record.  Something like the following:

from django.utils import timezone
from django.views.generic.edit import CreateView
from django.contrib.auth.decorators import login_required
from flow.models import Flow, Log

class CreateFlow(CreateView):
    model = Flow
    fields = ['state']
    template_name = 'create_flow.html'
    # there is a problem with this:
    @login_required
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        # ... and this:
        log = Log(user=self.request.user.id, flow=id, state=1, created=timezone.now)
        log.save()
        return super(CreateFlow, self).form_valid(form)

Daniel Roseman

unread,
Oct 10, 2014, 3:50:16 PM10/10/14
to django...@googlegroups.com
"Something" like that? What, exactly, is wrong with that?
--
DR. 

Daniel Grace

unread,
Oct 12, 2014, 3:06:04 PM10/12/14
to django...@googlegroups.com
I get the error:
'CreateFlow' object has no attribute 'user'

How do I get the id of the record just created?

Collin Anderson

unread,
Oct 13, 2014, 9:45:09 AM10/13/14
to django...@googlegroups.com
Hi Daniel,

Interesting. Could you post a traceback?

Thanks,
Collin

Daniel Grace

unread,
Oct 13, 2014, 10:32:42 AM10/13/14
to django...@googlegroups.com
I made a different approach after getting help, which I now have working:
Reply all
Reply to author
Forward
0 new messages