gpt4 book ai didi

python - Django Createview外键字段的默认值

转载 作者:行者123 更新时间:2023-11-28 20:59:17 27 4
gpt4 key购买 nike

我有两个相关的类(class)(表)学校和学生(外键)当我创建一个新学生时,我希望它自动填充学校字段(这是学校类(表)中名称字段的外键,因为它已经链接到学校。我试过 def get_initial(self): 没有运气(它给我错误)。如果有人能指出我做错了什么……谢谢模型.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,
}

最佳答案

由于您将学校的 slug 存储在 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)

关于python - Django Createview外键字段的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com