django test client fails, but url works - django

I'm having a strange problem with some unit tests, which are quite simple, but are failing. The strange thing is that this work with runserver, i.e, I can render the perfil_usuario view, but in unit tests this is failing with NoReverseMatch.
First of all, this my main urlconf:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r"^$", include("traxx.hotsite.urls", namespace="hotsite")),
url(r'^admin/', include(admin.site.urls)),
url(r'^imperavi/', include('imperavi.urls')),
url(r"^app/", include("traxx.sistema.urls", namespace="app")),
url(r"^usuarios/", include("traxx.usuarios.urls", namespace="usuarios")),
url(r"^notificacoes/", include("traxx.notificacoes.urls", namespace="notificacoes")),
url(r"^clientes/", include("traxx.clientes.urls", namespace="clientes")),
)
My usuarios (4th url conf in main) urlconf is the following:
# coding: utf-8
from django.conf.urls import patterns, include, url
urlpatterns = patterns("traxx.usuarios.views",
url(r"^perfil/(?P<id>\d+)/$", "perfil_usuario", name="perfil"),
url(r"^configuracoes/(?P<id>\d+)/$", "configuracoes_usuario", name="configuracoes"),
url(r"^login/$", "login", name="login"),
url(r"^logout/$", "logout", name="logout"),
)
This is the view:
def perfil_usuario(request, id):
usuario = get_object_or_404(Usuario, pk=id)
return render(request, "usuarios/perfil_usuario.html", {"usuario": usuario})
And this is the failing unit test:
class PerfilUsuarioViewTestCase(TransactionTestCase):
"""Testes para a view home"""
def setUp(self):
pass
def test_get_perfil_usuario(self):
usuario_fake = mommy.make(Usuario, nome_usuario="teste")
c = Client()
resposta = c.get(reverse("usuarios:perfil", kwargs={"id": usuario_fake.pk}))
self.assertEqual(200, resposta.status_code)
The reverse call reverse("usuarios:perfil", kwargs={"id": usuario_fake.pk}) works just fine, outputing /usuarios/perfil/1/.
Call to reverse
>>> from django.core.urlresolvers import reverse
>>> reverse("usuarios:perfil", kwargs={"id":1})
/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/imperavi/views.py:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
'/usuarios/perfil/1/'
I'm using Django 1.6.
Full traceback
Traceback (most recent call last):
File "/home/george/projetos/traxx/src/traxx/testes/usuarios/views.py", line 21, in test_get_perfil_usuario
resposta = c.get(reverse("usuarios:perfil", kwargs={"id": usuario_fake.pk}))
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/client.py", line 473, in get
response = super(Client, self).get(path, data=data, **extra)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/client.py", line 280, in get
return self.request(**r)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/client.py", line 444, in request
six.reraise(*exc_info)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/george/projetos/traxx/src/traxx/usuarios/views.py", line 12, in perfil_usuario
return render(request, "usuarios/perfil_usuario.html", {"usuario": usuario})
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 53, in render
return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader.py", line 169, in render_to_string
return t.render(context_instance)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 140, in render
return self._render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
return self.nodelist.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 840, in render
bit = self.render_node(node, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
return node.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 123, in render
return compiled_parent._render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
return self.nodelist.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 840, in render
bit = self.render_node(node, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
return node.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 155, in render
return self.render_template(self.template, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 137, in render_template
output = template.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 140, in render
return self._render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
return self.nodelist.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 840, in render
bit = self.render_node(node, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
return node.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/defaulttags.py", line 447, in render
six.reraise(*exc_info)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/defaulttags.py", line 433, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 509, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 429, in _reverse_with_prefix
(lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'perfil' with arguments '(None,)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'usuarios/perfil/(?P<id>\\d+)/$']

As you can see from the traceback, id passed in kwargs is evaluated to None. This is why it is not matching the usuarios/perfil/(?P<id>\\d+)/$ url pattern.
In other words usuario_fake.pk value is None.
UPD:
the problem was actually in the template which the traceback was complaining about.

Related

filter using the django filter backend on the Multiselectfield

Unable to filter using DjangoFilterBackend, Its returns NULL.
While using other attribute like name or value it works fine.
__basic_fields =('name',)
filter_fields = __basic_fields
It returns correct value.
import django_filters
from rest_framework.viewsets import ModelViewSet
from .models import UserDetails
from .serializer import UserDataSerializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import ListAPIView
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.pagination import LimitOffsetPagination
class MyDetailViewSet(ModelViewSet):
queryset = putDetails.objects.all()
serializer_class = putDataSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
__basic_fields =('stock',)
ilter_fields = __basic_fields
'stock' is Multiselectfield in my models.py.
Should I handle MultiSelect in some other way?
Traceback Traceback (most recent call last): File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response
response = self.process_exception_by_middleware(e, request) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\core\handlers\base.py", line 154, in _get_response
response = response.render() File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\rest_framework\renderers.py", line 733, in render
context = self.get_context(data, accepted_media_type, renderer_context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\rest_framework\renderers.py", line 710, in get_context
'filter_form': self.get_filter_form(data, view, request), File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\rest_framework\renderers.py", line 642, in get_filter_form
html = backend().to_html(request, queryset, view) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django_filters\rest_framework\backends.py", line 105, in to_html
return template.render(context, request) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py", line 199, in render
c = self.get_render(context).flatten() File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py", line 118, in get_render
actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\helper.py", line 308, in render_layout
template_pack=template_pack File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\layout.py", line 140, in render
return self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\layout.py", line 104, in get_rendered_fields
for field in self.fields File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\layout.py", line 104, in <genexpr>
for field in self.fields File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\crispy_forms\utils.py", line 148, in render_field
html = template.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\defaulttags.py", line 309, in render
return nodelist.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\defaulttags.py", line 309, in render
return nodelist.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\defaulttags.py", line 309, in render
return nodelist.render(context) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\template\base.py", line 940, in render
bits.append(str(bit)) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\utils\html.py", line 397, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self)) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\forms\boundfield.py", line 33, in __str__
return self.as_widget() File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\forms\boundfield.py", line 93, in as_widget
renderer=self.form.renderer, File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\forms\widgets.py", line 229, in render
context = self.get_context(name, value, attrs) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\forms\widgets.py", line 668, in get_context
context = super().get_context(name, value, attrs) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\forms\widgets.py", line 629, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs) File "C:\.virtualenvs\Stock-k36TmZyJ\lib\site-packages\django\forms\widgets.py", line 592, in optgroups
for subvalue, sublabel in choices: ValueError: too many values to unpack (expected 2) [12/Apr/2019 12:52:58] "GET /api/usr/ HTTP/1.1" 500 297265

NoReverseMatch URL not being found Django

I'm probably missing something here, but I have a connect page in which the logged in user can chat to another user by clicking on a Chat? link located on each users profile.
The chat functionality is built using Django Channels and is accessed via the url pattern
site/messages/username
where username is the other_user that the current_user is chatting with.
I currently have the chat? link as
<a class='btn btn-light' href="{% url 'thread' username %}" id="chat">Chat?</a>
However that throws the error
NoReverseMatch Reverse for 'thread' not found. 'thread' is not a valid view function or pattern name.
I have tried following the docs and adding username as an arg / taking it off but I keep hitting this same error.
The chat app is included in settings.py and the urls are included in admin.py.
The connect and chat are separate apps.
Below is relevant code. Thank you for your time and help!
chat/urls.py
from django.urls import path, re_path
from .views import ThreadView, InboxView
app_name = 'chat'
urlpatterns = [
path("", InboxView.as_view()),
re_path(r"^(?P<username>[\w.#+-]+)", ThreadView.as_view(), name='thread'),
]
chat/views.py
class ThreadView(LoginRequiredMixin, FormMixin, DetailView):
template_name = 'chat/thread.html'
form_class = ComposeForm
success_url = './'
def get_queryset(self):
return Thread.objects.by_user(self.request.user)
def get_object(self):
other_username = self.kwargs.get("username")
obj, created = Thread.objects.get_or_new(self.request.user, other_username)
if obj == None:
raise Http404
return obj
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = self.get_form()
return context
traceback
Internal Server Error: /connect/
Traceback (most recent call last):
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/xx/xx/project/src/project/connect/views.py", line 15, in connect_home_view
return render(request, 'connect/home.html', context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 171, in render
return self._render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
return self.nodelist.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 937, in render
bit = node.render_annotated(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
return self.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
return self.nodelist.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 937, in render
bit = node.render_annotated(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
return self.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 937, in render
bit = node.render_annotated(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
return self.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
return self.render(context)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/template/defaulttags.py", line 442, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/urls/base.py", line 90, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/xx/xx/project/lib/python3.7/site-packages/django/urls/resolvers.py", line 622, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'thread' with arguments '('',)' not found. 1 pattern(s) tried: ['messages/(?P<username>[\\w.#+-]+)']
[2019/01/27 12:36:43] HTTP GET /connect/ 500 [0.10, 127.0.0.1:50815]
You're using app_name = 'chat'. This makes your app level urls available under the app namespace. See docs: https://docs.djangoproject.com/en/2.1/topics/http/urls/#url-namespaces-and-included-urlconfs
This should work:
{% url 'chat:thread' username %}
Since you have given your app a name in your url app_name = 'chat'
your url must have the name given
<a class='btn btn-light' href="{% url 'chat:thread' username %}" id="chat">Chat?</a>
this is called namespacing in programming

Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried:

I can't seem to spot the error in my code and I have tried everything. It is probably something simple that is escaping my eye. Please help! Any input is appreciated. New Django learner here.
Traceback (most recent call last):
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\doctrinality\doctrinality\Testimony\views.py", line 175, in TestimonyOrderView
return render(request, 'testimony_post.html', {'queryset_list':queryset_list})
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader_tags.py", line 188, in render
return template.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 173, in render
return self._render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\defaulttags.py", line 442, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\base.py", line 90, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py", line 622, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried: ['(?P<id>[0-9]+)/details(?P<format>\\.[a-z0-9]+/?)$', '(?P<id>[0-9]+)/details/$']
[16/Jan/2019 21:58:50] "GET /testimonypost/ HTTP/1.1" 500 187935
template
{%for objects in queryset_list%}
<div class="w3-card-4">
<header class="w3-container w3-blue">
<h1><a href="{% url 'details' testimony.id %}"</a>{{testimony.Title}}</h1>
</header>
<div class="w3-container">
<p>{{objects.body}}</p>
</div>
<footer class="w3-container w3-blue">
</footer>
</div>
<form action="{% url 'testimonydelete'%}" method="POST" style="display">
<button class="glyphicon glyphicon-trash"></button>
</form>
{%endfor%}
models.py
class Testimony(models.Model):
...
def __str__(self):
return int(self.id)
urls.py
urlpatterns = [
...
path('<int:id>/details/', views.detail, name='details'),
]
views.py
def details(request, id=None):
print('1')
testimony=get_object_or_404(Testimony, id=id)
print('2')
return render(request, 'details.html', {'testimony': testimony})
The name of the variable in the for loop is actually objects, for some reason. So, just like you use objects.body to display the body, you need objects.id in the URL:
<h1><a href="{% url 'details' objects.id %}"</a>{{ objects.Title }}</h1>

Django Search Query Fails

I've implemented this search feature on a small site I'm working on and I am having problems when I carry out a search query. This is the traceback:
Traceback (most recent call last):
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__
return self.application(environ, start_response)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__
return self.application(environ, start_response)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 272, in __call__
response = self.get_response(request)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/core/handlers/base.py", line 169, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/core/handlers/base.py", line 203, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/glosseyvilly/PycharmProjects/first_django_dev/apps/photos/views.py", line 113, in search_photos
'search_query': search_query
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/shortcuts/__init__.py", line 44, in render
return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/loader.py", line 188, in render_to_string
return t.render(context_instance)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 123, in render
return self._render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 117, in _render
return self.nodelist.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 744, in render
bits.append(self.render_node(node, context))
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/debug.py", line 73, in render_node
result = node.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/loader_tags.py", line 127, in render
return compiled_parent._render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 117, in _render
return self.nodelist.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 744, in render
bits.append(self.render_node(node, context))
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/debug.py", line 73, in render_node
result = node.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/loader_tags.py", line 64, in render
result = block.nodelist.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 744, in render
bits.append(self.render_node(node, context))
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/debug.py", line 73, in render_node
result = node.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/defaulttags.py", line 311, in render
return self.nodelist_true.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 744, in render
bits.append(self.render_node(node, context))
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/debug.py", line 73, in render_node
result = node.render(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/defaulttags.py", line 227, in render
nodelist.append(node.render(context))
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 915, in render
resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 653, in resolve
value = self._resolve_lookup(context)
File "/Users/glosseyvilly/Desktop/web_dev/ccdev/lib/python2.6/site-packages/django/template/base.py", line 692, in _resolve_lookup
raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute
TemplateSyntaxError: Caught VariableDoesNotExist while rendering: Failed lookup for key [user] in u"'uploaded_photos/Published/2011/December/21/image_5.jpeg'"
This is my view function:
def search_photos(request):
"""
"""
search_query = ''
results = None
if ('q' in request.GET) and request.GET['q'].strip():
search_query = request.GET['q']
photo_query = get_query(search_query, ['caption',])
results = Photo.objects.filter(photo_query).order_by('-date_added')
return render(request, 'photos/search.html', {
'results': results,
'search_query': search_query
})
NB: The traceback highlights 'search_query': search_query being a possible error and I'm not sure why.
EDIT: Here is a link to my search.html template : gist.github.com/1524911
You need to format the error message as a code block.
The specific error is at the end of the traceback: Failed lookup for key [user] in u"'uploaded_photos/Published/2011/December/21/image_5.jpeg'" which occurred in _resolve_lookup. This is the routine that does the variable value fetching for templates.
I would take a hard look at the template. Pay special attention to any tricky loop references or template tags that might be doing strange lookups (e.g {% expr %} comes to mind). Let us know what you come up with.
Update:
My money is on the line:
{% phileo_widget result.user result %}
Does the result object have an attribute named user?
Shouldn't your method take self as its first parameter?:
def search_photos(self):
So, you access the request object with:
request = self.request

Why is Django-lean test failing with "NoReverseMatch: Reverse for 'opensearch' with arguments '()' and keyword arguments '{}' not found."

I'm confused why my tests won't pass for the Django-lean module.
======================================================================
ERROR: testIntegrationWithRegisteredUser (django_lean.experiments.tests.test_tags.ExperimentTagsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/django_lean-0.15-py2.7.egg/django_lean/experiments/tests/test_tags.py", line 55, in testIntegrationWithRegisteredUser
client_factory=create_registered_user_client)
File "/usr/local/lib/python2.7/site-packages/django_lean-0.15-py2.7.egg/django_lean/experiments/tests/test_tags.py", line 71, in doTestIntegration
response = client.get(confirm_human_url)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/test/client.py", line 290, in get
response = self.request(**r)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/test/client.py", line 230, in request
response = self.handler(environ)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/test/client.py", line 74, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/core/handlers/base.py", line 142, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/core/handlers/base.py", line 181, in handle_uncaught_exception
return callback(request, **param_dict)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/views/defaults.py", line 24, in server_error
return http.HttpResponseServerError(t.render(Context({})))
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/__init__.py", line 173, in render
return self._render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/test/utils.py", line 29, in instrumented_test_render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/__init__.py", line 796, in render
bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/__init__.py", line 809, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/loader_tags.py", line 125, in render
return compiled_parent._render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/test/utils.py", line 29, in instrumented_test_render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/__init__.py", line 796, in render
bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/__init__.py", line 809, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/defaulttags.py", line 378, in render
raise e
NoReverseMatch: Reverse for 'opensearch' with arguments '()' and keyword arguments '{}' not found.
----------------------------------------------------------------------
Ran 1 test in 1736.834s
Here is the test:
class ExperimentTagsTest(TestCase):
urls = 'django_lean.experiments.tests.urls'
def setUp(self):
self.experiment = Experiment(name="test_experiment")
self.experiment.save()
self.experiment.state = Experiment.ENABLED_STATE
self.experiment.save()
self.other_experiment = Experiment(name="other_test_experiment")
self.other_experiment.save()
self.other_experiment.state = Experiment.ENABLED_STATE
self.other_experiment.save()
self.mox = mox.Mox()
def testIntegrationWithRegisteredUser(self):
def create_registered_user_client(i):
user = User(username="user%s" % i, email="user%s#example.com" % i)
user.set_password("password")
user.save()
client = Client()
if not client.login(username=user.username, password="password"):
raise Exception("login failure")
return client
self.doTestIntegration(
url=reverse('django_lean.experiments.tests.views.experiment_test',
args=[self.experiment.name]),
client_factory=create_registered_user_client)
def doTestIntegration(self, url, client_factory):
confirm_human_url = reverse('django_lean.experiments.views.confirm_human')
# confirm_human_url set to '/main-app/confirm_human/' during test
found_control = False
found_test = False
for i in range(100):
client = client_factory(i)
import pdb; pdb.set_trace()
response = client.get(confirm_human_url) # this is where the Client can't find the url
self.assertEquals(204, response.status_code)
response = client.get(url)
self.assertEquals(200, response.status_code)
in_test = "test" in response.content.lower()
in_control = "control" in response.content.lower()
self.assertTrue(in_test != in_control)
found_control = found_control or in_control
found_test = found_test or in_test
self.assertTrue(found_control)
self.assertTrue(found_test)
This is the View, django_lean.experiments.views.confirm_human
#never_cache
def confirm_human(request):
experiment_user = WebUser(request)
experiment_user.confirm_human()
return HttpResponse(status=204)
Finally, this is the URL patterns from django_lean.experiments.urls :
urlpatterns = patterns('django_lean.experiments.views',
url(r'^goal/(?P<goal_name>.*)$', 'record_experiment_goal'),
url(r'^confirm_human/$', 'confirm_human')
)
I don't understand why the client.get request can't be followed.
Update Couldn't find any reference to opensearch in Django-lean source. Are you using a Django opensearch plugin or is some other app referring to opensearch? Try searching for opensearch in your project.
Original Answer
At first blush it seems that one of the templates is using an {% url %} tag with argument opensearch. At least that is what I suspect based on the following lines in the error trace.
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/__init__.py", line 809, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.1-py2.7.egg/django/template/defaulttags.py", line 378, in render
raise e
I am not familiar with Django-lean but I think it will be worrh checking if they have an URL named opensearch.