我有两个一对多关系中的模型。我正在编辑父记录并创建子记录。当我创建子项时,我无法弄清楚如何发送父项的引用,以便实例化子项的ForiegnKey指向父项。有人能帮忙吗。感谢
父级是:
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()
孩子是:
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}"
我试图在孩子的验证函数中将孩子指向父母
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())
方法1:为Site
实例创建一个视图,该视图将按id
显示特定站点。例如:/site/1/
。在该视图中,为Administrator
实例化一个表单。然后在form_valid
方法中,可以将site
作为self.object
传递,如下所示:
def form_valid(self,form):
form.instance.site = self.get_object()
return super().form_valid(form)
方法2:为Administrator
实例创建一个表单。然后,site
将是一个下拉列表,您可以在其中选择一个site
并提交表单。
选择最适合你的。
我终于这样做了。
url.py有以下行:
path('administrator/new/<int:site_id>',views.AdministratorCreateView.as_view(),name='administrator.new'),
链接到我的详细视图的html带有:
<a href="{% url 'administrator.new' site.id %}" class="btn btn-primary">Create</a>
我的视图类如下:
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())
这正是我想要做的,感谢大家的帮助。