简体   繁体   English

Django外键默认

[英]Django foreign key default

I'm using CreateView to add a Section with a foreign key to Course. 我正在使用CreateView将带有外键的Section添加到Course。 If I have a default value for the foreign key, it always saves as the default value. 如果我有外键的默认值,它将始终另存为默认值。 If I don't have a default value, it always saves as null or blank. 如果我没有默认值,它将始终保存为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

Here's the CreateView: 这是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)

I get the Course that I'm adding in with get_initial, the Sections related to that course with get_form, the get_context_data is based on the url, and in form_valid I save the form. 我使用get_initial获得要添加的课程,使用get_form获得与该课程相关的部分,get_context_data基于url,并在form_valid中保存表单。

Template: 模板:

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

I changed my form_valid() to this: 我将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)

Apparently, it wanted the id of the Course model. 显然,它想要课程模型的ID。 Needed to set the foreign key name with _id to the id being passed into the context. 需要将带有_id的外键名称设置为要传递到上下文的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM