为了账号安全,请及时绑定邮箱和手机立即绑定

Django使用外键添加到数据库,同时仍显示来自其他模型的信息

Django使用外键添加到数据库,同时仍显示来自其他模型的信息

鸿蒙传说 2021-08-11 21:30:20
我想将元素添加到我的数据库(对于模型学生),同时将来自另一个模型(学校)的内容与学生的表单一起显示。\这是models.pyclass School(models.Model):    name = models.CharField(max_length=256)    principal = models.CharField(max_length=256)    location = models.CharField(max_length=256)    def get_absolute_url(self):        return reverse('basiccbv:detail', kwargs={'pk':self.pk})    def __str__(self):        return self.nameclass Student(models.Model):    name = models.CharField(max_length=256)    age = models.PositiveIntegerField(validators= [validators.MinValueValidator(1),validators.MaxValueValidator(20)],default=1)    school = models.ForeignKey(School, related_name='students')def __str__(self):    return self.name在我的 views.py 我有这个:class SchoolDetailedView(DetailView):    context_object_name = 'school_detail'    model = models.School    template_name = 'basiccbv/school_detail.html'    # What i want is when I visit the link in the description I want to    # to see the school stuff and the form to add the student in this new     # viewclass StudentCreateView(CreateView):    model = models.School    # I tried using the Student but that I don't know how to display the     # school information, I tried with related_name = 'students' but it     # didn't work(I don't know if that can be done the way that intended it     # or I just don't have the knowledge )      fields = ['name', 'age']    # If I use School I could get the name of the school in the title and     # its primary key, but than I don't know how to display the form and     # vise versa     template_name = 'basiccbv/student_update.html'这是 .html 文件,可将我带到需要表单的页面。该链接是一个名为“basiccbv:studentupdate”的链接,这里使用了 related_name 学生,但我仍然不知道是否可以按照我想要的方式添加内容我真的被困住了,找不到任何关于这方面的信息,但如果你能帮助我或提供任何建议,谢谢。我过去添加学生的方式是使用 admin,对于学校,我使用 admin 直到我创建了用于创建没有问题的 Schools 的视图(可能是因为没有外键)。
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号