not able to get parent id record for saving a extra records on def save of inline
- I'm saving a Project.
- It has a Practitioner inline model.
- On the def save of the Practitioner model I am running custom code to insert another record into another table called Simple Auth.
My thinking was that if I pass through the instance of the project to the practitioner like I'm doing in the views.py, that the def save would then be able to reference the project of of self.
So my views.py looks like this:
def form_valid(self, form):
practitioner_form = context['practitioner_form']
if practitioner_form.is_valid():
self.object = form.save(commit=False)
self.object.slug = slugify(self.object.title)
self.object.save()
practitioner_form.instance = self.object
practitioner_form.save()
return HttpResponseRedirect(reverse('profile_detail', kwargs={'username':user.username}))
else:
return self.render_to_response(self.get_context_data(form=form))
My Practitioner def save looks like this:
def save(self, *args, **kwargs):
if SimpleAuth.objects.filter(project=self.project,name=self.practitioner_name).exists():
simpleauth = SimpleAuth.objects.get(project=self.project,name=self.practitioner_name)
simpleauth.project = self.project
simpleauth.name = self.practitioner_name
simpleauth.save()
else:
SimpleAuth.objects.create(project = self.p开发者_如何学Pythonroject, name = self.practitioner_name)
super(Practitioner, self).save(*args, **kwargs)
For some reason simpleauth.project = self.project
doesn't seem to have any value. Why can't I get the project id like this?
Just a note. If I create my project via the admin then it all works. It is on my form that this doesn't work.
I don't think it's the best way but for now it works. If no one answers with a more elegant way then I'll mark this as the answer.
In the def save I've added a get_object_or_404.
def save(self, *args, **kwargs):
project = get_object_or_404(Project, pk=self.project_id)
if SimpleAuth.objects.filter(project=self.project,name=self.practitioner_name).exists():
simpleauth = SimpleAuth.objects.get(project=project,name=self.practitioner_name)
simpleauth.project = project
simpleauth.name = self.practitioner_name
simpleauth.save()
else:
SimpleAuth.objects.create(project = project, name = self.practitioner_name)
super(Practitioner, self).save(*args, **kwargs)
精彩评论