I'm trying to do something like this:
(r'^$', RedirectView.as_view(url='^(?P<username>\w+)/$')),
but it doesn't seem to parse the regex part to the actual username...
I've done research but I can only find examples that redirect to exact urls or other regex examples that work but only in Django 1.1
Anyone have any idea how to do this in Django 1.5+?
Subclass RedirectView, and override the get_redirect_view method.
from django.core.urlresolvers import reverse
class UserRedirectView(RedirectView):
permanent = False
def get_redirect_url(self, pk):
# it would be better to use reverse here
return '/myapp/%s/' % self.request.user.username
You would include your UserRedirectView in your myapp.urls.py module as follows:
url(r'^$', UserRedirectView.as_view(), name='myapp_index'),
It would be better to reverse the url instead of hardcoding /myapp/ in the url above. As an example, if you were redirecting to a url pattern like the following
url(r'^(?P<username>\w+)/$', 'myapp.view_user', name='myapp_view_user'),
Then you could change the get_redirect_url view to:
def get_redirect_url(self, pk):
return reverse('myapp_view_user', args=(self.request.user.username,))
I think you need something like this
(r'^(?P<username>\w+)/$', 'your_view'),
where your_view is
def page(request, username):
pass
If you need redirection with parameters, you can use
('^(?P<username>\w+)/$', 'django.views.generic.simple.redirect_to',
{'url': '/bar/%(username)s/'}),
More info here:
https://docs.djangoproject.com/en/1.2/ref/generic-views/#django-views-generic-simple-redirect-to
and here:
https://docs.djangoproject.com/en/1.4/topics/http/urls/#notes-on-capturing-text-in-urls
You can try this package https://github.com/maykinmedia/django-regex-redirects. It is used in some of our projects
Related
I want to get the URI template for a Django view. As in the Internet Standards URI template, not the Django url template tag. So for example for a urls.py with:
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register(r'collections', views.CollectionViewSet)
and view.py with
from restframework import viewsets
class CollectionViewSet(viewsets.ModelViewSet):
queryset = Collection.objects.all()
serializer_class = serializers.CollectionSerializer
lookup_field='name'
def list(self, *args, **kwargs):
<...code overriding list...>
What I would like to do is to be able to, from the list function, get the uri template like so:
'http://localhost:8000/api/collections/{name}/'
I have tried using rest framework's 'reverse', which is an extension of a django 'reverse' function; like this:
from rest_framework.reverse import reverse
field=self.lookup_field
url = reverse('collection-detail', args=['temp'], request=request)
url = url.replace('temp', '{' + field + '}')
This is so clunky though! Is there a better way?? Thank you :)
I tried to google this but all the results are about the url template tag, which is something else entirely.
I don't know any solution provided out of the box but I know there is a command in the django-extensions that gives a way to print all urls patterns and their params,
you could dig a solution from how they did it:
Code extract for show_urls command
# Basicly they load urls configurations
# ...
urlconf = __import__(getattr(settings, 'ROOT_URLCONF'), {}, {}, [''])
# ...
# then you can have a look on the patterns
print(urlconf.urlpatterns)
Sorry if this seems too 'hacky' but perhaps it could help you.
How to redirect to another domain with python django and pass additional informations?
For example i want to redirect to https://ssl.dotpay.pl/test_payment/ and give additional informations so url will look like this
https://ssl.dotpay.pl/test_payment/?id=123456&amount=123.00&description=Test
but I don't want to generate url in my view, just pass the data in json or something like that.
What is the way to do this?
this is generated url by what i meant 'ssl.dotpay.pl/test_payment/?id=123456&amount={}&description={}'.format(123.00, 'Test')
Be sure to put a protocol before your url (or at least two slashes).
This way, Django will see it as an absolute path.
From your comment it seems you redirect to ssl.dotpay.pl what will be seen as a local path rather than another domain.
This is what I came across. (See question I put on stackoverflow and answer)
So in your case, you can use the following:
class MyView(View):
def get(self, request, *args, **kwargs):
url = 'https://ssl.dotpay.pl/test_payment/'
'?id=123456&amount={}&description={}'.format(123.00, 'Test')
return HttpResponseRedirect(url)
You could also use redirect from django.shortcuts instead of HttpResponseRedirect
Assuming you are using a functional view, you could probably do something like this in your view:
from django.http import HttpResponseRedirect
def theview(request):
# your logic here
return HttpResponseRedirect(<theURL>)
Not sure if I should be doing this or not... but here goes.
I have a url that looks like this:
/deals/category/Apparel/
I changed it to category/Apparel to shorten it.
but also notice the capitalized Apparel --as it is using the category name.
So I added a slug to my Category model and I'm trying to redirect the
deals/category/Apparel to category/apparel where the latter represents the slug
In my deals app I have this URL:
path('category/<str:category>', RedirectView.as_view(pattern_name='category', permanent=True)),
and which I'm trying to redirect to (in my core urls file)
path('category/<slug:slug>', deals_by_category, name='category')
My view for the `deals_by_category' looks like this:
def deals_by_category(request,slug):
category_deals = Deal.objects.filter(category__slug=slug).order_by('expired','-date_added')
category = category_deals[0].category
return render(request, 'deals/category.html', {'category_deals': category_deals, 'category':category})
so when I go to deals/category/Apparel it is redirecting to category/Apparel which is not what I want... and I get an error like this:
Reverse for 'category' with keyword arguments '{'category': 'Apparel'}' not found. 1 pattern(s) tried: ['category\\/(?P<slug>[-a-zA-Z0-9_]+)$']
I guess I understand that it is looking at the category name and trying to match against a slug, but not exactly sure how to correctly redirect this with the correct format.
path('category/<str:category>', RedirectView.as_view(pattern_name='category', permanent=True)),
When you use pattern_name, Django will try to reverse the URL with the same args and kwargs, in this case category='Apparel'.
If you want to use the slug in the URL instead, then you'll have to subclass RedirectView and override get_redirect_url.
from django.shortcuts import get_object_or_404
class CategoryRedirectView(RedirectView):
permanent = True
def get_redirect_url(self, *args, **kwargs):
category = get_object_or_404(Category, name=self.kwargs['category'])
return reverse('category', kwargs={'slug': category.slug})
Then use your view in your URL pattern:
path('category/<slug:slug>', CategoryRedirectView.as_view(), name='category')
I wouldn't set permanent = True until you are sure that the redirect is working as expected. Otherwise browsers may cache incorrect redirects.
What I am trying to do is as follows
I have urls like this /blog/1/sdc/?c=119 or /forum/83/ksnd/?c=100 What I want to do is to redirect these to a view, so that I can change the url to /blog/1/sdc/#c119
One way would be to do this is to make provision in views of each of the app, where such a url maybe generated, but that is not scalable. What I want to do is to catch any url that has ?c=<some_digit> at the end and redirect to my custom view.
Can anybody help, I am not good with regex.
You can't do this in your urlconf, it doesn't match anything in the query string. What you'll need to do is write a middleware along the lines of this:
class RedirectMiddleware:
def process_request(self, request):
if 'c' in request.GET:
# return a HttpResponseRedirect here
See https://docs.djangoproject.com/en/dev/topics/http/middleware/ for more details.
In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?
What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.
If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature:
reverse(viewname, urlconf=None, args=None, kwargs=None)
https://docs.djangoproject.com/en/dev/ref/urlresolvers/
At the time of this edit the import is django.urls import reverse
I'm using two different approaches in my models.py. The first is the permalink decorator:
from django.db.models import permalink
def get_absolute_url(self):
"""Construct the absolute URL for this Item."""
return ('project.app.views.view_name', [str(self.id)])
get_absolute_url = permalink(get_absolute_url)
You can also call reverse directly:
from django.core.urlresolvers import reverse
def get_absolute_url(self):
"""Construct the absolute URL for this Item."""
return reverse('project.app.views.view_name', None, [str(self.id)])
For Python3 and Django 2:
from django.urls import reverse
url = reverse('my_app:endpoint', kwargs={'arg1': arg_1})
Be aware that using reverse() requires that your urlconf module is 100% error free and can be processed - iow no ViewDoesNotExist errors or so, or you get the dreaded NoReverseMatch exception (errors in templates usually fail silently resulting in None).