Django URL Routing Issue - python

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

Related

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

VisualStudio django.conf.urls

This is my first question ever. I am working in VisualStudio to create a django/python application for smartshopping AI. This is also my first python/django technology application. I have trouble with the urls.py and have read that django versions do not include urlpatterns. I've changed my url patterns to reflect the advice online and have changed my django.conf.urls import url section of my code. It is still not working. Please help.
I've followed the advices online to get here:
from datetime import datetime
from django.conf.urls import url
from app.forms import BootstrapAuthenticationForm
# Uncomment the next lines to enable the admin:
from django.conf.urls import include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
url(r'^$', 'app.views.home', name='home'),
url(r'^contact$', 'app.views.contact', name='contact'),
url(r'^about', 'app.views.about', name='about'),
url(r'^login/$',
'django.contrib.auth.views.login',
{
'template_name': 'app/login.html',
'authentication_form': BootstrapAuthenticationForm,
'extra_context':
{
'title':'Log in',
'year':datetime.now().year,
}
},
name='login'),
url(r'^logout$',
'django.contrib.auth.views.logout',
{
'next_page': '/',
},
name='logout'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
]
I want an easy fix not to change all the views to add include - these were autogenerated by visual studio. I want to keep autogeneraton working and just add a line of code to reference the url.py
from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/index.html',
context_instance = RequestContext(request,
{
'title':'Home Page',
'year':datetime.now().year,
})
)
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
context_instance = RequestContext(request,
{
'title':'Contact',
'message':'Your contact page.',
'year':datetime.now().year,
})
)
def about(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
context_instance = RequestContext(request,
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
})
)
Based on the responses and the stack overflow answer to a similar question (Django URLs error: view must be a callable or a list/tuple in the case of include()) I have tried this approach (which still does not work).
from datetime import datetime
from django.conf.urls import url
from app.forms import BootstrapAuthenticationForm
from django.contrib.auth import views as auth_views
from SmartShopper import views as SmartShopper_views
# Uncomment the next lines to enable the admin:
# from django.conf.urls import include
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
# Examples:
url(r'^$', SmartShopper_views.home, name='home'),
url(r'^contact$', SmartShopper_views.contact, name='contact'),
url(r'^about', SmartShopper_views.about, name='about'),
url(r'^login/$',
'django.contrib.auth.views.login',
{
'template_name': 'app/login.html',
'authentication_form': BootstrapAuthenticationForm,
'extra_context':
{
'title':'Log in',
'year':datetime.now().year,
}
},
name='login'),
url(r'^logout$',
'django.contrib.auth.views.logout',
{
'next_page': '/',
},
name='logout'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
[what my solution contains - I'm coming from an asp.net MVC background and django is a bit different with its MVC type structure still getting used to it, just help me make thisthing run! HELPPP please. thanks 1
You don't need to change your views. The problem is still in your urls.py. Instead of referring to eg "app.views.home" as a string, you need to import the view and refer to views.home directly.
After learning more about the Django framework from this youtube tutorial I was able to fix my code (https://www.youtube.com/watch?v=nAn1KpPlN2w&index=3&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK#t=4.759461)
What I learned was that each "app" is a segment of the program with associated views. All I had to do was import all the views from my_app or app or whatever else you are calling your new "app" in Django. Besides the slight change to the urlpatterns from () to [] all I did was modify the url call to pull from the app_views I set up above. Here is functional code. I have a "Server error (500)" which is something else I'll figure out but yea please explain things more for devs who are simply new to the django framework. Visualstudio is a good tool. use it for python. Reach out if you have any questions I'd be happy to help the newbie. Here is my functional code.
from datetime import datetime
from django.conf.urls import url
from app.forms import BootstrapAuthenticationForm
from django.contrib.auth import views as auth_views
from app import views as app_views
# Uncomment the next lines to enable the admin:
# from django.conf.urls import include
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
# Examples:
url(r'^$', app_views.home, name='home'),
url(r'^contact$', app_views.contact, name='contact'),
url(r'^about', app_views.about, name='about'),
url(r'^login/$',
auth_views.login,
{
'template_name': 'app/login.html',
'authentication_form': BootstrapAuthenticationForm,
'extra_context':
{
'title':'Log in',
'year':datetime.now().year,
}
},
name='login'),
url(r'^logout$',
auth_views.logout,
{
'next_page': '/',
},
name='logout'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
]

What can go wrong with admin url?

I am new in Python, I have a problem with the admin URL.
When I type
localhost:8000/admin/
My browser tells me:
DoesNotExist at /admin/
Question matching query does not exist
My index page and detail pages work fine.
I thought it was a mistake in the order of URL's,
I changed the order of the admin and detail URL,
but still nothing.
Can somebody please give me a hint.
project/urls.py
from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
urlpatterns = [
url(r'^$', 'books.views.index', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<book_title>[\w_-]+)/$', 'books.views.detail', name='detail'),
]
urlpatterns += staticfiles_urlpatterns()
books/views.py
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.all
context = {'latest_question_list': latest_question_list}
return render(request, 'books/index.html', context)
def detail(request, book_title):
question = Question.objects.get(title=book_title)
return render(request, 'books/detail.html', {'question': question})
I forgot to put parentheses for Question.objects.all So silly of me.
add this before urlpatterns in urls.py
admin.autodiscover()

Django views and URl's

I'm having a problem with the way my URL's look in Django. I have a view like this:
def updatetext(request, fb_id):
Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])
fb = get_object_or_404(Account, pk=fb_id)
return render(request, 'myapp/account.html', {
'success_message': "Success: Settings updated.",
'user': fb
})
When a user clicks on the URL to update the text they are then redirected to the account page but the URL then looks like 'account/updatetext/'. I would like it just be 'account/'.
How would I do this in Django. What would I use in place of render that would still allow me to pass request, 'success_message' and 'user' into the returned page but to not contain the 'updatetext' within the URL?
[edit]
The urls.py file looks like this:
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^home/$', views.index, name='index'),
url(r'^(?P<fb_id>\d+)/$', views.account, name='account'),
url(r'^(?P<fb_id>\d+)/updatetext/$', views.updatetext, name='updatetext'),
url(r'^(?P<fb_id>\d+)/updatepages/$', views.updatepages, name='updatepages'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^admin/$', views.useradmin, name='admin'),
)
You need to actually redirect the user to '/account/'. Rather than returning a call to render you can do the following:
from django.http import HttpResponseRedirect
def updatetext(request, fb_id):
Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])
fb = get_object_or_404(Account, pk=fb_id)
return HttpResponseRedirect(reverse('account', kwargs={"fb_id": fb_id}))
However, it would be better to pass in a call to reverse into the HttpResponseRedirect constructor, but since I don't know your urls.py I just wrote the relative url.

Categories