Friday, October 10, 2014

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

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)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9922a44a-b4ce-4fdd-9b4b-044507c3d1ca%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment