В настоящее время я получаю данные из всей базы данных, поэтому я пытаюсь отфильтровать их, а затем передать отфильтрованную модель в форму, чтобы отображались только данные, относящиеся к пользователю. Я сделал это в соответствии с тем, что я нашел в Google, но я получаю эту ошибку:
too many values to unpack (expected 2)
Это не имеет смысла для меня, поскольку я фильтрую данные, как ожидалось. Вот мой код:
модели:
from django.db import models
from django.contrib.auth.models import User
from posts.models import PDF
from children.models import Children
HEADER_CHOICES = [
('Financial Support', 'Financial Support'),
('Educational Support', 'Educational Support'),
('Governmental Support', 'Governmental Support '),
('Charity Support Groups', 'Charity Support Groups'),
('Therapy Support', 'Therapy Support '),
('Transport Support', 'Transport Support ')
]
AGE_CHOICES = [
('0-4', '0-4'),
('4-11', '4-11'),
('11-18', '11-18'),
('18-25', '18-25')
]
class Timeline(models.Model):
header = models.CharField(max_length=30, choices=HEADER_CHOICES)
age = models.CharField(max_length=6, choices=AGE_CHOICES)
child = models.ForeignKey(Children, on_delete=models.CASCADE)
class Pdf(models.Model):
pdf = models.FileField(upload_to='timelinepdfs')
timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE)
дети модели:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.urls import reverse
from django.dispatch import receiver
from django.db.models import signals
DIAGNOSIS_CHOICES = [
(1, ("Yes")),
(2, ("No"))
]
class Children(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
age = models.CharField(max_length=100)
diagnosis = models.IntegerField(
choices= DIAGNOSIS_CHOICES,
)
disability = models.CharField(max_length=100)
parent = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.first_name + " " + self.last_name
def get_absolute_url(self):
return reverse('children-detail', kwargs={'pk': self.pk})
просмотров:
def upload(request):
if request.method == 'POST':
form = TimelineForm(request.POST, request.FILES)
form_pdf = PdfForm(request.POST, request.FILES)
if form.is_valid() and form_pdf.is_valid():
search_result = Timeline.objects.get(
Q(header = form.data['header']) & Q(age = form.data['age']) & Q(child = form.data['child'])
)
form_pdf.instance.timeline = search_result
form_pdf.save()
return redirect('timeline')
else:
children = Children.objects.filter(parent=request.user)
tl = Timeline.objects.filter(child=children)
pdf = Pdf.objects.filter(timeline = tl)
form = TimelineForm(tl)
form_pdf = PdfForm(pdf)
return render(request, 'upload.html', {
'form': form,
'form_pdf': form_pdf
})
Полная ошибка:
Error during template rendering
In template /Users/fetz/Desktop/git/majorProjectEXO/parentsubportal/pages/templates/pages/home_page.html, error at line 9
too many values to unpack (expected 2)
1 {% load static %}
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">{% if title %}
7 <title>ParentSuportal - {{title}}</title>
8 {% else %}
9 <title>ParentSuportal</title>
10 {% endif %}
11 <link rel="icon" href="images/icon.png">
12 <!-- Bootstrap core CSS -->
13 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
14 <!-- <link rel="stylesheet" type="text/css" href="{% static 'pages/stylesheet.css' %}"> -->
15 <style>
16 @import url('https://fonts.googleapis.com/css?family=Bree+Serif|Righteous&display=swap');
17 #logo {
18 font-family: 'Bree Serif';
19 font-size: 40px;
Internal Server Error: /upload/
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/fetz/Desktop/git/majorProjectEXO/parentsubportal/timeline/views.py", line 40, in upload
'form_pdf': form_pdf
File "/usr/local/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/usr/local/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/usr/local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 171, in render
return self._render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 986, in render
output = self.filter_expression.resolve(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 670, in resolve
obj = self.var.resolve(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 795, in resolve
value = self._resolve_lookup(context)
File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 857, in _resolve_lookup
current = current()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 299, in as_p
errors_on_separate_row=True,
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 197, in _html_output
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 308, in non_field_errors
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 175, in errors
self.full_clean()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 376, in full_clean
self._clean_fields()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 388, in _clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "/usr/local/lib/python3.7/site-packages/django/forms/widgets.py", line 658, in value_from_datadict
return getter(name)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 404, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1381, in _add_q
check_filterable=check_filterable,
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1247, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
forms.py:
from django import forms
from .models import Timeline, Pdf
class TimelineForm(forms.ModelForm):
class Meta:
model = Timeline
fields = ('header', 'age', 'child')
class PdfForm(forms.ModelForm):
class Meta:
model = Pdf
fields = ('pdf',)