简体   繁体   English

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

[英]Passing variables from views.py to forms.py causes an error when form submitt

I've passed some variables from my views to forms to use it filtering some fields in the forms. 我已经将一些变量从视图传递到表单,以使用它过滤表单中的某些字段。 but when I hit the submit button in the form it gives me the error. 但是当我点击表单中的提交按钮时,它给了我错误。

KeyError at /add_ad/mod/
'cat'

Here are the full traceback of the error : 这是错误的完整回溯:

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'

And here are the codes I've used for my files : 这是我用于文件的代码:

views.py 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 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']

I see that the error leys in the line current_categ = kwargs.pop('cat') but I can't find out what is the reason for it. 我看到在current_categ = kwargs.pop('cat')行中出现了错误,但是我找不到原因。

UPDATE 更新

After following the answer showing below it gave me the error 按照下面显示的答案后,它给了我错误

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'

You've told the code to expect the arguments cat and loc , but you're only passing them from the view in the GET block, not the POST one. 您已经告诉代码期望使用参数catloc ,但是只从GET块中的视图传递它们,而不是POST传递。 You need to pass them both times. 您需要两次通过它们。

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

(Note, you've got an unnecessary extra instantiation before the if statement; you should remove that.) (请注意,在if语句之前有不必要的额外实例化;应该将其删除。)

Edit As I mentioned in the comments, you shouldn't use basic choice fields for relationships. 编辑正如我在评论中提到的那样,您不应将基本选择字段用于关系。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM