TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“ QueryDict”

时间:2019-03-25 04:53:05

标签: python django

我正在尝试根据Django中扩展的管理员用户的位置属性形式打印过滤的sub_location下拉列表。 我有一个显示表单并保存相同表单的视图。显示视图没有问题,但是保存时出现以下错误:

TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“ QueryDict”

这是我的代码:-

型号:

class Location(models.Model):
    name = models.CharField(max_length=30)
    def __str__(self):
        return self.name

class SubLocation(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class AdminProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True)

    def __str__(self):  # __unicode__ for Python 2
        return self.user.username


class Batch(models.Model):
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True)
    sub_location = models.ForeignKey(SubLocation, on_delete=models.SET_NULL, null=True)
    batch_name = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.batch_name

表格:

class BatchForm(forms.ModelForm):
    class Meta:
        model = Batch
        fields = ('sub_location', 'batch_name')
    def __init__(self, user, *args, **kwargs):
        super(BatchForm, self).__init__(*args, **kwargs)
        self.fields['sub_location'].queryset = SubLocation.objects.filter(location = Subquery(AdminProfile.objects.filter(user = user).values('location')))

查看:

def add_batch(request):
    if request.user.is_authenticated:
        msg = ""
        if request.method == "GET":
            batch_form = BatchForm(user=request.user)
        else:
            batch_form = BatchForm(request.POST, request.FILES)
            if batch_form.is_valid():
                try:
                    obj = batch_form.save(commit=False)
                    #logined admin location will be here

                    admin_object = AdminProfile.objects.filter(user = request.user)
                    obj.location = admin_object[0].location
                    obj.save()

                    batch_form = BatchForm()
                    msg = "Batch Added successfully....!"
                except IntegrityError as e:
                    msg= "Batch already exist...!"
            else:
                batch_form = BatchForm(request.POST, request.FILES)
        return render(request, 'add_new_batch.html', {'batch_form':batch_form,'msg':msg})
    else:
        return redirect('admin_login')

当我单击“提交”按钮以保存表单时,出现此错误
错误

Internal Server Error: /admin_panel/add_batch
Traceback (most recent call last):
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\monu\Desktop\Task\AdminPanel\views.py", line 34, in add_batch
    batch_form = BatchForm(request.POST, request.FILES)
  File "C:\Users\monu\Desktop\Task\AdminPanel\forms.py", line 27, in __init__
    self.fields['sub_location'].queryset = SubLocation.objects.filter(location = Subquery(AdminProfile.objects.filter(user = user).values('location')))
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 844, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q
    split_subq=split_subq,
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "C:\Users\monu\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py", line 965, in get_prep_value
    return int(value)

TypeError: int() argument must be a string, a bytes-like object or a number, not 'QueryDict'
[25/Mar/2019 09:31:03] "POST /admin_panel/add_batch HTTP/1.1" 500 125516

2 个答案:

答案 0 :(得分:0)

您已在表单的init方法中提供了一个用户参数。在几个情况下,如果您的else子句在实例化表单时没有提供该用户:

else:
        batch_form = BatchForm(request.user,request.POST, request.FILES)

答案 1 :(得分:0)

我遇到了完全相同的问题,

我所做的只是将它作为* args和** kwargs之间的关键字,对我有用!

根据您的代码,试试看!

 batch_form = BatchForm(request.POST, request.FILES, user=request.user)

在您的views.py

 def __init__(self, *args, user=None, **kwargs):
     super(BatchForm, self).__init__(*args, **kwargs)
     self.fields['sub_location'].queryset = SubLocation.objects.filter(location = 
     Subquery(AdminProfile.objects.filter(user = user).values('location')))

在您的表格中。py