Page not found (404) - Django urls and views - python

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')),
]

Related

Django - method not allowed error after moving ajax request to different app

I have a small form in my django app called home that I submit through jquery ajax request. Below is the setup that I have
home urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^submitseries/$', views.submitseries, name='submitseries'),
url(r'^getstats/$', views.getstats, name='getstats'),
]
home views.py
def submitseries(request,id=None):
if request.method == "POST":
series_url = request.POST.get("series_url")
# rest of the processing code that is working fine
application urls.py
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('', include(('home.urls','home'),namespace="home")),
path('series/', include(('series.urls','series'),namespace="series")),
path('submitseries/', include(('home.urls','submitseries'),namespace="submitseries")),
path('players/', include(('players.urls','players'),namespace="players")),
path('admin/', admin.site.urls),
]
This setup is working fine but I would like to move this ajax request to a different app in my application that is with name series
So I have moved the submitseries function to views.py of series app modified the
series urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^$submitseries/', views.submitseries, name='submitseries'),
]
((tried different variations such as series/submitseries/ ))
modified the application urls.py as following
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('', include(('home.urls','home'),namespace="home")),
path('series/', include(('series.urls','series'),namespace="series")),
path('submitseries/', include(('series.urls','submitseries'),namespace="submitseries")),
path('players/', include(('players.urls','players'),namespace="players")),
path('admin/', admin.site.urls),
]
rather than pointing it to home.urls I have pointed it to series.url
But it starts giving 405 Method not allowed error and it doesn't matter what I try I am not able to solve it.
I have tried giving different variations of path in urls.py of both application and series app. I am just not able to make it work.
The only different in both the setup is that home app is base and the relative path is "http://localhost:8000/submitseries"
but when I move it to series app the base url becomes
"http://localhost:8000/series/submitseries"
Adding AJAX code as requested
//function to submit series url and save to DB
$("#save_series").click(function(e){
e.preventDefault();
series_url = $("#series_url").val();
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
console.log("Series URL " + series_url);
$.ajax({
type: "POST",
url: "series/submitseries/",
data: {"series_url":series_url},
headers:{
"X-CSRFToken": csrftoken
},
success: function(result){
message = "Series #" + result["series_id"] + " inserted successfully";
bootstrap_alert['info'](message);
},
error: function(result){
bootstrap_alert['warning'](result.responseJSON.error_msg);
}
});//end of ajax submit
});//end of button click block
I was able to fix the issue thanks to the users pointing out different things in comments.
The first clue was suggestion by #amadou sow to use url substituting in JS using following expression
{% url 'submitseries:submitseries' %}
When I did this in the action attribute of the form then I started getting following error
"Reverse for 'submitseries' with no arguments not found. 1 pattern(s)
tried: ['series/submitseries/$submitseries/']
This made it clear that there is something wrong with endpoint I have provided in the series urls.py
After playing with some permutations and combinations what I found is that $ is being evaluated literally rather than a regex symbol in case of subdirectory case and #BrianD comment about the $ being in right place hit the nail in the head.
Finally changing the series urls.py to following got the whole thing working
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^submitseries/', views.submitseries, name='submitseries'),
]
P.S. submitseries is without $ in front.

I have problem Page not found (404) Django

import jobs.views
urlpatterns = [
path('admin/', admin.site.urls),
path('nick', jobs.views.nick, name='nick'),
]
enter code here
def nick(request):
return render(request, 'jobs/nick.html')
I got:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/nick/
Using the URLconf defined in FadhelPro.urls, Django tried these URL patterns, in this order:
admin/
nick/ [name='nick']
The empty path didn't match any of these.
Instead of:
path('nick', jobs.views.nick, name='nick')
Try:
path(r'^nick/', jobs.views.nick, name='nick'),
If python -V is 3.x or above then:
urlpatterns = [
path('admin/', admin.site.urls),
path('nick/', jobs.views.nick, name='nick'),
]
def nick(request):
return render(request, 'jobs/nick.html')
If python -V is 2.x or above then:
urlpatterns = [
path(r'^admin/', admin.site.urls),
path(r'^nick/', jobs.views.nick, name='nick'),
]
def nick(request):
return render(request, 'jobs/nick.html')
Html templates could not be rendered without an app but you can write the code of the html in a http response!
If you create an app instead that will be more hacky and good.If this doesn't work then you go for an app and Get some tutorials of django before you mess up!!

Page not found in Django (404)

I have a little problem with Django 2.0. In my case the debugger responded with this message:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in bajkowo.urls, Django tried the following URL patterns, in this order:
admin/
bajki/
But that resulted in an error:
The empty path didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I have checked the views and URLs, but I could not find a bug or a typo. Could anyone check my code?
urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('bajki/', include('bajki.urls')),
]
bajki/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('bajki/',views.lista_bajek, name='lista_bajek'),
]
bajki/views.py:
from django.shortcuts import render
def lista_bajek(request):
return render(request, 'bajki/lista_bajek.html', {})
The def lista_bajek should respond with a blank website, but returns a 404 error code. Of course, I did create the bajki/templates/bajki/lista_bajek.html file.

Django View Error - NoReverseMatch

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'))

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