Моя функция не принимает аргументов, но я получаю эту ошибку not enough values to unpack (expected 2, got 0)
. Я могу напечатать значения на терминале, но не могу отображаться в браузере.
Я извлекаю данные из двух таблиц базы данных (Postgres) и помещаю их в выбранный вход в шаблон Django.
Этот метод предполагает возвращение отображаемых данных
def get_categories():
myvars = {}
sdet = {}
items = CategoriesDB.objects.all()
vals = '<option value="">Please Select Category</option>'
try:
for item in items:
section_id = item.section_id
gname = repr(item.section.section_name)
sdet[section_id] = gname
category_id = item.id
category_name = item.category_name
gcat = {'id': category_id, 'name': category_name}
if section_id not in myvars:
myvars[section_id] = [gcat]
else:
myvars[section_id].append(gcat)
for var in myvars:
otitle = sdet[var]
otl = len(otitle)
tshort = '%s ...' % (otitle[:100]) if otl > 100 else otitle
vals += '<optgroup label="%s" title="%s">' % (tshort, otitle)
gitems = myvars[var]
for i, itm in enumerate(gitems):
gname = str(itm['name'])
itm_id = itm['id']
itl = len(gname)
itms = '%s ...' % (gname[:100]) if itl > 100 else gname
vals += '<option value="%s" title="%s">%s</option>' % (
itm_id, gname, itms)
vals += '</optgroup>'
except Exception as e:
raise e
else:
# on returning vals - I get the error not enough to unpack
return vals
Это файл форм
categories = forms.ChoiceField(
choices=get_categories(),
initial='0',
required=True,
widget=forms.Select(
attrs={'class': 'form-control selectpicker',
'data-size': '10',
'data-live-search': 'true',
'data-style': 'btn-white',
'data-parsley-errors-container': '#gc_error',
'id': 'goods_category'}))
Это файл html
<div class="col-md-5">
<div class="form-group">
<label>Category of Goods <span class="asteriskField">*
</span></label>
{{ form.categories }}
<span id="gc_error"></span>
</div>
</div>
Это трассировка
Environment:
Request Method: GET
Request URL: http://localhost:8000/forms/cargo/
Django Version: 3.0.3
Python Version: 3.7.6
Installed Applications:
('django.contrib.sites',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mins_auth',
'mins_forms',
'mins_main',
'mins_payment',
'mins_reports',
'mins_bonds',
'mins_docs',
'mins_search',
'captcha')
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'corsheaders.middleware.CorsMiddleware']
Template error:
In template C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\templates\base.html, error at line 0
not enough values to unpack (expected 2, got 0)
1 : {% load static %}
2 : <!DOCTYPE html>
3 : <!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
4 : <!--[if !IE]><!-->
5 : <html lang="en">
6 : <!--<![endif]-->
7 : <head>
8 : <meta charset="utf-8" />
9 : <title>Marine Insurance | {% block page_title %}{% endblock %}</title>
10 : <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
Traceback (most recent call last):
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\mins_forms\views.py", line 286, in cargo
raise e
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\mins_forms\views.py", line 284, in cargo
'premium_limit': premium_limit})
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 992, in render
return render_value_in_context(output, context)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\template\base.py", line 971, in render_value_in_context
value = str(value)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\utils\html.py", line 373, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\forms\boundfield.py", line 33, in __str__
return self.as_widget()
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\forms\boundfield.py", line 89, in as_widget
attrs = self.build_widget_attrs(attrs, widget)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\forms\boundfield.py", line 224, in build_widget_attrs
if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\forms\widgets.py", line 700, in use_required_attribute
return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice)
File "C:\Users\NKorir\Desktop\Backup\WorksWell\insurity\venv\lib\site-packages\django\forms\widgets.py", line 686, in _choice_has_empty_value
value, _ = choice
Exception Type: ValueError at /forms/cargo/
Exception Value: not enough values to unpack (expected 2, got 0)
Я перепробовал несколько решений для работы со стеком, но безуспешно. Что я делаю не так?