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)),
]
Related
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')
]
Okay... let's try to explain things clearly. I've used Python Django to create a dynamic webpage/web-app. After completing the website I have published it using DigitalOcean and have successfully attached my purchased domain name to the name server of DigitalOcean. When I access my website, ordinanceservices.com, i get an error 404; however, if I type ordinanceservices.com/home it works as it should and displays the home page. How, by editing the python files, can I have it to where ordinanceservices.com will display the home page as opposed to error 404? I feel like there's something that I am doing that is fundamentally wrong regarding my .urls structure and thus a rewrite/redirect in the nginx config should not be necessary.
Here is the specific error:
Page not found (404)
Request Method: GET
Request URL: http://ordinanceservices.com/
Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order:
^admin/
^ ^home/ [name='home']
^ ^contact/ [name='contact']
^ ^services/ [name='services']
The current URL, , didn't match any of these.
I somewhat understand what is happening here though I do not know how to fix this. Next I will provide my .urls files for each folder that contains such:
/django_project 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('company.urls')),
)
/company urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^home/', views.home, name='home'),
url(r'^contact/', views.contact, name='contact'),
url(r'^services/', views.services, name='services'),
]
/company views.py
from django.shortcuts import render
def home(request):
return render(request, 'company/home.html')
def contact(request):
return render(request, 'company/contact.html')
def services(request):
return render(request, 'company/services.html')
What I am aiming to do, without needing to redirect the main URL using the nginx config files to do so, is to edit my urls and views structure of my Python files to ensure that the normal URL, ordinanceservices.com, will actually display a page; preferably the home page of my webpage.
I have a hunch that it has to do with the fact that I do not have a views.index for the r'^admin/' to reach to. I am not certain but I have been trying to figure this out for hours. Does anyone have a clue what I can do to fix this?
You haven't defined anything at the root url. Add one more line to your company urls.py so it becomes
//company urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^home/', views.home, name='home'),
url(r'^contact/', views.contact, name='contact'),
url(r'^services/', views.services, name='services'),
]
First of all, check if you have added www.yourdomain.com or yourdomain.com to ALLOWED_HOST = ['www.yourdomain.com','yourdomain.com'] in your settings.py
and then in your company/urls.py do this
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^services/$', views.services, name='services'),
]
and in your main urls.py add this code
from django.conf.urls import url,include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('company.urls')),
]
I am having trouble with my urls. I have one app called users that has two models, Salon and Stylist. The url /stylists and /salons is rendering the same view (stylist_results) however /salons should render salon_results and I cannot figure out why. I think there may be something wrong with the way I am using namespaces.
users/urls.py
from django.conf.urls import url
#import views from the current directory
from . import views
urlpatterns=[
url(r'^$', views.stylist_results, name='stylist_results'),
url(r'^(?P<pk>\d+)$', views.stylist_detail, name='stylist_detail'),
url(r'^$', views.salon_results, name='salon_results'),
url(r'^(?P<pk>\d+)$', views.salon_detail, name='salon_detail'),
]
users/views.py
from django.shortcuts import get_object_or_404, render
from .models import Salon, Stylist
# Create your views here.
def salon_results(request):
salons = Salon.objects.all()
return render(request, 'salons/salon_results.html', {'salons': salons})
def salon_detail(request, pk):
salon = get_object_or_404(Salon, pk=pk)
return render(request, 'salons/salon_detail.html', {'salon': salon})
def stylist_results(request):
stylists = Stylist.objects.all()
return render(request, 'stylists/stylist_results.html', {'stylists': stylists})
def stylist_detail(request, pk):
stylist = get_object_or_404(Stylist, pk=pk)
return render(request, 'stylists/stylist_detail.html', {'stylist': stylist})
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^salons/', include('users.urls', namespace='salons')),
url(r'^stylists/', include('users.urls', namespace='stylists')),
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
]
urlpatterns += staticfiles_urlpatterns()
views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
Split your stylist and salon views into two separate modules. You might consider creating two different apps, but you don't have to.
users/stylist_urls.py
urlpatterns = [
url(r'^$', views.stylist_results, name='stylist_results'),
url(r'^(?P<pk>\d+)$', views.stylist_detail, name='stylist_detail'),
]
users/salon_urls.py
urlpatterns = [
url(r'^$', views.salon_results, name='salon_results'),
url(r'^(?P<pk>\d+)$', views.salon_detail, name='salon_detail'),
]
Then update your project's urls.py with the new modules:
urlpatterns = [
url(r'^salons/', include('users.salon_urls', namespace='salons')),
url(r'^stylists/', include('users.stylist_urls', namespace='stylists')),
...
]
At the moment, the regexes for your salon URLs are exactly the same as the stylist URLs, so the salon URLs will always match first.
You are specifying same set of url's(users.urls) for salons and stylists here:
url(r'^salons/', include('users.urls', namespace='salons')),
url(r'^stylists/', include('users.urls', namespace='stylists')),
What did you expect to happen
You are including same users/urls.py in urls.py
It does following:
find me /stylist/ => go into included urls
find first occurance of url(r'^$', views.stylist_results, name='stylist_results'),
renders that view
same thing happens with /salons/
URL Dispatcher documentation
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')
I am following this guide here tango with django and I am reading/copying as best from here tutorial part 3
But I cannot get different views to display different content. I am missing the explanation somewhere/somehow.
so this is my project urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Sayth.views.home', name='home'),
# url(r'^Sayth/', include('Sayth.foo.urls')),
# 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)),
url(r'^rango/', include('rango.urls')),
url(r'^rango/about/', include('rango.urls')),
)
This is my application urls.py
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.about, name='about'),
)
These are my views
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Rango says Hello World! <a href='/rango/about'>About</a>" )
def about(request):
return HttpResponse("This is the about page. <a href='/rango/'>Index</a>")
Both my pages resolve but both show the index page, why?
The urls defined are not correct. The root urls.py should have only a pointer to the app, and the app's urls.py should resolve the different endpoints.
Try the following urls.py:
#Project urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Sayth.views.home', name='home'),
# url(r'^Sayth/', include('Sayth.foo.urls')),
# 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)),
url(r'^rango/', include('rango.urls')),
)
#rango/urls.py
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
)
As the first answer have mentioned, your project's urls.py only needs one pointer to the application urls.py.
Conceptually it is like this, anything matching '^rango/' should be passed onto the application urls.py, and then the applications handles the rest of the url.. either '/' or 'about/'
So in your applications urls.py, you then need to ensure that a mapping for each of these patterns exists.
In the tangowithdjango book, the about page is an exercise, left for the reader, but if you have future problems you can always inspect the code for the application, for example:
The project urls.py:
https://github.com/leifos/tango_with_django/blob/master/tango_with_django_project/tango_with_django_project/urls.py
The application urls.py:
https://github.com/leifos/tango_with_django/blob/master/tango_with_django_project/rango/urls.py
If you do not wish to create an urls.py on the app you can just do the url mapping like this:
urlpatterns = patterns('',
# ...
# most detailed urls comes first.
url(r'^rango/about/?$', 'rango.views.about', name='about'),
url(r'^rango/?$', 'rango.views.index', name='index'),
)