I have two models in a one to many relationship. I am editing a parent record and creating a child. When I create the child I cannot figure out how the send a reference of the parent so that I can instantiate the ForiegnKey of the child to point to the parent. Could anyone help. thanks
The parent is:
class Site(models.Model):
name = models.CharField(max_length=100)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
postcode = models.CharField(max_length=50)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sites")
def __str__(self):
return f"{self.name}, {self.postcode}"
def get_queryset():
return set.request.user.sites.all()
I am trying to point the child at the parent in the child’s validation function:
def form_valid(self, form):
self.object = form.save(commit=False)
self.site = # I don't know what to put here as I have to reference to the parent Site object
self.object.save()
return HttpResponseRedirect(self.get_success_url())
def form_valid(self, form):
self.object = form.save(commit=False)
self.site = # I don't know what to put here as I have to reference to the parent Site object
self.object.save()
return HttpResponseRedirect(self.get_success_url())
And is this to do with updating a form, or creating a form?
I was viewing a Site detail form, and linked to create an Administrator for that Site. How else can make the Administrator a child of a particular Site - I don’t want to select the Site from a list.
The problem is that i am trying to set the value for a.Site not read it. I am creating the Administrator and wanting to put a reference to the Site in it.
Sorry, my explanation is not clear. I can’t keep a reference to the Site object because the Administrator object doesn’t know what the Site should be. My problem is: how do I tell the Administrator object what Site object it belongs to programmatically, rather than having the user select it from list of existing Sites. Thank you for your help, but I haven’t got there yet. I am an absolute beginner with Django.
this would involve selecting the sites from a list though and I don’t think that’s what you wanted to do. I’m not sure of other ways to go about it because you need a context for the site. Maybe there are other ways around this but I’m not sure
For clarity, are you performing this operation in a view that you have written, or are you looking at doing this in the Django admin?
It would be helpful if you posted the complete view.
[Edit] In general terms if these operations are being performed on two separate pages (two different views), you would generally pass the parent’s PK to the child view as a parameter in the url. The appropriate fix for this is likely going to involve changes to the parent’s view and template, and the child’s url definition.
Thank you, that seems to work, although I don’t quite understand why since I don’t have a field ‘site_id’ on the Administrator object; is it implied by the ‘site’ object?