gpt4 book ai didi

python - Django 提交无效表单时出错 (VariableDoesNotExist)

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:23 24 4
gpt4 key购买 nike

我有一个表单,可以很好地处理有效数据,但会在处理无效数据时出现奇怪的错误。我不知道是什么原因造成的。

完整回溯:

Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/nyt_hus/9/feedback/

Template error:
In template C:\website\Conference\app\templates\app\nyt_hus_detail.html, error at line 57
Failed lookup for key [%s] in %r 47 : </tr>
48 : </thead>
49 : <tbody>
50 : <tr style="font-weight:bold; font-style:normal;">
51 : <td class="rotated-label fed" rowspan="6">
52 : <span style="top:75%;">Anbefalinger</span>
53 : </td>
54 : <th>Gennemsnitspris pr. uge</th>
55 : <td class="text-center">{{ nythus.price_rec_avg}} kr</td>
56 : <td class="text-center">{{ nythus.price_comp_avg}} kr</td>
57 : <td class="text-center"> {{ nythus.price_rec_avg|percentage_dif:nythus.price_comp_avg }} </td>
58 : </tr>
59 : <tr>
60 : <th style="font-weight: normal;">Medianpris</th>
61 : <td class="text-center">{{ nythus.price_rec_median }} kr</td>
62 : <td class="text-center">{{ nythus.price_comp_median }} kr</td>
63 : <td class="text-center">{{ nythus.price_rec_median|percentage_dif:nythus.price_comp_median }}</td>
64 : </tr>

Traceback:

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in _resolve_lookup
883. current = current[bit]

File "C:\Anaconda3\lib\site-packages\django\template\context.py" in __getitem__
77. raise KeyError(key)

During handling of the above exception ('nythus'), another exception occurred:

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in _resolve_lookup
889. if isinstance(current, BaseContext) and getattr(type(current), bit):

During handling of the above exception (type object 'RequestContext' has no attribute 'nythus'), another exception occurred:

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in _resolve_lookup
898. current = current[int(bit)]

During handling of the above exception (invalid literal for int() with base 10: 'nythus'), another exception occurred:

File "C:\Anaconda3\lib\site-packages\django\core\handlers\base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)

File "C:\Anaconda3\lib\site-packages\django\core\handlers\base.py" in get_response
172. response = response.render()

File "C:\Anaconda3\lib\site-packages\django\template\response.py" in render
160. self.content = self.rendered_content

File "C:\Anaconda3\lib\site-packages\django\template\response.py" in rendered_content
137. content = template.render(context, self._request)

File "C:\Anaconda3\lib\site-packages\django\template\backends\django.py" in render
95. return self.template.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render
206. return self._render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in _render
197. return self.nodelist.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render
992. bit = node.render_annotated(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render_annotated
959. return self.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\loader_tags.py" in render
173. return compiled_parent._render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in _render
197. return self.nodelist.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render
992. bit = node.render_annotated(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render_annotated
959. return self.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\loader_tags.py" in render
69. result = block.nodelist.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render
992. bit = node.render_annotated(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render_annotated
959. return self.render(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in render
1043. output = self.filter_expression.resolve(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in resolve
730. arg_vals.append(arg.resolve(context))

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in resolve
850. value = self._resolve_lookup(context)

File "C:\Anaconda3\lib\site-packages\django\template\base.py" in _resolve_lookup
905. (bit, current)) # missing attribute

Exception Type: VariableDoesNotExist at /nyt_hus/9/feedback/
Exception Value: Failed lookup for key [nythus] in "[{'None': None, 'True': True, 'False': False}, {}, {}, {'form': <ErrorForm bound=True, valid=False, fields=(content)>, 'view': <app.views.FeedbackView object at 0x00000238D00E5390>}]"

模板:

<form role="form" action="{% url 'feedback' pk=nythus.id %}" method="post">
{% csrf_token %}
{{ form.content }}
<button type="submit">Send</button>
</form>

表单.py:

class ErrorForm(forms.Form):
content = forms.CharField(
required=True,
widget=forms.Textarea
)

def __init__(self, *args, **kwargs):
super(ErrorForm, self).__init__(*args, **kwargs)
self.fields['content'].label = "Beskriv fejl"
self.helper = FormHelper()

url.py:

url(r'^nyt_hus/(?P<pk>\d+)/$', views.NytHusDetail.as_view(), name='nyt_hus_detail'),
url(r'^nyt_hus/(?P<pk>\d+)/feedback/$', views.FeedbackView.as_view(), name='feedback'),

views.py:

class NytHusDetail(DetailView, FormMixin):
model = NytHus
template_name = "app/nyt_hus_detail.html"
form_class = ErrorForm

class FeedbackView(FormView):
form_class = ErrorForm
template_name = 'app/nyt_hus_detail.html'

def get_success_url(self, **kwargs):
return reverse_lazy('nyt_hus_detail', kwargs={'pk': self.kwargs['pk']})

def form_valid(self, form, **kwargs):
form_content = form.cleaned_data['content']

template = get_template('error_template.txt')
context = Context({
'form_content': form_content
})
content = template.render(context)

email = EmailMessage(
'mail',
content,
'from@email.com' + '',
['to@email.com']
)
email.send()
return super(FeedbackView, self).form_valid(form, **kwargs)

我使用的是 Django 1.9 和 Python 3.5。

最佳答案

您的 FeedbackView View 使用 app/nyt_hus_detail.html 模板,但您未在模板上下文中包含 nythus

当模板尝试使用 nythus 作为过滤器中的参数时,这会导致 KeyError,例如以下行:

<td class="text-center"> {{ nythus.price_rec_avg|percentage_dif:nythus.price_comp_avg }} </td>

您可以通过重写 get_object_or_404nythus 添加到模板上下文。

from django.shortcuts import get_object_or_404

class FeedbackView(FormView):
...
def get_context_data(self, **kwargs):
context = super(FeedbackView, self).get_context_data(**kwargs)
context['nythus'] = get_object_or_404(NytHus, pk=self.kwargs['pk'])
return context

关于python - Django 提交无效表单时出错 (VariableDoesNotExist),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41706163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com