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
Related
i work in pythonanywhere and i have run a signup script - local it works without problems in pythonanywhere i get this error
2020-09-13 15:37:43,507: Internal Server Error: /signup1/
Traceback (most recent call last):
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/username/werkvertragrepo/werkvertrag/views.py", line 612, in signup1
text_body = render_to_string('acc_active_email.txt', merge_data)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/base.py", line 170, in render
return self._render(context)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/urls/base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments
'{'uidb64': 'NTA', 'token': 'aa5a2v-c248dcaea908540be1e8e3d5feff970f1'}' not found. 1
pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-
Za-z]{1,20})/']
serverlogs
2020-09-13 15:37:43 {'user': <User: user#usermail.de>, 'domain': 'www.mywebsite.de',
'uid': 'NTA', 'token': 'aa5a2v-c248dcaea908540be1e8e3d5feff970f1'}
2020-09-13 15:37:43 Internal Server Error: /signup1/#012Traceback (most recent call l
ast):#012 File "/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/core/handlers/exception.py", line 47, in inner#012 response =
get_response(request)#012 File
"/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/core/handlers/base.py", line 179, in _get_response#012 response =
wrapped_callback(request, *callback_args, **callback_kwargs)#012 File
"/home/username/werkvertragrepo/werkvertrag/views.py", line 612, in signup1#012 text_body
= render_to_string('acc_active_email.txt', merge_data)#012 File
"/home/username/.virtualenvs/myenv/lib/python3.6/site-packages/django/template/loader.py",
line 62, in render_to_string#012 return template.render(context, request)#012 File
"/home/username/.virtualenvs/myenv/lib/python3.6/site-
packages/django/template/backends/django.py", line 61, in render#012 return self.template
if found out the error come in views with this line:
text_body = render_to_string('acc_active_email.txt', merge_data)
on my localhost it works without problems
views.py
def signup1(request):
if request.method == 'POST':
form = werkforms.UserCreationform(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
Firmennamen = form.cleaned_data.get('Firmennamen')
Street = form.cleaned_data.get('Street')
plzort = form.cleaned_data.get('plzort')
user = User.objects.create_user(username, email, raw_password)
user.is_active = False
user.save()
userid = user.id
UserID = User.objects.get(id=userid)
current_site = get_current_site(request)
print("hallo")
merge_data = {
'user': user,
'domain': current_site.domain,
'uid': force_text(urlsafe_base64_encode(force_bytes(user.pk))),
'token': account_activation_token.make_token(user),
}
print(merge_data)
text_body = render_to_string('acc_active_email.txt', merge_data)
--- some more code ---
test = "das ist response"
return HttpResponse(test, content_type="text/html")
acc_active_email.txt
Hallo {{ user }},
Willkomen beim Onlineforum,
Deine Registrierung war erfolgreich. Klicke nun auf den unteren Link um deine Registrierung abzuschließen.
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
Vielen Dank
Mit freundlichen Grüßen
in the urls you have to set
path('activate/<slug:uidb64>/<slug:token>/',
activate, name='activate'),
and don't forget to import in the urls from views activate
from myapp.views import (
activate
)
You should use context args in activation function as well:
context = {'uidb64': uidb64, 'token': token}
return render(request, 'users/thank_confirm.html', context)
Some people recommend to use decode() func in uid key, but I think it should be just:
'uid': urlsafe_base64_encode(force_bytes(user.pk))
And the main problem is in the urls of your app (that including activation view). You should use slug:
path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate')
and don't forget to import path if you are using only urls
from django.urls import path
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>
I have a project folder mysite and my app folder passwordValidate. When I move the path of user_login to passwordValidate/urls.py, the login works but same is not working from mysite/urls.py.
The error message is Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name.
mysite/urls.py
from passwordValidate import views
urlpatterns = [
path('',views.home,name='home'),
path('passwordValidate/',include('passwordValidate.urls')),
path('user_login',views.user_login,name='user_login'),
]
passwordValidate/views.py
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('home'))
else:
return render(request,'passwordValidate/login.html')
passwordValidate/templates/passwordValidate/base.html
<li class="nav-item">
<a class="nav-link" href="{% url 'user_login' %}">Log In</a>
</li>
console
[16/Jan/2019 10:00:39] "GET / HTTP/1.1" 200 2555
Not Found: /media/profile_pics/IMG_20181030_161728.jpg
[16/Jan/2019 10:00:39] "GET /media/profile_pics/IMG_20181030_161728.jpg HTTP/1.1" 404 2670
Not Found: /favicon.ico
[16/Jan/2019 10:00:44] "GET /favicon.ico HTTP/1.1" 404 2577
Internal Server Error: /user_login
Traceback (most recent call last):
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Anshul\Desktop\django_lectures\Learning Jango\Django\NEW\PASSWORD VALIDATION\mysite\passwordValidate\views.py", line 74, in user_login
return render(request,'passwordValidate/login.html')
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 937, in render
bit = node.render_annotated(context)
File "C:\Users\Anshul\Anaconda3\lib\site-packages\django\template\base.py", line 904, in render_annotated
return self.render(context)
File "C:\Users\Anshul\Anaconda3\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\Anshul\Anaconda3\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\Anshul\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 622, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name.
[16/Jan/2019 10:00:47] "GET /user_login HTTP/1.1" 500 148137
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.
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.