Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CreateView ModelForm dropdown field queryset filter

Tags:

django

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.

like image 583
dennyreiter Avatar asked Feb 12 '14 05:02

dennyreiter


2 Answers

Try to filter like this.

 self.fields['project'].queryset = Project.objects.filter(status_id=2)
like image 195
CrazyGeek Avatar answered Oct 19 '22 06:10

CrazyGeek


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.

like image 28
user3577915 Avatar answered Oct 19 '22 06:10

user3577915