Django View Error - NoReverseMatch - python

I am new to django and I am trying to solve a NoReverseMatch issue. I think it has something to do with the views but i'm new to this.
The code is from a popular boiler plate repo from a few years ago. PLEASE NOTE: I tried reading like every answer on stack overflow already and have been stuck for hours.
Any help would be greatly appreciated
main urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^login/', include('shopify_app.urls')),
url(r'^', include('home.urls'), name='root_path'),
url(r'^admin/', admin.site.urls),
]
urls.py inside of app
from django.conf.urls import url
from shopify_app import views
urlpatterns = [
url(r'^$', views.login, name='shopify_app_login'),
url(r'^authenticate/$', views.authenticate, name='shopify_app_authenticate'),
url(r'^finalize/$', views.finalize, name='shopify_app_finalize'),
url(r'^logout/$', views.logout, name='shopify_app_logout'),
]
views.py inside of app
from django.shortcuts import redirect, render
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.conf import settings
import shopify
def authenticate(request):
shop = request.GET.get('shop')
print('shop:', shop)
if shop:
scope = settings.SHOPIFY_API_SCOPE
redirect_uri = request.build_absolute_uri(reverse('shopify_app.views.finalize'))
permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri)
return redirect(permission_url)
return redirect(_return_address(request))
def finalize(request):
shop_url = request.GET['shop']
try:
shopify_session = shopify.Session(shop_url)
request.session['shopify'] = {
"shop_url": shop_url,
"access_token": shopify_session.request_token(request.REQUEST)
}
except Exception:
messages.error(request, "Could not log in to Shopify store.")
return redirect(reverse('shopify_app.views.login'))
messages.info(request, "Logged in to shopify store.")
response = redirect(_return_address(request))
request.session.pop('return_to', None)
return response
Error
NoReverseMatch at /login/authenticate/
Reverse for 'shopify_app.views.finalize' not found. 'shopify_app.views.finalize' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://localhost:8000/login/authenticate/?csrfmiddlewaretoken=zEwwHeTfxK7apbAp3dSxsehsafxqjSgEM4t&shop=piepiedev.myshopify.com&commit=Install
Django Version: 1.11.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'shopify_app.views.finalize' not found. 'shopify_app.views.finalize' is not a valid view function or pattern name.
Source code / file structure-
https://github.com/Shopify/shopify_django_app
Similar issue but not working solution-
https://github.com/Shopify/shopify_django_app/issues/13

Change inside authenticate(request):
redirect_uri = request.build_absolute_uri(reverse('shopify_app:shopify_app_finalize'))

Related

How to avoid Page 404 Error on my first app

I am following this tutorial.
https://www.youtube.com/watch?v=a48xeeo5Vnk
Here is my code for views:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse('<h1>This is our blog</h1>')
def about(request):
return HttpResponse('<h1>This is our About Page</h1>')
def next(request):
return HttpResponse('<h1>This is our next Page</h1>')
This is my App urls page code
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='blog-home'),
path('about/', views.about, name='blog-about'),
path('next/', views.next, name='blog-NEXT'),
]
This is my main project URL code
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('firstapp', include('firstapp.urls')),
path('admin/', admin.site.urls),
]
Now when I try this with only single view i.e default page '', it works alone, with no more pages mentioned in code, however when I add more views it gives me a 404 page error. I believe the code is fine and it shoud work, but somehow it chose not to.
Tried different browser, tried forums but nothing.
Here is the error.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/firstapp/
Using the URLconf defined in first.urls, Django tried these URL patterns, in this order:
firstapp [name='blog-home']
firstapp about/ [name='blog-about']
firstapp next/ [name='blog-NEXT']
admin/
The current path, firstapp/, didn't match any of these.
Any assistance would be appreciated.
Do below changes
from:
path('firstapp', include('firstapp.urls')),
to:
path('firstapp/', include('firstapp.urls')),

I am getting a 404 error when using login_required

I'm new to Django and I'm trying to make a learning log website.
When I try to restrict my topics with login_required function I get a 404 error.
Here is my code:
from django.contrib.auth.decorators import login_required
#login_required(login_url='/users/login/')
def topics(request):
""" Show all topics."""
topics = Topic.objects.order_by("date_added")
context = {"topics": topics}
return render(request, "learning_logs/topics.html", context)
I get this error whenever I use the decorator in my code:
Using the URLconf defined in learning_log.urls, Django tried these URL
patterns, in this order:
admin/
users/ login [name='login']
users/ logout [name='logout']
users/ registration [name='register']
learning_logs/ยจ
The current path, users/login/, didn't match any of these.
The url works fine but when I use the decorator it breaks.
that means you have not defined the django builtin login in your url to solve it you can just past that inside you urls.py
##urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('users/login/', auth_views.login, name='login'),
path('users/logout/', auth_views.logout, name='logout'),
path('admin/', admin.site.urls),
]
if you have already done that you need to do the following in views
##views.py
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
#login_required(login_url=reverse_lazy("login"))
def topics(request):
""" Show all topics."""
topics = Topic.objects.order_by("date_added")
context = {"topics": topics}
return render(request, "learning_logs/topics.html", context)
It looks like your users urls don't have trailing slashes. Make sure that the URLS in your users/urls.py end with slashes. For example:
urlpatterns = [
url(r'^login/$', LoginView.as_view(), name='login')
]

Page not found (404) - Django urls and views

I'm trying to make a web server with Django for making "parrot bot".
I'm using
python3.5
Django
apache2.4
The error I'm getting :
Page not found (404)
Request Method: GET
Request URL: http://54.95.30.145/
Using the URLconf defined in bot.urls, Django tried these URL patterns, in this order:
^keyboard/
^message
The empty path didn't match any of these.
This is my project bot/urls.py code.
from django.conf.urls import url, include
urlpatterns = [
url(r'',include('inform.urls')),
]
This is my app inform/urls.py code.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^keyboard/',views.keyboard),
url(r'^message',views.message),
]
This is my inform/views.py code.
from django.http import JsonResponse
def keyboard(request):
return JsonResponse({
'type' : 'text',
})
def message(request):
message = ((request.body).decode('utf-8'))
return_json_str = json.loads(message)
return_str = return_json_str['contetn']
return JsonResponse({
'message': {
'text' : return_str
}
})
Please help me.
It error is nothing but you didn't define any url patterns for your root address (http://54.95.30.145/).
To solve this, add a url pattern for home/root address as below in project bot/urls.py
from django.conf.urls import url, include
def root_view(request):
return JsonResponse({"message": "This is root"})
urlpatterns = [
url(r'^$', root_view),
url(r'', include('inform.urls')),
]

django - 'function' object has no attribute 'resolve'

I am trying to learn about class based views and django in general. The project is notes_project and in it I have created an app notes. Below is the urls.py for both of these and views.py for notes app:
notes_project/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import notes
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'notes_project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^notes/', include('notes.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
)
notes/urls.py
from django.conf.urls import include, patterns, url
from .views import IndexView
urlpatterns = patterns(r'^$/', IndexView.as_view())
notes/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
class IndexView(View):
def get(request):
return HttpResponse("Welcome to notes index")
However, whenever I access the URL http://127.0.0.1:8000/notes/, I keep getting below error:
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/
Django Version: 1.7.4
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'resolve'
Exception Location: /path/notes/venv/lib/python3.4/site-packages/django/core/urlresolvers.py in resolve, line 345
Python Executable: /path/notes/venv/bin/python
Python Version: 3.4.2
Python Path:
['/path/notes/notes_project',
'/path/notes/venv/lib/python3.4',
'/path/notes/venv/lib/python3.4/plat-x86_64-linux-gnu',
'/path/notes/venv/lib/python3.4/lib-dynload',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/path/notes/venv/lib/python3.4/site-packages']
The first argument to patterns is a string that acts as prefix to the rest of the patterns. Also each pattern needs to be a tuple of its own. You've done that correctly in the main urls.py but missed it in the notes one. It should be:
urlpatterns = patterns('',
(r'^$', IndexView.as_view()),
)

Django URL Routing Issue

Very new to Django, so I apologize as I'm sure this has an easy answer.
I have a PHP background, and so I guessing that I am trying to force a structure I am used to, and not one that is native in Django.
Here is my Project's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('pm.urls', namespace='pm')),
)
Here is my App's urls.py
from django.conf.urls import patterns, url
from pm import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^label/add/$', views.add_label, name='label_add'),
)
I am doing an AJAX Post request to /label/add/, but it's coming back with a 500 error.
This is the views.py:
from django.shortcuts import render
from pm.models import Label
import json
# Create your views here.
def index(request):
labels_list = Label.objects.order_by('name')
return render(request, 'pm/index.html', {
'labels' : labels_list
})
""" Labels """
def add_label(request):
if request.is_ajax():
response = {
'success': True
}
else:
response = {
'success': False,
'error': "Invalid request"
}
return json.dumps(response)
Any advise or references would be great.
UPDATE
Here's the first couple of lines from the traceback I am getting:
AttributeError at /label/add/
'str' object has no attribute 'get'
you have to return HttpResponse instead of string:
return HttpReponse(json.dumps(response), content_type='application/json')

Categories