Django CreateView ModelForm下拉字段queryset过滤器 [英] Django CreateView ModelForm dropdown field queryset filter
本文介绍了Django CreateView ModelForm下拉字段queryset过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我第一次使用Django(1.6),但我一直无法弄清楚:
This is my first real go with Django (1.6) and I haven't been able to figure this out:
我正试图限制CreateView仅显示在项目模型中具有活动状态(2)的项目:
I'm trying to limit a dropdown on a CreateView to only show projects that have an active status (2) in the Project model:
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()
我的form.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)
和我的CreateView从views.py:
and my CreateView from views.py:
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)
我改为:
If I change my filter to be (Project.status.id == 2)
I instead get:
AttributeError at /log/add/
'ReverseSingleRelatedObjectDescriptor' object has no attribute 'id'
我想我已经接近了,但是显然我没有足够的把握。有任何想法吗?谢谢。
I think I'm close but don't quite have the firm grasp I need apparently. Any ideas? Thanks.
推荐答案
尝试像这样过滤。
self.fields['project'].queryset = Project.objects.filter(status_id=2)
这篇关于Django CreateView ModelForm下拉字段queryset过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文