6

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.

BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70
dennyreiter
  • 65
  • 1
  • 5

2 Answers2

5

Try to filter like this.

 self.fields['project'].queryset = Project.objects.filter(status_id=2)
CrazyGeek
  • 3,397
  • 2
  • 24
  • 38
  • Thanks! That got me past that error, but now my form doesn't seem to be created. First the view complained that no template_name was defined and after I specified it, then it stops at rendering, saying the form attributes don't exist. I'm going to keep digging until I find out how deep this hole is :) – dennyreiter Feb 12 '14 at 14:25
  • 2
    I moved the query into def get_form() of my CreateView (which I wanted initially) and now it seems to work. Thanks so much for your help. – dennyreiter Feb 12 '14 at 14:29
1

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.