我在尝试编辑时在管理页面中遇到问题。在下面的图片中,您可以看到它(额外的“需要字段”)。当我尝试编辑时,我看到一个额外的行。我有点自定义会员块与我自己的形式因为我想在'角色'字段中向管理员显示'经理'值。它工作但编辑引发错误。顺便说一句,当我不使用自定义表单编辑工作没有问题,尽管有额外的行。在下面你可以看到我的代码。所以我很满意。我怎么解决这个问题?我还尝试使用awk 'FNR==1{ cnt=split(FILENAME, arr, "/"); basename=arr[cnt] } { print $0, basename}'
格式__init__
和self.fields['user'].required = False
,但它没有帮助。
models.py :
self.fields['role'].required = False
admin.py :
class Project(models.Model):
***FIELDS***
members = models.ManyToManyField(User, through='Membership',)
ROLE_CHOICES = (
('manager', 'Manager'),
('developer', 'Developer'),
('business_analyst', 'Business analyst'),
('system_analysts', 'System analysts'),
)
class Membership (models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
role = models.CharField(max_length=20, choices=ROLE_CHOICES,)
forms.py :
class MembershipInline(admin.TabularInline):
model = Membership
form = MembershipAdminForm
extra = 1
class MembershipAdmin(admin.ModelAdmin):
inlines = (MembershipInline,)
admin.site.register(Project, MembershipAdmin)
错误:
class MembershipAdminForm(forms.ModelForm):
class Meta:
model = Membership
fields = '__all__'
def __init__(self, *args, **kwargs):
super(MembershipAdminForm, self).__init__(*args, **kwargs)
self.fields['role'].choices = tuple(choice for choice in ROLE_CHOICES if choice[0] not in ['developer', 'business_analyst', 'system_analysts'])
答案 0 :(得分:0)
将blank=True
和null=True
添加到您希望成为可选字段:
class Membership (models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
role = models.CharField(max_length=20, choices=ROLE_CHOICES, blank=True, null=True)
答案 1 :(得分:0)
好吧,毕竟我在Django的官方文档中找到了解决方案。在我的管理员。 py文件我添加了max_num = 1
。
如果max_num的值大于现有相关的数量 对象,最多额外的空白表格将被添加到 formset,只要表单总数不超过max_num
class MembershipInline(admin.TabularInline):
model = Membership
form = MembershipAdminForm
extra = 1
max_num = 1