AttributeError:“ tuple”对象在Django

时间:2018-09-17 08:12:40

标签: python django

我想将多选字段添加到我的项目应用程序中。此字段应允许用户选择多个选项。但是我得到一个错误。在添加多选字段之前,这部分没有给出任何错误。我的错误在哪里?

我的views.py

def project_new(request):
if request.method == 'POST':
    form = ProjectForm(request.POST)
    if form.is_valid():
        project = Project()
       ...
        project.lang_choices = form.cleaned_data['select_lang']
        project.save()
        return redirect('projects')
else:
    form = ProjectForm()


  return render(request, 'blog/project_new.html', {'form': form})

@login_required(login_url='/login/')
def project_details(request, pk):
    project = get_object_or_404(Project, pk=pk)
    return render(request, 'blog/project_detail.html', {'project': project})

我的模型。py

class ProgrammingLanguage(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
    return self.name
class Project(models.Model):
        ...
        select_langs = models.ManyToManyField(ProgrammingLanguage)
        ...
        slug = models.UUIDField(default=uuid.uuid4)
    ...

forms.py

class ProjectForm(forms.Form):
...
select_lang = forms.ChoiceField(
    label='diller: ',
    widget=forms.CheckboxSelectMultiple()
)

def __init__(self, *args, **kwargs):
    super(ProjectForm, self).__init__(args, kwargs)



       self.fields['select_lang'].choices = [(l.id, l.name) for l in ProgrammingLanguage.objects.all()]


class Meta:
    model = Project
    fields = (
        'first_name', 'last_name', 'email', 'project_name', 'project_description', 'project_notes', 'select_langs')

这是我的回溯

Internal Server Error: /project/new/
Traceback (most recent call last):
  File "/home/eda/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/eda/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/eda/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/eda/.local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/eda/staj_defteri/project/views.py", line 16, in project_new
    if form.is_valid():
  File "/home/eda/.local/lib/python2.7/site-packages/django/forms/forms.py", line 183, in is_valid
    return self.is_bound and not self.errors
  File "/home/eda/.local/lib/python2.7/site-packages/django/forms/forms.py", line 175, in errors
    self.full_clean()
  File "/home/eda/.local/lib/python2.7/site-packages/django/forms/forms.py", line 384, in full_clean
    self._clean_fields()
  File "/home/eda/.local/lib/python2.7/site-packages/django/forms/forms.py", line 396, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "/home/eda/.local/lib/python2.7/site-packages/django/forms/widgets.py", line 240, in value_from_datadict
    return data.get(name)
AttributeError: 'tuple' object has no attribute 'get'
[17/Sep/2018 08:19:35] "POST /project/new/ HTTP/1.1" 500 98194

1 个答案:

答案 0 :(得分:4)

错误可能是因为您使用super(ProjectForm, self).__init__args作为两个参数调用了kwargs,而使用序列解包和字典解包的 not 是两个参数,喜欢:

def __init__(self, *args, **kwargs):
    super(ProjectForm, self).__init__(*args, **kwargs)
    self.fields['select_lang'].choices = [
        (l.id, l.name) for l in ProgrammingLanguage.objects.all()
    ]

如果使用args等进行调用,则第一个参数将包含一个(可能为空)元组作为data参数。如果随后您打算处理data,则将失败。

话虽如此,我不明白您为什么在这里将其设为forms.ChoiceField。默认情况下,Django将选择一个ModelMultipleChoiceField [Django-doc]字段,并且默认情况下还将获取ProgrammingLanguage个对象的整个集合。