regular expression in django for urls - python

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.

Related

Django view that redirects to another domain

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>)

Django: Make query using url ( Assigning variable using url )

I am trying to make a query system for my website, i think the best way and the most compact would be to assign search variable using url pattern.
So for example, i want to search objects of model User:
User sends HttpRequest to following url:
https://127.0.0.1/search/q="admin"
Now HttpRequest is also sent to search view, we somehow get q variable data.
def search(request):
for query in User.objects.all():
if q in query: # < We somehow need to get data of 'q'.
return HttpResponse(q)
Since i have admin in User.objects.all(), this should return HttpResponse of 'admin'.
How can this url pattern be made? So i can assign q variable from the url and then send it to system to find it?
I have problems with this URL:
https://127.0.0.1/search/q="admin"
There is no ? in the URL, so there is no query string, it's all part of the "path". Using characters like = and " in there will confuse a lot of things, if it works at all.
Either just do
https://127.0.0.1/search/admin
With an URL pattern like r'^search/(?P<querystring>.+)$', or
https://127.0.0.1/search/?q=admin
In this case the query string will be in request.GET['q']; it's also possible to use Django forms to process query parameters (e.g. for validating them).
You can capture named strings from URLs like this:
urls.py:
urlpatterns = [
url(r'^blog/page(?P<num>[0-9]+)/$', views.page),
]
views.py:
def page(request, num="1"):

How can I redirect in django middleware? global name 'view' is not defined

Django newbie here, need help on basic middleware to redirect to another view if a certain model field is empty.
I am creating a terms of agreement page that users must get redirected to right after they signup to the platform if their filed_terms field on their Profile model is empty.
I am using middleware for this. However I am unable to get this to work. This is my middleware class:
class TermsMiddleware(object):
def process_request(self, request):
if request.user.profile.filled_terms is None:
return redirect(reverse(terms))
This gives me the following error:
global name 'terms' is not defined
I also have the url matcher that works perfectly when I navigate to it manually:
url(r'^terms/', 'my_app.views.terms')
I have a terms.html template and a terms view in my views.py file that is working perfectly in all other respects. I have also added it to the settings middleware requirements to make sure it loads.
Do I have to import something from views or url dispatcher into my middleware file? If so what would that be? I have been at this for a while an cannot find anything helpful.
reverse function takes url name instead on the regex. So you need to add name on your url configuration. Here is the example.
url(r'^terms/', 'my_app.views.terms', name='terms')
Add this in your views.py
from django.core.urlresolvers import reverse
And you need to fix your reverse function into.
return redirect(reverse('terms'))
Python interpret your terms as a variable and you have no variable named terms while you need to put string on reverse.

Django 1.5 url redirect with regex?

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

How to use current logged in user as PK for Django DetailView?

When defining URL patterns, I am supposed to use a regular expression to acquire a PK from the URL.
What if I want a URL that has no PK, and if it's not provided, it will use the currently logged in user? Examples:
visiting /user will get a DetailView of the currently logged in user
/user/edit will show an UpdateView for the currently logged in user
I tried hard-coding the pk= in the Detail.as_view() call but it reports invalid keyword.
How do I specify that in the URL conf?
My sample code that shows PK required error when visiting /user URL:
urlpatterns = patterns('',
url(r'user/$',
DetailView.as_view(
model=Account,
template_name='user/detail.html')),
)`
An alternative approach would be overriding the get_object method of the DetailView subclass, something along the line of:
class CurrentUserDetailView(UserDetailView):
def get_object(self):
return self.request.user
Much cleaner, simpler and more in the spirit of the class-based views than the mixin approach.
EDIT: To clarify, I believe that two different URL patterns (i.e. one with a pk and the other without) should be defined separately in the urlconf. Therefore they could be served by two different views as well, especially as this makes the code cleaner. In this case the urlconf might look something like:
urlpatterns = patterns('',
url(r"^users/(?P<pk>\d+)/$", UserDetailView.as_view(), name="user_detail"),
url(r"^users/current/$", CurrentUserDetailView.as_view(), name="current_user_detail"),
url(r"^users/$", UserListView.as_view(), name="user_list"),
)
And I've updated my example above to note that it inherits the UserDetailView, which makes it even cleaner, and makes it clear what it really is: a special case of the parent view.
As far as I know, you can't define that on the URL definition, since you don't have access to that information.
However, what you can do is create your own mixin and use it to build views that behave like you want.
Your mixin would look something like this:
class CurrentUserMixin(object):
model = Account
def get_object(self, *args, **kwargs):
try:
obj = super(CurrentUserMixin, self).get_object(*args, **kwargs)
except AttributeError:
# SingleObjectMixin throws an AttributeError when no pk or slug
# is present on the url. In those cases, we use the current user
obj = self.request.user.account
return obj
and then, make your custom views:
class UserDetailView(CurrentUserMixin, DetailView):
pass
class UserUpdateView(CurrentUserMixin, UpdateView):
pass
Generic views uses always RequestContext. And this paragraph in the Django Documentation says that when using RequestContext with auth app, the template gets passed an user variable that represents current user logged in. So, go ahead, and feel free to reference user in your templates.
You can get the details of the current user from the request object. If you'd like to see a different user's details, you can pass the url as parameter. The url would be encoded like:
url(r'user/(?P<user_id>.*)$', 'views.user_details', name='user-details'),
views.user_details 2nd parameter would be user_id which is a string (you can change the regex in the url to restrict integer values, but the parameter would still of type string). Here's a list of other examples for url patterns from the Django documentation.

Categories

Resources