[英]Django foreign key default
我正在使用CreateView將帶有外鍵的Section添加到Course。 如果我有外鍵的默認值,它將始終另存為默認值。 如果我沒有默認值,它將始終保存為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>
我將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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.