0

My goal is to create a form to add a rental for a device including a user.

device and user are implemented with a ForeignKey, and for the user i want to use django-select2 , because of the heavy amount of users.

models.py

class Device(models.Model):
    name = models.CharField(
        verbose_name = "Gerätename",
        max_length =       128,
        unique =        True,
        )

    def __str__(self):
        return self.name



class ldap_data(models.Model):
    username = models.CharField(max_length=1024, unique=True)

    class Meta:
        ordering = ('username',)

    def __str__(self):
        return self.username


class Rental(models.Model):
    user = models.ForeignKey(ldap_data, on_delete=models.CASCADE)
    device = models.ForeignKey(Device, on_delete=models.CASCADE)
    date_start = models.DateField()
    date_end = models.DateField()


    class Meta:
        ordering = ('date_start',)

    def __str__(self):
        return self.device

forms.py

class RentalForm(forms.ModelForm):
    user = forms.ChoiceField(
            widget=ModelSelect2Widget(
                model=ldap_data,
                search_fields=['username__icontains']
            )
        )


    date_start = forms.CharField(label="Datum Ausleihe", help_text="", widget=forms.TextInput(attrs={'id': 'datepicker', 'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' }))
    date_end = forms.CharField(label="Datum Rückgabe", help_text="", widget=forms.TextInput(attrs={'id': 'datepicker2', 'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' }))

    class Meta:
        model = Rental
        fields = ['device', 'user', 'date_start', 'date_end',]

The form works so far, but if i select a user from the django-select2 field user and submit the form, it complains:

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

It looks like the form tries to validate the pk (=1) of the selected user, instead of the username of ldap_data. How would i get the username (CharField) instead of the pk (IntegerField) ?

fuser60596
  • 1,087
  • 1
  • 12
  • 26

1 Answers1

0

I had to switch to ModelChoiceField and set a queryset.

class RentalForm(forms.ModelForm):
    user = forms.ModelChoiceField(
            queryset=ldap_data.objects.all(),
            widget=ModelSelect2Widget(
                model=ldap_data,
                search_fields=['username__icontains']
            )
        )
...
fuser60596
  • 1,087
  • 1
  • 12
  • 26