Django response redirect on variable url - django

I'm on a page with a variable url /emails/edit/32/, and I want to update the form and refresh the page...how do I issue an HttpResponseRedirect to the current page, which has a variable extension?
My urls.py is:
urlpatterns = patterns('',
(r'^emails/edit/$', 'email_edit'), # this is the page it is re-directing to
(r'^emails/edit/(?P<email_id>\d+)/$', 'emails_single'),
)
And my views.py is:
def emails_single(request, email_id):
...(stuff)...
Email.objects.filter(id=request.POST['id']).update(email=request.POST['email'])
return HttpResponseRedirect(reverse('emails_single',args=[email_id]))
Update: what it is doing is just chopping off the ending of the URL (even when using the reverse examples). For example: http://127.0.0.1:8000/emails/edit/42/ --> http://127.0.0.1:8000/emails/edit/

from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('emails_single', args=[email_id]))

reverse()

from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('urlname', args=[1945]))

Related

Django redirect doesn't reach the root url

Looks like redirect(<url>) is adding <url> to the current view url, ignoring urls.py, with respect to the Code below redirecting to "<mydomain>.com/savePersonalEdits/account/" while what I wanted is: "<mydomain>.com/account/"
Code:
At the end of some Django view function I have:
return redirect('account/')
urls:
path('account/', views.accountSettings),
path('savePersonalEdits/', views.saveEdits, name="savePersonalEdits") #name needed for HTML form action url
you can use HttpResopnseRedirect for this
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/account/')
also there is a better way to redirect, create name your path in ulrs.py
path('account/', views.accountSettings, name="account_url_name"),
#and in your views import reverse and HttpResponseRedirect
from django.urls import reverse
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse("account_url_name"))
Just do it
return redirect('/account/')
or
return redirect('account')

Can't redirect using urls patterns

When i try go to http://127.0.0.1:8000/1395ec37e4/ i get error: Page not found at ...
I don't know why, twice, when i had changed variable getted_short_url to short_urlin urls.py and views.py(redirect_view) it could redirect me. I am confused...
Log from page:
Using the URLconf defined in cut_and_go.urls, Django tried these URL patterns, in this order:
<str:getted_short_url>
admin/
The current path, 1395ec37e4/, didn't match any of these.
views.py:
from hashlib import sha256
from .models import URL
from .forms import URLInput
from django.shortcuts import render, redirect
def input_form(request):
if request.method == 'POST':
form = URLInput(request.POST)
if form.is_valid():
getted_url = form.cleaned_data["full_url"]
transformed_url = 'https://' + getted_url
try:
URL.objects.get(full_url=transformed_url)
except URL.DoesNotExist:
maked_url = sha256(transformed_url.encode()).hexdigest()[:10]
URL(full_url=transformed_url, short_url=maked_url).save()
else:
form = URLInput()
return render(request, 'shortener/input_form.html', {'form': form})
def redirect_view(request, getted_short_url):
return redirect(URL.get_full_url(getted_short_url))
urls.py:
from . import views
from django.urls import path
urlpatterns = [
path('', views.input_form),
path('<str:getted_short_url>', views.redirect_view)
]
The str path converter does not catch the / character at the end of your URL. If you want to match only the part before the /, add a 2nd urlpattern (or replace the existing one if you don't care about URLs not ending with /) that includes the / at the end. If you want to catch this trailing slash in your path argument, use path instead of str. See Django docs for more information.

How to redirect to another page

Well, I have my own session and authentication routines in my app. When a user goes to app/login/ page, if he or she is not loggen in, then he/she sees a form to submit, otherwise I want to redirect the user to the root page app/. login view looks like this:
def index(request):
if sessionCheck(request):
# here I want to redirect one level above to app/
pass
else:
template = loader.get_template('login/login.html')
... other code which is not important
In PHP, I think, I would do it like this:
header("Location: /");
exit;
But how should I do exactly the same thing in Django?
You can use the redirect shortcut function:
from django.shortcuts import redirect
return redirect('some-view-name')
You can also specify a URL apart from a named view. So if your index url does not have a name, you can specify '/'.
This shortcut function is essentially the same as:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('some-view-name'))
In order to have a named view, in your urls.py you have to provide a name argument. For instance:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^some-view$', views.something, name='some-view-name'),
]
More on that on Django tutorial, Django URL dispatcher.
You can use redirect
if sessionCheck(request):
redirect(your_url)
else:
...

Following django form submission, redirect to page using newly created pk

I am trying to redirect the user to edit details of a task after task submission, but am having troubles redirecting to a page based on the newly created pk. Each view works without the return HttpResponseRedirect line. I have also tried arge=(instance.id) and kwargs=(instance.id) for the variable.
views.py
...
from django.http import HttpResponseRedirect, HttpResponseServerError, HttpResponseForbidden, Http404, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404,render
...
def new_task(request):
...
...
task.save()
instance = task.save()
return HttpResponseRedirect(reverse('task_values', instance.id))
def task_values(request, task_id):
...
urls.py
from django.conf.urls.defaults import patterns, include, url
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
urlpatterns += patterns('core.views_entry',
#Task viewing/editing
(r'^task/(?P<task_id>\d+)/$','task_values'),
(r'^enter/$','new_task'),
return HttpResponseRedirect(reverse('task_values', kwargs={'task_id': instance.id}))
Also note that you don't need to save the task twice.
Edit OK, there's another problem. You haven't given your URLs specific names, which means that the only way to identify them is to pass the fully qualified view name:
reverse('core.views_entry.task_values', kwargs=...)
Or, better, use the the url() function to name your URL:
url(r'^task/(?P<task_id>\d+)/$','task_values', name='task_values'),
and you can use the original version I gave above.
Note that the error isn't telling you it's going to enter/<id>/, just that in that view it's trying to create the reverse URL for the redirection and failing.

Django RequestContext and media doesnt work

I'm beginner, but I've been looking everywhere for solution. I can't see uploaded images (404).
Error from image link (for example:http://192.168.1.1:8000/media/portfolio/icon.png/ -> by the way, this proper url ) :
No SuperPages matches the given query.
SuperPages is my model which contains url object.
I configured everything for media files like here: http://www.muhuk.com/2009/05/serving-static-media-in-django-development-server/. And to be clear, when I'm using generic views only, it works great. But with views, I can't see images (links to images are fine). Static files works great. So this is my code:
urls.py
from mysite.cms.views import superpages
urlpatterns = patterns('',
(r'^(?P<url>.*)$', superpages),)
views.py
from django.template import loader, RequestContext
from mysite.cms.models import SuperPages
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
DEFAULT_TEMPLATE = 'default.html'
def superpages(request, url):
if not url.endswith('/') and settings.APPEND_SLASH:
return HttpResponseRedirect("%s/" % request.path)
if not url.startswith('/'):
url = "/" + url
f = get_object_or_404(SuperPages, url__exact = url)
t = loader.get_template(DEFAULT_TEMPLATE)
c = RequestContext(request, {
'superpages': f,
})
return HttpResponse(t.render(c))
There's something wrong with your urls.py. I suppose you have defined your patterns like this:
urlpatterns = patterns('',
(r'^(?P<url>.*)$', superpages),
(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
A URL such as http://192.168.1.1:8000/media/portfolio/icon.png/ matches the first pattern so your superpages view is called and raises a 404. What you need to do is put your catch-all superpages pattern at the very end of your urlpatterns. Or you can choose a different approach with a middleware, see what django.contrib.flatpage does for an example.