Django Createview default value for a foreign key field

前端 未结 2 1424
失恋的感觉
失恋的感觉 2021-01-14 12:34

I have two classes(tables) schools and students that are related together(foreignkey) When I create a new student I want it to autofill the school field (which is a foreignk

相关标签:
2条回答
  • 2021-01-14 13:15

    If you want to give a default value for your FK field go with default attribute. Django already gives the option to add a default value to your field.

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

    You are an overriding get_initial method its used for Returns the initial data to use for forms on this view not actually adding a default value to your field

    0 讨论(0)
  • 2021-01-14 13:32

    Since you are storing the school's slug in the URL, it would be better to leave the school field out of the form. Then you can set the school in the form_valid method:

    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)
    
    0 讨论(0)
提交回复
热议问题