Django Createview外键字段的默认值

时间:2018-04-16 12:38:41

标签: python django django-class-based-views

我有两个班级(表格)学校和相关的学生(外键) 当我创建一个新学生时,我希望它自动填充学校字段(这是学校班级(表)中名字字段的外键,因为它已经链接到学校。 我试过def get_initial(self):没有运气(它给我错误)。如果有人能指出我做错了什么......谢谢 Models.py:

class School(models.Model):
    school_pk = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)
    def __str__(self):
        return str(self.name)
    def get_absolute_url(self):
        return reverse("basic_app:school_detail",kwargs={'school_pk':self.school_pk})
class Student(models.Model):
    student_pk = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE,default=None)

    def __str__(self):
        return self.name
    def get_absolute_url(self):
        return reverse("basic_app:student_detail",kwargs={'student_pk':self.student_pk,'school':self.school})

views.py:

class StudentCreateView(CreateView):
    fields = ("name","age","school")
    model = models.Student
    template_name = 'basic_app/student_form.html'

    pk_url_kwarg = 'student_pk'
    slug_url_kwarg='school'
    def get_initial(self):
        school = get_object_or_404(models.School, school_pk=self.kwargs.get('school_pk'))
        return {
        'school':school,
    }

2 个答案:

答案 0 :(得分:5)

由于您将学校的slu存储存在URL中,最好将学校字段排除在表单之外。然后,您可以使用form_valid方法设置学校:

from django.shortcuts import get_object_or_404

class StudentCreateView(CreateView):
    fields = ("name","age",)  # don't include 'school' here
    ...

    def form_valid(self, form):
        school = get_object_or_404(School, slug=self.kwargs['school'])
        form.instance.school = school
        return super(StudentCreateView, self).form_valid(form)

答案 1 :(得分:0)

如果您想为FK字段指定默认值,请使用default属性。 Django已经提供了为你的字段添加默认值的选项。

DEFAULT_SCHOOL_ID = 1
class Student(models.Model):
   ...
   school=models.ForeignKey(School, default=DEFAULT_SCHOOL_ID)

您是一个重写的get_initial方法,用于返回用于此视图中的表单的初始数据,而不是实际向您的字段添加默认值