django OneToOneField上出现“选择有效选项,该选项不是可用选项之一”错误

gk7wooem  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(149)

models.py

class Major(models.Model):
    major = models.CharField(max_length=50, unique=True)
    description = models.TextField()
    image = models.ImageField(default='default_pics/default_major.jpg', upload_to='major_pics')

class Teacher(models.Model):
    image = models.ImageField(default='default_pics/default_teacher.jpg', upload_to='teacher_pics')
    interest = models.TextField(blank=True,null=True)

    major = models.ForeignKey(Major, on_delete=models.SET_NULL, null=True)
    user = models.OneToOneField(MyUser, on_delete=models.CASCADE)

forms.py

class TeacherProfileCreationForm(forms.ModelForm):
    class Meta:
        model = Teacher
        fields = ['major', 'image']
        help_texts = {
            'image': 'If you do not set any image, one will be set automatically for this teacher upon creation.'
        }

views.py

@login_required
def teacher_create_view(request):

    if request.method == 'POST':
        u_form = TeacherUserCreationForm(request.POST)
        t_form = TeacherProfileCreationForm(request.POST, request.FILES)
        if u_form.is_valid and t_form.is_valid():
            u_form.save()

            t_form.save(commit=False)
            email = u_form.cleaned_data.get('email')
            user = MyUser.objects.get(email=email)
            t_form.instance.user = user
            t_form.save()

            teacher = Teacher.objects.get(user__email=email)
            messages.success(request, f'A teacher has been added!')
            return redirect('teacher-detail', teacher.id)
    else:
        u_form = TeacherUserCreationForm()
        t_form = TeacherProfileCreationForm()

    context = {'u_form': u_form, 't_form': t_form,
               'list_url':list_url,'list_title':list_title, 'detail_title': detail_title}
    return render(request, 'users/teacher_create_update_form.html', context)

tests.py

class TestTeacher(TestCase):

    def setUp(self):
        self.client = Client()
        self.major = Major.objects.create(
            major='Test Major',
            description='Foo bar',
        )
        self.teacher_user = User.objects.create(
            email="test_teacher@gmail.com",
            full_name="Test Teacher 1",
            is_teacher=True
        )
        self.teacher = Teacher.objects.create(
            major=self.major,
            user=self.teacher_user
        )
        self.teacher_create = reverse('teacher-create')

    def test_teacher_create(self):
        response = self.client.post(self.teacher_create, {
            'email': 'test_teacher2@gmail.com',
            'full_name': "Test Teacher 2",
            'password1': '@DylanBergmanN1!',
            'password2': '@DylanBergmanN1!',
            'major': self.major # The error is most probably right here
        })
        print(response.context['t_form'].errors)

终端出错信息

<ul class="errorlist"><li>major<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

基本上,我试图测试这个创建视图,当我将major传递给视图时,它说我必须选择一个有效的选择,但我如何才能正确地为OneToOneField做这件事?我尝试了'major':self.major.major},'major':'Test Major'},' major ':[self.major]},' major ':[' Test Major']},etc. but none of them worked. Help me please!Thank you in advance.

r3i60tvu

r3i60tvu1#

错误不在OneToOneField中,而是在majorForeignKey字段中。当你使用Django测试客户端发送原始POST数据时,你需要为外键字段使用主键。
所以:

response = self.client.post(self.teacher_create, {
    'email': 'test_teacher2@gmail.com',
    'full_name': "Test Teacher 2",
    'password1': '@DylanBergmanN1!',
    'password2': '@DylanBergmanN1!',
    'major': self.major.pk
})

相关问题