gpt4 book ai didi

Django CreateView ModelForm 下拉字段查询集过滤器

转载 作者:行者123 更新时间:2023-12-04 10:07:50 25 4
gpt4 key购买 nike

这是我第一次真正使用 Django (1.6),我一直无法弄清楚:

我试图将 CreateView 上的下拉列表限制为仅显示在项目模型中具有事件状态 (2) 的项目:

class ProjectStatus(models.Model):
name = models.CharField(max_length=8)

class Project(models.Model):
name = models.CharField(max_length=30)
status = models.ForeignKey(ProjectStatus)

class WorkLog(models.Model):
project = models.ForeignKey(Project)
author = models.ForeignKey(User)
log_date = models.DateField( default=datetime.date.today)
accomplishments = models.TextField()

我的forms.py:
class WorklogCreateForm(ModelForm):

class Meta:
model = WorkLog
fields = [ 'project', 'log_date', 'accomplishments' ]

def __init__(self, *args, **kwargs):
super(WorklogCreateForm, self).__init__(self, *args, **kwargs)
self.fields['project'].queryset = Project.objects.filter(Project.status == 2)

和我的来自 views.py 的 CreateView:
class WorklogCreate(CreateView):
form_class = WorklogCreateForm
success_url = reverse_lazy('dashboard')

但我得到了 错误:
TypeError at /log/add/
'bool' object has no attribute '__getitem__'

如果我将过滤器更改为 (Project.status.id == 2)我反而得到:
AttributeError at /log/add/
'ReverseSingleRelatedObjectDescriptor' object has no attribute 'id'

我想我很接近,但显然没有完全掌握我需要的东西。有任何想法吗?谢谢。

最佳答案

尝试像这样过滤。

 self.fields['project'].queryset = Project.objects.filter(status_id=2)

关于Django CreateView ModelForm 下拉字段查询集过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21719474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com