2

The dropdown list appears correctly in the html, However I am unable to figure out why I run into the same error time after time when I try to submit / .

"Select a valid choice. That choice is not one of the available choices."

the problem context

I have two models defined in Django. One CourseModel database to hold all the offered courses and one registration database to link a course to a user.

models.py

from django.db import models
# Create your models here.

class CourseModel(models.Model):
    course = models.CharField(max_length=100)
    date = models.DateField(max_length=100)
    time = models.TimeField()
    location = models.CharField(max_length=100)
    datetime = models.DateTimeField()

class RegistrationModel(models.Model):
    name = models.CharField(max_length=100)
    adress = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    course = models.ForeignKey('self', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

I use modelForm to create a registration form, where the user can subscribe for a course from a dropdown list.

forms.py

from django.forms import ModelForm, RegexField
from home.models import RegistrationModel, CourseModel
from django import forms
import datetime


class RegistrationForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['course'].queryset = CourseModel.objects.exclude(date__lt=datetime.datetime.today()).values_list('datetime', flat=True)
        self.fields['course'].empty_label = None


    class Meta:
        model = RegistrationModel
        fields = '__all__'

views.py

from django.shortcuts import render, redirect
from home.forms import RegistrationForm
from .models import CourseModel
import datetime

def home(request):
    return render(request, 'home/home.html')


def registration(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        crs = request.POST.get('course')
        print(crs)
        if form.is_valid():
            cleanform = form.save(commit=False)
            cleanform.course = crs
            cleanform.save()
            return redirect('home')
    else:
        form = RegistrationForm()
    return render(request, 'home/registration.html', {'form': form})

1 Answers1

0

In the RegistrationForm's __init__() method, your self.fields['course'].queryset = ...values_list('datetime', flat=True) returns datetime instances. See values_list() docs.

I believe this may cause the issue. I guess the queryset should return CourseModel instances, based on the Django docs:

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet.

Also, your RegistrationModel.course field has a foreign key to 'self' instead of the CourseModel. Not sure if that is what you want.

Other examples of setting the field queryset can be found here.

djvg
  • 11,722
  • 5
  • 72
  • 103