I am in a way of making a module for my project that can be reused later also.
Lets say I have an django app named "demo" and I have included it in root url like url(r'demo/',include("demo.urls")),
Now inside "demo.urls" I want to redirect admin url to custom url.
/admin/auth/group/add/
should be redirected to any url that is of demo.urls
define a view function that redirects to your desired url:
from django.http import HttpResponseRedirect
def redirect_to_desired_url(request):
return HttpResponseRedirect('new_url/')
and then in your urls.py
urlpatterns = patterns('',
...
url(r'^/redirect_to_desired_url/$',redirect_to_desired_url),
...
)
Related
My views.py runs code fine when I press a button on my HTML page, views.py:
def start_or_end_fast(request):
#If starting fast, add a row to the db:
#fast_finished = False
#start_date_time using = current time
#end_date_time using = current time
if request.method == 'POST' and 'start_fast' in request.POST:
add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now())
add_fast.save()
print(add_fast.start_date_time,add_fast.end_date_time)
print('Fast started')
#return render(request,'startandstoptimes/index.html')
return HttpResponseRedirect('startandstoptimes/index.html')
You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become.
My application urls.py:
from turtle import home
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.start_or_end_fast,name="start_or_end_fast")
]
My project urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('startandstoptimes.urls'))
]
I believe it is related to the URLs, due to the 404 message I see:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/startandstoptimes/index.html
Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order:
admin/
[name='start_or_end_fast']
The current path, startandstoptimes/index.html, didn’t match any of these.
Am I going down the right route trying to use HttpResponseRedirect or is there a better solution?
class HttpResponseRedirect¶
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.
'https://www.yahoo.com/search/'), an absolute path with no domain
(e.g. '/search/'), or even a relative path (e.g. 'search/'). In that
last case, the client browser will reconstruct the full URL itself
according to the current path. See HttpResponse for other optional
constructor arguments. Note that this returns an HTTP status code 302.
See this link for more details: docs
As what the documentation says, HttpResponseRedirect accepts URL and not the path of your template. You should be doing it something like this:
from django.urls import reverse
return HttpResponseRedirect(reverse('start_or_end_fast'))
I'm new to Django and am trying to create a small website where I click on a flag and the language changes. I'm using django i18n for that:
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [url(r'^i18n/', include('django.conf.urls.i18n'))]
urlpatterns += i18n_patterns(
url(r'^$', views.home, name='home'),
)
The problem is, when I run the following code:
templetatags.py
#register.simple_tag
def test():
r = requests.post('http://localhost:8000/i18n/setlang/', data = {'lang':'en', 'next' : '/'})
print r.status_code
home.html
<div id='country_flags'>
<a hreflang="en" href="{% test %}"><img id='en' src='{% static "mysyte/images/gb.png" %}'></a>
</div>
the result of r.status_code is 403.
What am I doing wrong?
Any POST request in django requires you to send the CSRF-Cookie by default. Your options around this:
Don't use a POST request. Use GET instead.
Send the CSRF-Token with the request. https://docs.djangoproject.com/en/1.9/ref/csrf/
use the decorator #csrf_exempt to remove any csrf-protection from a view (in your case the view for http://localhost:8000/i18n/setlang/)
don't send a request to your own app. use a link for the user to click on. probably your best option.
Note:
if you want to use the decorator w/ a class-based view, decorate the dispatch() function of that view
How can I redirect any kind of url patterns to a created page "404.html" page if it doesn't exist in the urls.py rather than being shown the error by django.
Make a view that'll render your created 404.html and set it as handler404 in urls.py.
handler404 = 'app.views.404_view'
Django will render debug view if debug is enabled. Else it'll render 404 page as specified in handler404 for all types of pages if it doesn't exist.
Django documentation on Customizing error views.
Check this answer for a complete example.
In your views.py, just add the following code (No need to change anything in urls.py).
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
Put a custom 404.html in templates directory.
source : click here
There is no need to change anything in your view or url.
Just do these 2 steps, in your settings.py, do the following
DEBUG = False
ALLOWED_HOSTS = ["*"]
And in your app directory (myapp in this example), create myapp/templates/404.html where 404.html is your custom error page. That is it.
Go to your project settings.py and set DEBUG = True to DEBUG = False
Then Django redirects all NOT set patterns to not found.
In additional if you want to customize 404 template , in your project urls.py
set
handler404 = 'app.views.404_view'
then in your projects view.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
and Finally, in your templates add 404.html and fill it with what you want to show end user.
I have my url:
url(r'^home/', HomeQuestionView, name='home_question') ,
When I enter localhost:8000/home I get my homepage but what I want is when I just enter I get my homepage.
I mean I want to redirect to the above homepage url when user enters only my site likewww.xyz.com not www.xyz.com/home
I dont want to configure in this way
url(r'^', HomeQuestionView, name='home_question') ,
Thanx in advance
Use generic RedirectView:
from django.views.generic.base import RedirectView
url(r'^$', RedirectView.as_view(url='/home/')),
I found this solution (long story short, you need to add views.py to your main project folder and make view which redirect your empty route to your url):
In your urls.py inside urlpatterns add this:
urlpatterns = [
...
path("", views.home, name="home"),
...
]
In main Django folder create views.py and import it in urls.py
example
In views.py add this code:
from django.shortcuts import render, redirect
def home(request):
return redirect("blog:index") # redirect to your page
Now every time your url will be empty like (localhost:8000) it will be redirected to (localhost:8000/your_adress). Also, you can use this not only with blank url, but anywhere you need this sort of redirection
I plan on having several different apps inside my django project, each for a new technology I want to play around with. As I work on each on, I want to have the root URL path redirect to the project I'm working on.
Directory Structure:
backyard/
my_project/
views.py
backyard/
urls.py
backyard/backyard/urls.py:
from django.conf.urls import patterns, include, url
from django.shortcuts import redirect
urlpatterns = patterns('',
url(r'^$', redirect('my_app/')),
url(r'^my_project/$', 'my_project.views.homepage'),
)
backyard/my_project/views.py
def homepage(request):
return render_to_response('my_project/index.html', {'data':data})
When I access the page at http:machine-name:8000/ I get an error saying The included urlconf backyard.urls doesn't have any patterns in it I most definitely have URLs in my urls.py, what is the issue?
A URLconf needs to map regexes to views -- the redirect function doesn't return a view; rather, it returns an HttpResponse. You can look at this question for an example of how to define a redirect directly in the URLconf.