I'm new to django and I've been trying to test the URLs redirection methods I've tried two options but the return render() keeps giving me this error of no reverse match
this is my urls.py code :
app_name = 'blog'
urlpatterns = [
# path('about', views.about, name = 'about'),
path('about.html', views.about, name='about'),
path('home.html', views.home, name='home'),
# path('home', views.home, name ="home")
path('redirect', views.redirect_view),
path('redirection_fct',views.redirection_fct, name='redir_fct'),
#redirection par la fonction as_view
path('redirect1', RedirectView.as_view(url='http://127.0.0.1:8000/blog/redirection_fct')),
path('redirect2', views.redirect_view1),
]
and this is my views file :
def about(request):
return render(request, 'about.html', {})
def home(request):
return render(request, 'home.html', {})
#redirection par HttpResponseRedirect
def redirect_view(request):
return HttpResponseRedirect("redirection_fct")
def redirect_view1(request):
return redirect('redir_fct')
def redirection_fct(request):
return render(request, 'redirection.html', {})
Is there something wrong with my URLs pattern or it is the render one?
Is this the urls.py on your app? How do you include it on your project urls.py, if you have a namespace for it, then you probably need something like:
def redirect_view1(request):
return redirect('blog:redir_fct')
You can try running from a django shell:
from django.urls import get_resolver
print(get_resolver().reverse_dict.keys())
Related
I have this structure of urls:
page/section/subsection/article, where section, subsection and article are user-generated slug names.
How can I write the urlpatterns?
I do this, but may be exist better method?
urlpatterns = [
url(r'^$', views.index),
url(r'^(?P<slug>[-\w]+)/$', views.section),
url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/$', views.subsection),
url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/(?P<articleslug>[-\w]+)/$', views.article)
]
My views:
def index(request):
return render(request, 'MotherBeeApp/index.html', {})
def section(request, slug):
sections = Section.objects.filter(page=slug)
if sections:
return render(request, 'MotherBeeApp/section.html', {'Sections': sections})
else:
return render(request, 'MotherBeeApp/404.html', status=404)
def subsection(request, slug, subslug):
subsection = Section.objects.get(link_title=subslug)
articles = Article.objects.filter(section=subsection.pk)
page_title = subsection.title
return render(request, 'MotherBeeApp/subsection.html', {'Articles': articles, 'PageTitle': page_title})
def article(request, slug, subslug, articleslug):
article = Article.objects.get(link_title=articleslug)
return render(request, 'MotherBeeApp/article.html', {'Article': article})
If you are using Django version older than Django 2.0 (< 2.0) than you are doing right thing and you are already using optimistic way. but if your Django version is later than or equals to Django 2.0 you could write urlpatterns as shown here.
Maybe you can upgrade your Django to 2.0+, and then use code as follows:
from django.urls import path, include
urlpatterns = [
path('', views.index),
path('<slug:slug>/', include([
path('', views.section),
path('<slug:subslug>/', views.subsection),
path('<slug:subslug>/<articleslug>/', views.article),
])),
]
urls.py :
urlpatterns = [
path('', views.posts, name='home'),
path('<string:slug>', views.post_details, name='detail'),
]
views.py (function) :
def post_details(request, slug):
posts = Posts.objects.get(pk=slug)
return render(request, 'posts/post_details.html', {'posts': posts})
NOTE : I am currently learning django.
Your parameter is called slug, not string.
path('<slug:slug>',...
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
I'm working on a bilingual website French and English, and I'm trying to figure out how to detect and redirect the French users to index_fr.html (in templates folder).
My urls.py (it only shows the english ver. for now):
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', profiles.views.home, name='home'),
]
Thanks for your responses.
As dhke said, I enabled LocalMiddleware and used request.LANGUAGE_CODE to write a function in views.py that renders a template depending on the language and it works!:
views.py:
from django.http import HttpResponse
def home(request):
context={}
if request.LANGUAGE_CODE == 'fr':
template='index_fr.html'
else:
template='index_en.html'
return render(request,template,context)
def fr(request):
context={}
template='index_fr.html'
return render(request,template,context)
def all(request):
context={}
template='index_en.html'
return render(request,template,context)
urls.py:
urlpatterns =[
url(r'^admin/', admin.site.urls),
url(r'^$', profiles.views.home, name='home'),
url(r'^index_fr.html', profiles.views.fr, name='fr'),
url(r'^index_en.html', profiles.views.all, name='all'),
]
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'),