外键未显示在Django中的ModelForm下拉列表中

时间:2013-10-06 07:07:36

标签: django django-forms

这是我的模特:

class Task(models.Model):

    description = models.CharField(max_length=128)
    owner = models.ForeignKey(User, default="bride")
    category = models.ForeignKey(Category)

这是我的ModelForm:

class TaskForm(ModelForm):
    class Meta:
       model = Task
       exclude = ['owner']

    def __init__(self, user, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['category'].queryset = Task.objects.filter(category=user)

在视图中,我传递的形式如下:

 form = TaskForm(user=request.user.id)

现在,在表单中没有显示类别的下拉列表。是的,我已经为登录用户创建了类别。

当我在不输入类别的情况下保存表单时,它会显示:

int() argument must be a string or a number, not 'QueryDict'

怎么了?

修改

完整视图:

class ToDoView(View):
    def get(self, request):
        form = TaskForm(user=request.user.id)
        tasks = Task.objects.filter(owner=request.user.id)
        return render(request, 'website/todo.html', {'form': form, 'tasks': tasks})


    def post(self, request):
        form = TaskForm(request.POST)
        if form.is_valid():
            description = form.cleaned_data['description']
            category = form.cleaned_data['category']
            status = form.cleaned_data['status']
            deadline = form.cleaned_data['deadline']
            cost = form.cleaned_data['cost']
            task = Task(description=description, owner=request.user, category=category, status=status,
                        deadline=deadline, cost=cost)
            task.save()
            messages.success(request, 'Tasks successfully added.')
            return HttpResponseRedirect('/todo_list/')

        else:
            return render(request, 'website/todo.html', {'form': form})

完整追溯:

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  86.         return handler(request, *args, **kwargs)
File "/home/sachitad/thomas/wedplan/wedplan/website/views.py" in post
  96.         form = TaskForm(request.POST)
File "/home/sachitad/thomas/wedplan/wedplan/website/forms.py" in __init__
  24.         self.fields['category'].queryset = Category.objects.filter(user__id=user)
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py" in filter
  155.         return self.get_query_set().filter(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py" in filter
  669.         return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  687.             clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1271.                             can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_filter
  1202.                 connector)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/where.py" in add
  71.             value = obj.prepare(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/where.py" in prepare
  339.             return self.field.get_prep_lookup(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
  322.             return self.get_prep_value(value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  555.         return int(value)

Exception Type: TypeError at /todo/
Exception Value: int() argument must be a string or a number, not 'QueryDict'

1 个答案:

答案 0 :(得分:1)

您需要Category而不是Task的过滤查询。另外,pop在调用超级的init之前传递了user参数。

class TaskForm(ModelForm):
    class Meta:
       model = Task
       exclude = ['owner']

    def __init__(self, user, *args, **kwargs):
        userid = kwargs.pop('user')
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.filter(user__id=userid)
        # assuming your Category model has user foreignkey/onetone field.