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

Posted

技术标签:

【中文标题】Django 使用外键添加到数据库,同时仍显示来自其他模型的信息【英文标题】:Django adding to database with foreign key while still showing the informations from the other model 【发布时间】:2019-04-12 11:15:37 【问题描述】:

我想将元素添加到我的数据库(用于模型 Student),同时将来自另一个模型(School)的内容显示在 Student 的表单旁边。\

这是models.py

class 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.name


class 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 
    # view

class 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学生,但我仍然不知道它是否可以 以我想要的方式添加东西完成

<h1>Welcome to the school details page</h1>
<h2>School details:</h2>
<p>Name:  school_detail.name </p>
<p>Principal:  school_detail.principal </p>
<p>Location:  school_detail.location </p>
<h3>Students:</h3>
% for student in school_detail.students.all %
<p> student.name  who is  student.age  years old.</p>
% endfor %
<div class="container">
<p><a href="% url 'basiccbv:studentupdate' pk=school_detail.pk %">Add a 
student</a></p>

这是带有表单的 .html 文件

              ## I changed this part bellow but nothing worked
<h1>Student coming to  student.school.name </h1>
<form method="post">
% csrf_token %
 form.as_p 
    <input type="submit" class="btn btn-primary" value="Add student">
</form>

我真的被困住了,找不到任何有关此的信息,但如果您能帮助我或提供任何建议,谢谢。

我过去添加学生的方式是使用 admin,而对于学校,我使用 admin,直到我创建了用于创建没有问题的学校的视图(可能是因为没有外键)。

【问题讨论】:

【参考方案1】:

我认为你可以采用这种方法

表格:

# We need to define a new form first
class StudentForm(forms.ModelForm):
     class Meta:
         model = Student
         fields = ['name', 'age']

观看次数:

# we are using form view for using the form mentioned above
class StudentCreateView(FormView):
     form_class = StudentForm
     success_url = "/"

     def get(self, request, school_id, **kwargs):
         context = self.get_context_data(**kwargs)  # getting context, ie: the form
         context[school] = School.objects.get(pk=school_id)  # updating the context with school object using the PK provided with the url
         return self.render_to_response(context)

     def post(self, request, school_id, **kwargs):
        # overriding default implementation
        form = self.get_form()  
        if form.is_valid():
            return self.form_valid(form, school_id)  # passing the pk value to form valid function to override
        else:
            return self.form_invalid(form)

    def form_valid(self, form, school_id):
        # overriding default implementation
        self.object = form.save(commit=False)
        self.object.school = School.objects.get(id=school_id)  # saving the school information to the object
        self.object.save()
        return super(StudentCreateView, self).form_valid(form)

模板

# template
    <h1>Student coming to  school.name </h1>
    <form method="post">
    % csrf_token %
     form.as_p 
        <input type="submit" class="btn btn-primary" value="Add student">
    </form>

网址

path('school/student-update/<int:school_id>/', StudentCreateView.as_view(), name='studentupdate'),

【讨论】:

以上是关于Django 使用外键添加到数据库,同时仍显示来自其他模型的信息的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Django 中向 ModelForm 添加外键字段?

Django 表单 - 就地编辑来自反向外键连接的数据

Django Forms - 构建一个表单,显示来自多个不同模型的字段,但按外键排序

如何在 Django html 页面中显示外键数据?

通过 Django Admin 中的内联显示编辑/添加外键对象

Django 管理员添加自定义过滤器