AttributeError:“ tuple”对象没有属性“ get”

时间:2019-08-15 19:45:52

标签: python django python-3.x django-forms

我在Django中遇到问题,我真的不知道错误是什么。错误发生在UpdateView视图中,当在视图中放置多个input时,可以准确地知道错误的位置,因为我没有发现它,因此在视图中不会发生错误,我认为是这样的形式:

class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ['title', 'subtitle', 'image', 'description', 'status']

        widgets = {
            'title': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Titulo'}),
            'subtitle': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Subtitulo'}),
            'image': forms.FileInput(attrs = {'class': 'custom-file-input'}),
            'description': forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Descripcion'}),
            'status': forms.Select(attrs = {'class': 'custom-select'}),
        }

        labels = {'title': '', 'subtitle': '', 'image': '', 'description': ''}

    def __init__(self, *args, **kwargs):
        self.title_valid = False 
        if 'title_valid' in kwargs:
            self.title_valid = kwargs.pop('title_valid')

        super().__init__(args, kwargs)

    def clean_title(self):
        title = self.cleaned_data['title']
        if self.title_valid:
            if Course.objects.filter(title = title).exists():
                raise forms.ValidationError('Ya existe un curso registrado con ese titulo, elige otro.')

        return title

我还可以看到clean_title方法没有执行,在那里发生了错误……

查看:

class CourseUpdateView(UpdateView):
    model = Course
    form_class = CourseForm
    template_name = 'instructor/course_update_form.html'
    success_url = reverse_lazy('instructor:course:list')
    success_message = 'Se modificó con éxito el curso "{}".'

    def get_form(self, form_class = None):
        if form_class is None:
            form_class = self.get_form_class()

        form = form_class(**self.get_form_kwargs(), title_valid = True)
        for field in form.fields.keys():
            form.fields[field].required = False

        return form

    def form_valid(self, form):
        obj = form.save(commit = False)
        obj.slug = slugify(obj.title)
        obj.save()

        messages.success(self.request, self.success_message.format(obj.title))
        return redirect(self.success_url)

完全错误:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
August 15, 2019 - 19:44:47
Django version 2.2.2, using settings 'IBME.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /instructor/course/curso-practico-de-django-aprende-creando-3-webs/update
Traceback (most recent call last):
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/forms/forms.py", line 163, in __getitem__
    field = self.fields[name]
KeyError: 'errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/forms/forms.py", line 169, in __getitem__
    ', '.join(sorted(f for f in self.fields)),
KeyError: "Key 'errors' not found in 'CourseForm'. Choices are: description, image, status, subtitle, title."

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    content = template.render(context, self._request)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/defaulttags.py", line 302, in render
    match = condition.eval(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/defaulttags.py", line 876, in eval
    return self.value.resolve(context, ignore_failures=True)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors
    self.full_clean()
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/forms/forms.py", line 381, in full_clean
    self._clean_fields()
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/forms/forms.py", line 393, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/forms/widgets.py", line 258, in value_from_datadict
    return data.get(name)
AttributeError: 'tuple' object has no attribute 'get'

1 个答案:

答案 0 :(得分:1)

您的错误采用init形式;您传递了args和kwargs而不扩展它们。应该是:

    super().__init__(*args, **kwargs)

但是请注意,代码通常很奇怪;我不明白为什么您在get_form中拥有所有自定义逻辑。