This is my first real go with Django (1.6) and I haven't been able to figure this out:
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()
My 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)
and my CreateView from views.py:
class WorklogCreate(CreateView):
form_class = WorklogCreateForm
success_url = reverse_lazy('dashboard')
But I get the error:
TypeError at /log/add/
'bool' object has no attribute '__getitem__'
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.
Try to filter like this.
self.fields['project'].queryset = Project.objects.filter(status_id=2)
You were close, but for some reason mixed in what looks like SQLAlchemy syntax.
Also, the idea of filtering your queryset by an arbitrarily assigned number (the PK) is absurd.
self.fields['project'].queryset = Project.objects.filter(status__name="foo")
would make a lot more sense, if only your status name were marked unique=True
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With