Home > Software design >  Django adding link to parent when creating child in a many to one relationship
Django adding link to parent when creating child in a many to one relationship

Time:09-07

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()

the child is:

class Administrator(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    telephone = models.CharField(max_length=50)
    email = models.EmailField()
    site = models.ForeignKey(
        Site, on_delete=models.CASCADE, related_name="adminstrators"
    )

    def __str__(self):
        return f"{self.first_name} {self.last_name}, {self.email}"

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())

CodePudding user response:

Method 1: Create a view for Site instance, that will show a particular site by id. For example: /site/1/. In that view, instantiate a form for Administrator. Then in the form_valid method, you can pass the site as self.object like this:

def form_valid(self,form):
    form.instance.site = self.get_object()
    return super().form_valid(form)

Method 2: Create a form for Administrator instance. Then, site will be a dropdown, where you can select a site and submit the form.

Choose whatever suits you best.

CodePudding user response:

I finally did it this way.

The url.py had the following line:

path('administrator/new/<int:site_id>',views.AdministratorCreateView.as_view(),name='administrator.new'),

The html linked to my detail view with:

<a href="{% url 'administrator.new' site.id %}" >Create</a>

and my view class is as follows:

class AdministratorCreateView(CreateView):
    model = Administrator
    form_class = AdministratorForm
    template_name = "register/administrator_new.html"
    
    def get_success_url(self):
        return reverse_lazy("administrator.detail", kwargs={"pk": self.object.pk})

    def form_valid(self, form):
        site_id = self.kwargs['site_id']
        self.object = form.save(commit=False)
        self.object.site = Site.objects.get(pk=site_id)
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

This does what i was trying to do, thanks to all for the help.

  • Related