I'm currently experimenting with Django and creating apps following the tutorials on the official website.
So my urls.py looks like:
urlpatterns = patterns('',
(r'^/$','ulogin.views.index'), #why doesn't this work?
(r'^ucode/$', 'ulogin.views.index'),
(r'^ucode/(\d+)/$', 'ulogin.views.index'),
)
And my views.py looks like:
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
def redirect_to_index(request):
return HttpResponseRedirect('/ucode/')
When I run the server to check the test url, http://127.0.0.1:8000/ucode displays "Hello, world...etc" correctly, and works just fine. I've been messing with urls.py but I don't know how to get http://127.0.0.1:8000/ to display ulogin.views.index.
First of all, for the pattern to match
(r'^/$','ulogin.views.index')
Should be
(r'^$','ulogin.views.index')
Also, trying to match the following URL would raise errors
(r'^ucode/(\d+)/$', 'ulogin.views.index'),
because there is no view method that takes \d+ as a parameter.
The fix i recommend is:
(r'^ucode/(<?P<id>[\d]+)/$', 'ulogin.views.index'),
and then
def index(request, id=None):
return HttpResponse("Hello, world. You're at the poll index.")
You can read more about named URL groups here
It does not work because the root of a web-server when it comes to django urls is characterized by the empty string, like so -> ^$. So, just change ^/$ to ^$, and it will work.
Related
I'm pretty new to django and i'm working on a website that needs a dynamic URL for a database table, and it all works fine, but i would like to know how to remove the "?id=" from the url, so rather than
localhost:8000/dynamicurl/?id=XXXXX
The url becomes
localhost:8000/dynamicurl/XXXXX
Instead
I did a fine amount of searching in the documentation and didn't find a lot, though it's pretty likely i missed something.
EDIT:
thanks everyone for helping, the simplest answer was to remove the object i was using to fetch the ID and just replace it for ID in evert instance,
so my url became
url(r'^dynamicurl/(?P[0-9]+)/$', views.dynamicurl)
and my view became
def dynamicurl(request, id):
i'm like very very new to django FYI
you can capture a variable in url definition in the apps urls.py file. It would look something like this:
url(r'^dynamicurl/(?P<id>[0-9]+)?$', dynamicurl, name = 'dynamicurl'),
then in your view function you receive that parameter:
def dynamicurl(request, id):
If you are talking about how to change your url inside the urls, I suggest you to use code that already answered above: https://stackoverflow.com/a/41988051/6396981
But, if you talking about how to redirect localhost:8000/dynamicurl/?id=XXXXX to localhost:8000/dynamicurl/XXXXX, hope this usefull..
1. views.py
from django.http import HttpResponse
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse
class RedirectView(RedirectView):
permanent = False
def get_redirect_url(self):
get_id = self.request.GET.get('id')
if get_id is not None:
return reverse('redirected_page', kwargs={'id': id})
return reverse('origin_page')
def redirected_view(request, id):
# your final view goes here...
return HttpResponse("You're looking for id: %d." % id)
2. urls.py
from django.conf.urls import url
from yourapp.views import views (RedirectView, redirected_view)
urlpatterns = [
# first view the pool to doing redirection
url(r'^pool/$', RedirectView.as_view(), name='origin_page'),
# the final url
url(r'^pool/(?P<id>[\d]+)/$', redirected_view, name='redirected_page'),
]
Am trying to catch a variable in a url in my urls.py file, then pass it to a function in my views file, where I want to use it as a string:
# urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/(?P<title>)', views.blog_ronn_post, name='blog_ronn_post'),
]
# views.py
from django.http import HttpResponse
def blog_ronn_post(request, title):
html = "<html><body>This is the page for the blog titled: {s} </body></html>".format(title)
return HttpResponse(html)
However this doesn't work. In my development browser the html shows up, but displays nothing after the final colon. I don't think there is a problem with my Python 3 syntax as if I try to use a string in the format parentheses, eg:
html = "<html><body>This is the page for the blog titled: {s} </body></html>".format('Title 1')
it works, displaying " ... titled: Title 1". So why doesn't it pass my title string? I understood it that title is passed from url to views as a string, so there should be no problem. New to django so apologies if I'm making an obvious mistake.
Because you haven't given it anything to match.
r'^posts/(?P<title>\w+)$'
I have a view that either displays a form or a 'thank you' page (if the form submission was successful). I am using redirect with a url that I have tested working to display the thank-you page.
def form8(request):
form = UserInfoForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/sjwork/thanks')
return render(request, 'form8.html', {'form': form})
However, when the form is successfully submitted django give the error:
ViewDoesNotExist at /sjwork/form8
Could not import views. Error was: No module named views
As said, I can go to localhost:8000/sjwork/thanks directly and it displays the thank-you page. According to documentation I can use a hard-coded url like this. I tried alternatives, too (giving the view, using a full url like http://google.com) - nothing works. I must be missing something basic here. Would appreciate if someone can explain what is going on here. Thanks.
The app 'sjwork' has the following in its urls.py:
url(r'^$', 'views.home', name='home'),
url(r'^thanks$', 'sjwork.views.thanks'),
url(r'^form8$', 'sjwork.views.form8', name='form8'),
whereas the project urls.py contains:
url(r'^sjwork/', include('formtest.sjwork.urls')),
Looks like error is related to this pattern.
url(r'^$', 'views.home', name='home'),
Try removing it and try again.
Also, Could you include your import statements in your question.
Why? I want multiple models on the first level of the path :)
Using: Django 1.4.1
Code setup urls:
PAGE_SLUGS = '|'.join(Page.objects.values_list('slug', flat=True))
BRAND_SLUGS = ... same concept
(r'^(?P<brand_slug>%s)/$' % BRAND_SLUGS, 'novomore.apps.catalog.views.product_showcase_list'),
url(r'^%s/$' % PAGE_SLUGS, 'prefab.apps.pages.views.page_detail', name='page'),
In the save method of model Page:
if self.pk is None:
clear_url_caches()
I don't want to run a query on each request so thats why i use this aproach, when i add a instance the PAGE_SLUGS need to be updated.
clear_url_caches() doesnt seem to work
Any suggestions?
This doesn't do the trick:
if settings.ROOT_URLCONF in sys.modules:
reload(sys.modules[settings.ROOT_URLCONF])
reload(importlib.import_module(settings.ROOT_URLCONF))
From How to reload Django's URL config:
import sys
from django.conf import settings
def reload_urlconf(self):
if settings.ROOT_URLCONF in sys.modules:
reload(sys.modules[settings.ROOT_URLCONF])
return import_module(settings.ROOT_URLCONF)
I don't think what you're trying to do is a good idea. Why not simply allow any slug pattern in the URL regex, but return a 404 if you can't find the Page in question? That would have the same effect and be much simpler.
url(r'^(?P<slug>\w+)/$', 'prefab.apps.pages.views.page_detail', name='page'),
then your view code can do something like
from django import shortcuts
def page_detail(request, slug):
page = shortcuts.get_object_or_404(Page, slug=slug)
...
I'm in c.html (http://localhost:8000/practice/c) and I click a link that changes my url to
http://localhost:8000/practice/c/?q=1
this is urls.py
url(r'^$', prac_c),
url(r'^q=\d',fetch_c),
and this is views.py
def prac_c(request):
return render_to_response('subject/c.html', {"problem_list":problem_list})
def fetch_c(request):
qno = request.GET.get('q')
if qno:
return render_to_response('subject/que.html', {'qno':qno}, context_instance=RequestContext(request))
but I'm not getting directed to que.html. Something wrong with the urls.py?
What the URLconf searches against
The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.
source