开发者

Django: model foreign key and a selectbox widget

开发者 https://www.devze.com 2023-02-08 20:04 出处:网络
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'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.开发者_如何学CModelAdmin):
    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


You could try just re-declaring the field for the form inside the form (making sure to use the same name as it is in the Model) and setting the widget and attrs in there?

0

精彩评论

暂无评论...
验证码 换一张
取 消