

Djangoのポートフォリオサイト作成として、  
現在、サッカーゲームサイトの作成を目指して、プログラム作成を行っております。

同じ内容で既に [teratail でも質問しています](https://teratail.com/questions/364713) が、  
回答が得られなかったこともあり、本サイトに質問させて頂きました。

views.pyの「skill_form」へのリスト化し、  
格納までは、print(skill_form)にて確認が取ることが出来ましたが、  
そこからどの部分が問題となり、該当のエラーになってしまったかという点が、  
未だわかっていない状況です。

認識含めて甘い部分もあるかと思いますが、  
ご教示頂けると幸いです。

質問の仕方や質問内容に不明点があれば、随時ご指摘いただけると幸いです。

宜しくお願い致します。

**エラー内容**

[code]

    Internal Server Error: /detail/1/edit/
    Traceback (most recent call last):
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
        response = get_response(request)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
        return view_func(request, *args, **kwargs)
      File "/Users/hm/MyPort/pesproject/pes21/views.py", line 76, in playerupdateview
        if player_form.is_valid() and ability_form.is_valid() and formation_form.is_valid() and skill_form.is_valid():
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/forms/forms.py", line 175, in is_valid
        return self.is_bound and not self.errors
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/forms/forms.py", line 170, in errors
        self.full_clean()
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/forms/forms.py", line 372, in full_clean
        self._clean_fields()
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/forms/forms.py", line 384, in _clean_fields
        value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/forms/widgets.py", line 263, in value_from_datadict
        return data.get(name)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/query.py", line 424, in get
        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/query.py", line 941, in filter
        return self._filter_or_exclude(False, args, kwargs)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
        clone._filter_or_exclude_inplace(negate, args, kwargs)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
        self._query.add_q(Q(*args, **kwargs))
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q
        clause, _ = self._add_q(q_object, self.used_aliases)
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
        child_clause, needed_inner = self.build_filter(
      File "/Users/hm/MyPort/myvenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1283, in build_filter
        arg, value = filter_expr
    ValueError: too many values to unpack (expected 2)
    
[/code]

**defaulttags.py(filter_exprの代入時の情報です)**

[code]

    @register.tag('filter')
    def do_filter(parser, token):
        """
        Filter the contents of the block through variable filters.
    
        Filters can also be piped through each other, and they can have
        arguments -- just like in variable syntax.
    
        Sample usage::
    
            {% filter force_escape|lower %}
                This text will be HTML-escaped, and will appear in lowercase.
            {% endfilter %}
    
        Note that the ``escape`` and ``safe`` filters are not acceptable arguments.
        Instead, use the ``autoescape`` tag to manage autoescaping for blocks of
        template code.
        """
        # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
        _, rest = token.contents.split(None, 1)
        filter_expr = parser.compile_filter("var|%s" % (rest))
        for func, unused in filter_expr.filters:
            filter_name = getattr(func, '_filter_name', None)
            if filter_name in ('escape', 'safe'):
                raise TemplateSyntaxError('"filter %s" is not permitted.  Use the "autoescape" tag instead.' % filter_name)
        nodelist = parser.parse(('endfilter',))
        parser.delete_first_token()
        return FilterNode(filter_expr, nodelist)
    
[/code]

**query.py**

[code]

    def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
                         can_reuse=None, allow_joins=True, split_subq=True,
                         reuse_with_filtered_relation=False, check_filterable=True):
            """
            Build a WhereNode for a single filter clause but don't add it
            to this Query. Query.add_q() will then add this filter to the where
            Node.
    
            The 'branch_negated' tells us if the current branch contains any
            negations. This will be used to determine if subqueries are needed.
    
            The 'current_negated' is used to determine if the current filter is
            negated or not and this will be used to determine if IS NULL filtering
            is needed.
    
            The difference between current_negated and branch_negated is that
            branch_negated is set on first negation, but current_negated is
            flipped for each negation.
    
            Note that add_filter will not do any negating itself, that is done
            upper in the code by add_q().
    
            The 'can_reuse' is a set of reusable joins for multijoins.
    
            If 'reuse_with_filtered_relation' is True, then only joins in can_reuse
            will be reused.
    
            The method will create a filter clause that can be added to the current
            query. However, if the filter isn't added to the query then the caller
            is responsible for unreffing the joins used.
            """
            if isinstance(filter_expr, dict):
                raise FieldError("Cannot parse keyword query as dict")
            if isinstance(filter_expr, Q):
                return self._add_q(
                    filter_expr,
                    branch_negated=branch_negated,
                    current_negated=current_negated,
                    used_aliases=can_reuse,
                    allow_joins=allow_joins,
                    split_subq=split_subq,
                    check_filterable=check_filterable,
                )
            if hasattr(filter_expr, 'resolve_expression'):
                if not getattr(filter_expr, 'conditional', False):
                    raise TypeError('Cannot filter against a non-conditional expression.')
                condition = self.build_lookup(
                    ['exact'], filter_expr.resolve_expression(self, allow_joins=allow_joins), True
                )
                clause = self.where_class()
                clause.add(condition, AND)
                return clause, []
            arg, value = filter_expr
            if not arg:
                raise FieldError("Cannot parse keyword query %r" % arg)
            lookups, parts, reffed_expression = self.solve_lookup_type(arg)
    
            if check_filterable:
                self.check_filterable(reffed_expression)
    
            if not allow_joins and len(parts) > 1:
                raise FieldError("Joined field references are not permitted in this query")
    
            pre_joins = self.alias_refcount.copy()
            value = self.resolve_lookup_value(value, can_reuse, allow_joins)
            used_joins = {k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)}
    
            if check_filterable:
                self.check_filterable(value)
    
            clause = self.where_class()
            if reffed_expression:
                condition = self.build_lookup(lookups, reffed_expression, value)
                clause.add(condition, AND)
                return clause, []
    
            opts = self.get_meta()
            alias = self.get_initial_alias()
            allow_many = not branch_negated or not split_subq
    
            try:
                join_info = self.setup_joins(
                    parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many,
                    reuse_with_filtered_relation=reuse_with_filtered_relation,
                )
    
                # Prevent iterator from being consumed by check_related_objects()
                if isinstance(value, Iterator):
                    value = list(value)
                self.check_related_objects(join_info.final_field, value, join_info.opts)
    
                # split_exclude() needs to know which joins were generated for the
                # lookup parts
                self._lookup_joins = join_info.joins
            except MultiJoin as e:
                return self.split_exclude(filter_expr, can_reuse, e.names_with_path)
    
            # Update used_joins before trimming since they are reused to determine
            # which joins could be later promoted to INNER.
            used_joins.update(join_info.joins)
            targets, alias, join_list = self.trim_joins(join_info.targets, join_info.joins, join_info.path)
            if can_reuse is not None:
                can_reuse.update(join_list)
    
            if join_info.final_field.is_relation:
                # No support for transforms for relational fields
                num_lookups = len(lookups)
                if num_lookups > 1:
                    raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0]))
                if len(targets) == 1:
                    col = self._get_col(targets[0], join_info.final_field, alias)
                else:
                    col = MultiColSource(alias, targets, join_info.targets, join_info.final_field)
            else:
                col = self._get_col(targets[0], join_info.final_field, alias)
    
            condition = self.build_lookup(lookups, col, value)
            lookup_type = condition.lookup_name
            clause.add(condition, AND)
    
            require_outer = lookup_type == 'isnull' and condition.rhs is True and not current_negated
            if current_negated and (lookup_type != 'isnull' or condition.rhs is False) and condition.rhs is not None:
                require_outer = True
                if lookup_type != 'isnull':
                    # The condition added here will be SQL like this:
                    # NOT (col IS NOT NULL), where the first NOT is added in
                    # upper layers of code. The reason for addition is that if col
                    # is null, then col != someval will result in SQL "unknown"
                    # which isn't the same as in Python. The Python None handling
                    # is wanted, and it can be gotten by
                    # (col IS NULL OR col != someval)
                    #   <=>
                    # NOT (col IS NOT NULL AND col = someval).
                    if (
                        self.is_nullable(targets[0]) or
                        self.alias_map[join_list[-1]].join_type == LOUTER
                    ):
                        lookup_class = targets[0].get_lookup('isnull')
                        col = self._get_col(targets[0], join_info.targets[0], alias)
                        clause.add(lookup_class(col, False), AND)
                    # If someval is a nullable column, someval IS NOT NULL is
                    # added.
                    if isinstance(value, Col) and self.is_nullable(value.target):
                        lookup_class = value.target.get_lookup('isnull')
                        clause.add(lookup_class(value, False), AND)
            return clause, used_joins if not require_outer else ()
    
[/code]

**detail_edit.html**

[code]

        {% extends "pes21/base.html" %} {% load widget_tweaks %} {% block content %}
    
              <h5 class="card-title text-center">スキル編集</h5>
                <table class="profile_table mb-4">
                  <tbody>
                  {% for skill_item in skill_form %}
                    <tr>
                      <th class="header">スキル</th>
                      <td class="data form_wrap form_wrap-2">
                        {% render_field skill_item.player_skill class='form-control' placeholder='スキル入力' %}
                      </td>
                    </tr>
                  {% endfor %}
                  </tbody>
                　</table>
    
                <div class="button mx-auto">
                  <button class="btn btn-1g btn-warning btn-block" type="submit">
                    登録する
                  </button>
                </div>
              </form>
            </div>
          </div>
        </form>
      </div>
    </div>
    {% endblock content %}
    
[/code]

**views.py**

[code]

    @login_required
    def playerupdateview(request, pk):
            player = get_object_or_404(Player, pk=pk)
            ability = Ability.objects.filter(player=pk)[0]
            skill_query_set = Skill.objects.filter(player=pk)
            skillobj_kwarg = skill_query_set.values() 
            formation = Formation.objects.filter(player=pk)[0]
            
            playerobj_kwarg = {
                'date_field':player.date_field,'initial':player.initial,'maximum':player.maximum,'level':player.level,
                'player_name':player.player_name,'category':player.category,'position_category':player.position_category,'league_category':player.league_category,
                'country':player.country,'club':player.club,'age':player.age,'height':player.height,
                'dominant_foot':player.dominant_foot,'playstyle':player.playstyle,'player_image':player.player_image,
                }
            abilityobj_kwarg = {
                'offense_sense':ability.offense_sense,'ball_control':ability.ball_control,'dribble':ability.dribble,'ball_keep':ability.ball_keep,
                'grander_pass':ability.grander_pass,'fly_pass':ability.fly_pass,'determining_power':ability.determining_power,'heading':ability.heading,
                'place_kick':ability.place_kick,'curve':ability.curve,'speed':ability.speed,'instantaneous_power':ability.instantaneous_power,
                'kick_power':ability.kick_power,'jumping':ability.jumping,'physical_contact':ability.physical_contact,
                'body_control':ability.body_control,'physical_fitness':ability.physical_fitness,'defense_sense':ability.defense_sense,
                'take_the_ball':ability.take_the_ball,'aggressiveness':ability.aggressiveness,'gksense':ability.gksense,
                'catching':ability.catching,'clearing':ability.clearing,'cobraging':ability.cobraging,
                'deflectiveing':ability.deflectiveing,'reverse_foot_frequency':ability.reverse_foot_frequency,'reverse_foot_accuracy':ability.reverse_foot_accuracy,
                'condition_stability':ability.condition_stability,'injury_resistance':ability.injury_resistance,
                }
            
            formationobj_kwarg = {
                'formation_images':formation.formation_images
                }
    
            player_form = PlayerEditForm(request.POST or playerobj_kwarg)
            ability_form = AbilityEditForm(request.POST or abilityobj_kwarg)
            skill_form = SkillEditForm(request.POST or skillobj_kwarg)
            formation_form = FormationEditForm(request.POST or formationobj_kwarg)
    
            print(skill_form)
            if player_form.is_valid() and ability_form.is_valid() and formation_form.is_valid() and skill_form.is_valid():
                plyaer_data = player_form.save(commit=False)
                plyaer_data.save()
                ability_data = ability_form.save(commit=False)
                ability_data.save()
                formation_data = formation_form.save(commit=False)
                formation_data.save()
                skill_data = skill_form.save(commit=False)
                skill_data.player = player
                skill_data.save()
                return redirect('detail', id=player.id)
            
            return render(request, 'pes21/detail_edit.html', {
                'player_form' : player_form,
                'ability_form' : ability_form,
                'skill_form' : skill_form,
                'formation_form' : formation_form
            }) 
    
[/code]

**models.py**

[code]

    class Skill(models.Model):
        player = models.ForeignKey(Player, on_delete=models.CASCADE)
        player_skill = models.CharField('スキル入力', max_length=20, blank=True, null=True)
    
[/code]

**forms.py**

[code]

    class SkillEditForm(forms.Form):
        player_skill = forms.CharField(label='スキル入力', max_length=20)
    
[/code]


CC BY-SA 4.0
2021-11-24T12:13:32.357
83788
2021-11-27T10:51:46.787
2021-11-27T10:51:46.787
48697
48697
question
python html django
too many values to unpack (expected 2)のDjangoFormのデータ抽出について