Django-select2选择pk(IntegerField)而不是用户名(CharField)

时间:2019-09-09 18:13:26

标签: django django-models django-forms django-select2

我的目标是创建一个表单来为包括用户在内的设备添加租期。

deviceuser是由ForeignKey实现的,并且由于用户数量众多,我想为user使用django-select2

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',]

到目前为止,该表单仍然有效,但是如果我从django-select2字段user中选择一个用户并提交表单,它将抱怨:

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

该表单似乎试图验证所选用户的pk(= 1),而不是username的{​​{1}}。我如何获取用户名(CharField)而不是pk(IntegerField)?

1 个答案:

答案 0 :(得分:0)

我必须切换到ModelChoiceField并设置一个查询集。

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