将变量从views.py传递到forms.py会导致在提交表单时发生错误

时间:2018-07-23 09:09:00

标签: python django

我已经将一些变量从视图传递到表单,以使用它过滤表单中的某些字段。但是当我点击表单中的“提交”按钮时,就会出现错误。

KeyError at /add_ad/mod/
'cat'

这里是错误的完整回溯:

Traceback:

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\views.py" in add_ad_mod
  210.         add_ad_mod_form = AddAdModForm(request.POST, request.FILES)

File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\forms.py" in __init__
  47.         current_categ = kwargs.pop('cat')

Exception Type: KeyError at /add_ad/mod/
Exception Value: 'cat'

这是我用于文件的代码:

views.py

def add_ad_mod(request):
    current_user = request.user
    current_ip = get_client_ip(request)
    selected  = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0]
    selected_category = selected.cat
    selected_town = selected.town
    add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town)
    if request.method == 'POST':
        add_ad_mod_form = AddAdModForm(request.POST, request.FILES)
        if add_ad_mod_form.is_valid():
            model_instance = add_ad_mod_form.save(commit=False)
            model_instance.created_by = current_user.email
            model_instance.category = selected_category
            model_instance.town=selected_town
            if request.user.is_superuser:
                model_instance.is_active = True
            else:
                model_instance.is_active = False
            add_ad_mod_form.save()
            return redirect('dashboard')
    else:
        add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town)

    context = {
        'add_ad_mod_form': add_ad_mod_form,
        'selected_category': selected_category,
        'selected_town': selected_town,
    }
    return render(request, 'add_ad_mod.html', context)

Forms.py

class AddAdModForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        current_categ = kwargs.pop('cat')
        current_loc = kwargs.pop('loc')
        super(AddAdModForm, self).__init__(*args, **kwargs)
        self.fields['sub_category'] = forms.ChoiceField(label="Sniffer", choices=[(x, x) for x in
                                                                          SubCate.objects.filter(main_category=current_categ)])
        self.fields['sub_location'] = forms.MultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", choices=[(x, x) for x in
                                                                          SubLoc.objects.filter(main_town=current_loc)])

    title = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Ad Title here',
                'style': 'width: 100%; max-width: 800px;'
            }
        )
    )

    description = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'placeholder': 'Ad description is here',
                'style': 'width: 100%; max-width: 800px;'
            }
        )
    )

    image = forms.ImageField(required=True)
    image2 = forms.ImageField(required=False)
    image3 = forms.ImageField(required=False)
    image4 = forms.ImageField(required=False)
    image5 = forms.ImageField(required=False)



    address = forms.CharField(max_length=100,
        widget=forms.Textarea(
            attrs={
                'placeholder': 'Detailed Address is here ',
                'style': 'width: 100%; max-width: 800px;'
            }
        )
    )

    class Meta:
        model = Item
        fields = ['title', 'sub_category', 'price', 'description', 'sub_location', 'address', 'image', 'image2', 'image3', 'image4',
                  'image5', 'phone']

我发现current_categ = kwargs.pop('cat')行中出现了错误,但是我找不到原因。

更新

遵循下面显示的答案后,它给了我错误

Traceback:

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\views.py" in add_ad_mod
  219.             add_ad_mod_form.save()

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in save
  457.             self._save_m2m()

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in _save_m2m
  439.                 f.save_form_data(self.instance, cleaned_data[f.name])

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related.py" in save_form_data
  1619.         getattr(instance, self.attname).set(data)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py" in set
  969.                     self.add(*new_objs)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py" in add
  898.                 self._add_items(self.source_field_name, self.target_field_name, *objs)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py" in _add_items
  1045.                             '%s__in' % target_field_name: new_ids,

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in filter
  836.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  854.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in add_q
  1253.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1277.                     split_subq=split_subq,

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1215.         condition = self.build_lookup(lookups, col, value)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1085.         lookup = lookup_class(lhs, rhs)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\lookups.py" in __init__
  18.         self.rhs = self.get_prep_lookup()

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_lookups.py" in get_prep_lookup
  59.                 self.rhs = [target_field.get_prep_value(v) for v in self.rhs]

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_lookups.py" in <listcomp>
  59.                 self.rhs = [target_field.get_prep_value(v) for v in self.rhs]

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  947.         return int(value)

Exception Type: ValueError at /add_ad/mod/
Exception Value: invalid literal for int() with base 10: 's'

1 个答案:

答案 0 :(得分:4)

您已经告诉代码期望参数catloc,但是您只是从GET块的视图中传递它们,而不是POST块。您需要两次通过它们。

add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category, loc=selected_town)

(注意,在if语句之前,您有不必要的额外实例化;应该删除该实例。)

编辑正如我在评论中提到的那样,您不应将基本选择字段用于关系。

self.fields['sub_category'] = forms.ModelChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
self.fields['sub_location'] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))