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
Related
ok polls tutorial is done and can enter questions, vote, etc. but from the admin pages View site aka localhost:8000 gives...
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
dose/
admin/
The empty path didn’t match any of these.
Now I have polls/views.py...
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""
Return the last five published questions (not including those set to be
published in the future).
"""
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
and mysite/urls.py set to ...
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
and polls/urls.py set to...
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
The only hint I can find is that all the imports show error highlights in VSCode with the Error "reportMissingModuleSources"
But python and django run perfectly well everywhere but index.html
No url at http://localhost:8000/ address is expected behaviour, where you want to go is http://localhost:8000/polls/.
If you want go directly to the desired View without writing polls/ prefix you should define your urls this way:
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
So you place path() call without url prefix. Generally if you include any url group you define the beginning of address this way.
I was trying to call one html file from another via Django.
I actually have no errors inside my project(It works). But when I am trying to call the second html file the page refreshes only. Here is my code, thanks:D. My projects name is information and the name of my app is basic.
basic.views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'basic/index.html')
def customer(request):
return render(request,'basic/customer.html')
basic.urls.py:
from django.urls import path
from basic import views
app_name='basic'
urlpatterns=[
path('',views.index,name='index'),
path('',views.customer,name='customer'),
]
information.urls.py:
from django.contrib import admin
from django.urls import path,include
from basic import views
urlpatterns = [
path('',views.index,name="index"),
path('admin/', admin.site.urls),
path('',include('basic.urls'))
]
The problem is that you have two paths that match exactly the same path. So that means each time you make a request with an empty path, the first one is used.
You should make use of non-overlapping paths, for example:
# basic/urls.py
from django.urls import path
from basic import views
app_name='basic'
urlpatterns=[
path('', views.index, name='index'),
path('customer/', views.customer, name='customer'),
]
and in your information/urls.py:
# information/urls.py
from django.contrib import admin
from django.urls import path,include
from basic import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
path('basic/', include('basic.urls'))
]
register.html is not accessible on 'register/' url
tried changing url to '' and webpage is accessible but not on 'register/'
projects urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('login/',include('login.urls')),
path('admin/', admin.site.urls),
]
apps urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.indexView, name = "home"),
path('dashboard/', views.dashboardView, name="dashboard"),
#path('login/',),
path('register/',views.registerView, name="register_url"),
#path('logout/',),
]
views.py
from django.shortcuts import render
def indexView(request):
return render(request,'index.html')
def dashboardView(request):
return render(request,'dashboard.html')
def registerView(request):
return render(request,'register.html')
templates/register.html
Either you type login/ before evry URL pattern of apps urls.py file while testing URL.
or
You should include url mapping of apps urls.py in main urls.py
This might help you.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('apps.urls')), #put you app name here
path('admin/', admin.site.urls),
]
apps urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.indexView, name = "home"),
path('dashboard/', views.dashboardView, name="dashboard"),
path('register/',views.registerView, name="register_url"),
]
This will work and you can add login/ url mapping inside the apps urls.py.
This type of flow will make it easy to understand .
Use url_name for URL calling:
{% url 'register_url' %}
This will directly search for 'register_url' in the project and will return the path.
url_name must be unique so make sure your url_name is uniquely defined.
I'm just finding my way around python/django. I'm in the middle of trouble shooting another issue with assistance and in the process of trying various things am now seeing this error in my console:
__import__(name)
File "/Users/vaijoshi/PycharmProjects/adec/src/project/urls.py", line 12, in <module>
url(r'^termsandconditions/$', terms_and_conditions, name='terms_and_conditions'),
NameError: name 'terms_and_conditions' is not defined
I'm a little confused as this information is defined in my views.py (at least that's what I think I'm doing)
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
from src.adec.forms import UserForm
def home(request):
return render(request, "home.html")
def register_professional(request):
return render(request, "registerprofessional.html")
def register_user(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UserForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = UserForm()
return render(request, 'registeruser.html', {'form': form})
def terms_and_conditions(request):
return render(request, "termsandconditions.html")
def how_it_works(request):
return render(request, "howitworks.html")
def search_results(request):
return render(request, "searchresults.html")
def profile(request):
return render(request, "profile.html")
URL.py in the project folder (note I was advised to move the above views.py from the projects folder to the src folder for the other issue I'm troubleshooting. Do they need to be in the same folder?)
import...
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/docs/', include('django.contrib.admindocs.urls')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^termsandconditions/$', terms_and_conditions, name='terms_and_conditions'),
url(r'^how-it-works/$', how_it_works, name='how_it_works'),
url(r'^$', home, name='home'),
url(r'^registerprofessional/$', register_professional, name='register_professional'),
url(r'^registeruser/$', register_user, name='register_user'),
url(r'^searchresults/$', search_results, name='search_results'),
url(r'^profile/$', profile, name='profile'),
]
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My tree structure atm:
Kindly assist
Update based on comments below:
I have now done:
from adec.views import terms_and_conditions
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/docs/', include('django.contrib.admindocs.urls')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^termsandconditions/$', terms_and_conditions, name='terms_and_conditions'),
url(r'^how-it-works/$', how_it_works, name='how_it_works'),
url(r'^$', home, name='home'),
url(r'^registerprofessional/$', register_professional, name='register_professional'),
url(r'^registeruser/$', register_user, name='register_user'),
url(r'^searchresults/$', search_results, name='search_results'),
url(r'^profile/$', profile, name='profile'),
]
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is reverting me back to the original error I was facing:
__import__(name)
File "/Users/vaijoshi/PycharmProjects/adec/src/project/urls.py", line 1, in <module>
from adec.views import terms_and_conditions
File "/Users/vaijoshi/PycharmProjects/adec/src/adec/views.py", line 5, in <module>
from src.adec.forms import UserForm
ImportError: No module named src.adec.forms
Make sure that the name is imported in the urls.py:
from adec.views import terms_and_conditions
Alternatively, use string instead:
url(r'^termsandconditions/$', 'adec.views.terms_and_conditions',
name='terms_and_conditions'),
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()