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



我想将元素添加到我的数据库中(针对模型学生(,同时将来自另一个模型(学校(的内容显示在学生的表单旁边。\

这是型号.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

在我看来.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"的链接这里使用了相关名称的学生,但我仍然不知道是否可以按照我想要的方式添加内容

<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,直到我创建了创建学校的视图,它没有问题(可能是因为没有外键(。

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

表格:

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

Urls

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

最新更新