当我添加新工作时,我有2个模型Worker
和Position
应该有一个选择框,其中Positions
模型中列出的位置。
我尝试使用Select
小部件,但django因no such property
例外而失败。
模型
# 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')
表格
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'}),
}
在admin.py中定义
class WorkerAdmin(admin.ModelAdmin):
form = WorkerForm
list_display = ('w_name', 'w_lastname', 'w_position', 'w_dept')
list_display = ('w_name', 'w_lastname', 'w_position', 'w_dept')
如何根据外键显示选择框会出现什么问题?
苏丹
答案 0 :(得分:1)
您可以尝试重新声明表单内部表单的字段(确保使用与模型中相同的名称)并在其中设置窗口小部件和attrs?