I have a some problem with routing in my django app.
The problem:
There is some dynamic website and site administrator can create pages with random urls. For example, he can create a news page with url "company/news" or "store/news". Or he can create the page with feedback form with url "feedback" or "user/feedback".
So, Django needs to catch this request and show appropriate news or feedback content for these pages. How can I route the user request to the appropriate view according to the requested page functionality?
You can create view that parses your URL and chooses strategy for different types.
# urls.py
...
url(r'^dynamic-view/(?P<dynamic_view_url>.*)/$', 'dynamic_view')
# views.py
def dynamic_view(request, dynamic_view_url):
url_parts = [p for p in dynamic_view_url.split("/") if p]
if "feedback" in url_parts:
return _view_for_feedback(request, url_parts)
elif "news" in url_parts:
return _view_for_news(request, url_parts)
else:
raise Http404
Related
I'm working on a project, I want to code the following steps
=> The user in page A wants to access to page B, so the user in page A will redirect to page B after validating the form, then :
Creating a random url
The user is redirected to that random URL
the user cant access to page B if he doesn't validate the form on page A
I use django 2.1
Thanks for your help :)
You can do this with reverse from django.url and can able to pass random args or kwargs link.
Say your urls are be like
urlpatterns = [
path('articles/', your_article_view),
path('articles/<slug:slug>/', your_article_slug_view),
]
and from your article_view you can redirect to article_slug_view as
reverse('articles', args=['hello'])
'/articles/hello' # url
you can generate uuid and pass it by this, this will always make sure random different url everytime. Whatever you want to do.
First of all, let me say that this looks like an anti-pattern.
On Django you can set url's that matches some expression:
path('secret/<slug:passwd>/', views.super_secret, name="secret")
Then, you can redirect to this url with a key:
if form.is_valid():
some_key = #some random key
cache.set(some_key, True, 3)
return HttpResponseRedirect(reverse('secret', args=(some_key,)))
And check your key from cache on view secret.
So i've installed Django allauth to handle my login authentication. However I don't want a seperate URL for login. I want it to be available on my homepage via Javascript onclick (login box appears when you click a button/no page refresh). But the current allauth URL is located at '/accounts/login'. So as I said I need it located at '/'. How would I do this?
Here is my views.py:
def boxes_view(request):
...
search = request.GET.get('search')
posts = Post.objects.all().filter(category=1).order_by('-date')
if search:
posts = posts.filter(
Q(title__icontains=search) |
Q(content__icontains=search)
)
else:
posts = Post.objects.all().filter(category=1).order_by('-date')
context = {
'posts': posts,
}
return render(request, 'polls.html', context)
Can I pass it in as context or? How would it be done?
It sounds like you want a user to be able to log in using a modal from your homepage, or what you currently see when going to '/'
If so, you don't change the allauth login url. Instead change your javascript code for your login box to present the contents given here.
See also this answer.
I am new to Wagtail and python, so could apprectiate some help with my problem.
I have a web app (wagtail web site + rest api backend).
On my website I have 2 pages:
HomePage with list of accessible objects (e.g. photos)
PhotoPage with a detailed information on photo
What I want to achive:
When I click on photo on homepage I am redirected to the photopage
I fill the photopage with information I got from backend
And the photopage url is smth like this http://example.com/photo?id=12345
So, I want to
have 1 model for photopage
fill photopage based on a requested url (i.e. from homepage I redirect user to example.com/photo?id=12345 and it is filled with information on photo with id=12345)
I guess there should be some middleware to parse requested url to get the id and fill the page with info from API. Is there any standard solution to this issue?
Page objects (and any classes that inherit from Page) have a get_context method that can be used to add context pre-rendering of your templates.
from django.shortcuts import get_object_or_404
class PhotoPage(Page):
# your model definition ...
def get_context(self, request):
context = super(PhotoPage, self).get_context(request)
photo_pk = request.GET.get('id',None)
photo = get_object_or_404(YourPhotoModel,pk=photo_pk) # if no matching photo, return 404. You can do whatever you like instead :)
context['photo'] = photo
return context
Now in your photo template you can access your Photo model instance directly...
{{ photo.some_attribute }}
{{ photo.some_other_attribute }}
I'm using django allauth for user authentication and so far I have been able to display user's page like this: account/1/trial/, where 1 is the pk number and trial is the username(unique), or like this: account/1/. In both cases everything works fine, but if I want to show only the username (account/trial/) in the url than I can't load the profile (accounts/profile/) page for the logged in user(404). Probably my profile function is wrong, how can I correct it so that the page will load normally as if using pk in urls.
urls:
(r"^(?P<pk>\d+)/(?P<slug>[\w.#+-]+)/$", DetailView.as_view(context_object_name='detail',slug_field = "username",model=User,template_name='account/user_detail.html'), name='detail_view'), #if I use this url the page loads correclty
(r"^(?P<pk>\d+)/$", DetailView.as_view(context_object_name='detail',slug_field = "username",model=User,template_name='account/user_detail.html'), name='detail_view'), # also with this url it works
(r"^(?P<slug>[\w.#+-]+)/$", DetailView.as_view(context_object_name='detail',slug_field = "username",model=User,template_name='account/user_detail.html'), name='detail_view'), #if I use only the slug the page does not load.
(r"^profile/$", views.profile, name="profile_view"), #this is the profile page url
and the profile page view:
def profile(request):
return render_to_response("account/profile.html",locals(),context_instance=RequestContext(request))
The string "profile" matches the regex for the slug-only username view, and since Django matches URLs in order, a request for the URL "profile/" will always go to that view instead. The simple solution is to move the profile URL above the other one.
Hey there I try to use userena with django to build a website which has a clean dashboard after login in. My current problem is that userena uses a pretty high url depth.
Userena is under myproject/accounts and uses the url 'user'. Later 'dashboard'.
When logged in 127.0.0.1:8000/user/ is the userena url. In the normal state it lists all registred users. I've managed to change that to show the current logged in users profile with (accounts/urls.py):
url(r'^$', views.dashboard, name='dashboard'),
url(r'^', include('userena.urls')),
My problem is now that I want to change the normal userena urls.
Userena urls are:
127.0.0.1:8000/user/username/signout
127.0.0.1:8000/user/username/edit
127.0.0.1:8000/user/username/email
127.0.0.1:8000/user/username/password
....
I want:
127.0.0.1:8000/user/signout
127.0.0.1:8000/user/edit
....
I've tried to change both the url and the view but I get always the GuardianError.
Url change:
url(r'^edit', userena_views.profile_edit),
View change:
url(r'^edit', views.settings, name='settings'),
+
def settings(request):
user = request.user
response = userena_views.profile_edit(request, user)
return response
The error:
There are probably multiple ways to archive this. Thank you for the help and sorry for the poor english.
I found a method to solve this here http://tundebabzy.blogspot.de/2013/04/an-easy-way-to-override-third-party-app.html
I practically changed the view like in the tutorial to serve the same files like the original userena view. The case that there will be no username had me to add that extra in the view.
def profile_edit(request, edit_profile_form=userena_forms.EditProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None, **kwargs):
username = request.user
return userena_views.profile_edit(request=request, username=username,
edit_profile_form=edit_profile_form, template_name=template_name,
success_url=success_url, extra_context=extra_context)
Url:
url(r'^edit/$', views.profile_edit, name='userena_profile_edit'),