简体   繁体   中英

Django: model foreign key and a selectbox widget

I've 2 models Worker and Position when I add a new worker there should be selectbox with the positions listed in Positions model.

I tried to use Select widget but django fails with no such property exception.

Models


# Position model
class Position(models.Model):
    p_name   = models.CharField(max_length = 40, unique = True, verbose_name = 'Position')
    p_salary = models.IntegerField(max_length = 11, verbose_name = 'Salary')

    fields = ('p_name', 'p_salary')

# Worker model
class Worker(models.Model):
    w_name     = models.CharField(max_length = 40, verbose_name = 'Name')
    w_lastname = models.CharField(max_length = 40, verbose_name = 'Lastname')
    w_position = models.ForeignKey(to = Position, to_field = 'p_name', verbose_name = 'Position')
    w_dept     = models.ForeignKey(to = Department, to_field = 'd_name' verbose_name = 'Department')

Form


class WorkerForm(ModelForm):
    class Meta:
        model = Worker

        widgets = {
            'w_name'    : TextInput(attrs = {'class': 'e name'}),
            'w_lastame' : TextInput(attrs = {'class': 'e lastname'}),
            'w_position': Select(attrs = {'class': 'e position'}),
            'w_dept'    : Select(attrs = {'class': 'e department'}),
        }

Definition in admin.py


class WorkerAdmin(admin.ModelAdmin):
    form = WorkerForm

list_display = ('w_name', 'w_lastname', 'w_position', 'w_dept')

What goes wrong how to make select box appear according to a foreign key?

Sultan

您可以尝试在表单内重新声明表单的字段(确保使用与Model中相同的名称),然后在其中设置小部件和属性?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM