管理站点中的多选输入

时间:2018-02-18 04:00:53

标签: django django-forms

我正在尝试在管理网站中创建一个表单,该表单使用来自两个不同表(Employee,Product)的两个字段作为输入(单选和多选)并使其可供管理员用户选择并将其写入另一个table(JobQueue)。

以下是我的代码。

models.py

class Employee(models.Model):
    id = models.IntegerField(primary_key=True, verbose_name='Employee Code')
    name = models.CharField(max_length=200, verbose_name='Employee Name')

    def __str__(self):
        return self.name

class Product(models.Model):
    STATUS = (('New', 'New'), ('Go', 'Go'), ('Hold', 'Hold'), ('Stop', 'Stop'))

    code = models.IntegerField(primary_key=True, max_length=3, verbose_name='Product Code')
    name = models.CharField(max_length=100, verbose_name='Product Name')
    def __str__(self):
        return self.name

class JobQueue(models.Model):

    emp_name = models.CharField(max_length=200, default='1001')
    product_code = models.CharField(max_length=200, default='100')

admin.py:

class JobQueueAdmin(admin.ModelAdmin):
    form = JobQueueForm

    fieldsets = ( 
        (None,{'fields': ('emp_name', 'product_code'),}),)

    def save_model(self, request, obj, form, change):
        super(JobQueueAdmin, self).save_model(request, obj, form, change)

forms.py:

class JobQueueForm(forms.ModelForm):
    # Single select drop down 
    emp_name = forms.ModelChoiceField(queryset=Employee.objects.all(), widget=forms.ChoiceField())
    # Multiselect checkbox
    product_code = forms.MultiValueField(queryset=Product.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)

    def save(self, commit=True):
        return super(JobQueueForm, self).save(commit = commit)

    class Meta:
        model = JobQueue
        fields = ('emp_name', 'product_code')

当我启动Web服务器时,出现以下错误:

AttributeError: 'ModelChoiceField' object has no attribute 'to_field_name'

有人可以帮助我如何让用户从JobQueueForm中选择值并将其保存在JobQueue表中?

0 个答案:

没有答案