我正在使用CreateView向Course添加带有外键的Section。如果我有外键的默认值,它始终保存为默认值。如果我没有默认值,它始终保存为null或空白。
class Course(models.Model):
course_name = models.CharField(max_length=50)
course_code = models.CharField(max_length=8, unique=True)
atype = models.CharField(max_length=10, default='Course')
def get_absolute_url(self):
return reverse('calculate:course_detail', kwargs={'pk': self.pk})
def __str__(self):
return self.course_name
class Section(models.Model):
section_name = models.CharField(max_length=50)
percentage = models.IntegerField(default=100,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
])
atype = models.CharField(max_length=10, default='Section')
section_section = models.ForeignKey('self',
blank=True,
null=True,
on_delete=models.CASCADE)
section_course = models.ForeignKey('Course',
blank=True,
null=True,
on_delete=models.CASCADE)
def get_absolute_url(self):
if self.section_course is None:
pk = self.section_section.pk
else:
pk = self.section_course.pk
return reverse('calculate:course_detail', kwargs={'pk': pk})
def __str__(self):
return self.section_name
这是CreateView:
class SectionCreate(CreateView):
model = Section
fields = ['section_name', 'percentage', 'section_section', 'section_course']
def get_initial(self):
pk = self.kwargs['pk']
course = Course.objects.get(pk=pk)
return {'section_course': course}
def get_form(self, form_class=None):
pk = self.kwargs['pk']
course = Course.objects.get(pk=pk)
form = super(SectionCreate, self).get_form(form_class)
form.fields['section_section'].queryset = Section.objects.filter(section_course=course)
return form
def get_context_data(self, **kwargs):
pk = self.kwargs['pk']
s_type = self.kwargs['s_type']
context = super(SectionCreate, self).get_context_data(**kwargs)
if s_type == 'Course':
course = Course.objects.get(pk=pk)
self.model.section_course = course
if s_type == 'Section':
s = Section.objects.get(pk=pk)
section.section_section = s
context['course'] = course
context['pk'] = pk
context['s_type'] = s_type
return context
def form_valid(self, form):
form.save()
return super(SectionCreate, self).form_valid(form)
我使用get_initial添加了课程,使用get_form添加了与该课程相关的章节,get_context_data基于url,在form_valid中我保存了表单。
模板:
<form action="{% url 'calculate:add_section' s_type pk %}" method="POST">
{% csrf_token %}
<div class="modal-header">
<a type="button" class="close button" data-dismiss="modal" aria-hidden="true"
href="{% url 'calculate:course_detail' course.id %}">×</a>
<h4 class="modal-title" id="section-modal-label">Add Section</h4>
</div>
<div class="modal-body">
{{form.as_p}}
</div>
<div class="modal-footer">
<input type="submit" name="submit" value="Add Section" />
</div>
</form>
答案 0 :(得分:0)
我将form_valid()更改为:
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
form.instance.section_course_id = context['pk']
form.save()
return super(SectionCreate, self).form_valid(form)
显然,它想要课程模型的ID。需要将带有_id的外键名称设置为传递给上下文的id。