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.
Related
I've searched up but nothing seams to do the trick or be on point.
Let's say i have two websites on page A.html I have a filter (djnago_filter) and B.html is empty. If the user submits the search form he is redirected from page A.html to page B.html where the results are displayed with for loop.
How do I to that?
I was thinking about passing the data from query set to another view but there must be better solution to this.
There are several ways to store and display information on the different views(pages):
You could use the Sessions:
#views.py
#set the session key in the view A:
request.session['info'] = {'key', 'value'}
#get the session key in the view B:
info = request.session['info']
del request.session['info']
You could use Models with JSONField:
#app/models.py
#model to store information from page A
from django.contrib.auth.models import User
class MyModel(models.Model):
user = models.ForeignKey(User,
on_delete=models.DELETE,
related_name="info")
info = models.JSONField()
#views.py
#store data in the view A:
from app.models import MyModel
MyModel.objects.create(user=request.user, info={'key', 'value'})
#retrieve data in the view B:
info = MyModel.objects.get(user=request.user)
But actually, all depends on the logic that you intent to achieve. There are actually other methods like using async Ajax, React, WebSockets...
you can pass it as an HTML request parameter inside the url, for example, in your pageA template will be
to page B
and inside pageb view, you can take the filter from the request object
def page_b_view(request):
some_filter = request.GET.get('some_filter')
After I login, I need to redirect to another page while adding URL parameters to the URL of the next page. I get the value of these parameters after the user is authenticated because they need to be accessed from the user database table. I heard about using the next parameter but I don't know how I would use it since I need to access the database table and I can't do that from urls.py. This is my url.py line for login right now:
url(r'^$',auth_views.login, name='login',kwargs={
'authentication_form':loginPlaceHolderForm,
}),
I'm not really sure what other info you need so just ask for it in the comments and I'll be sure to add it.
Also I'm using Django 1.11
EDIT:
For more clarification: What I want is something like this /colors?team=blue
And let's say the team can be red, blue or green and you get this value from the team column in the given row that you get when the user logs in.
You could try to override djangos class-based view LoginView.
In views.py
from django.contrib.auth.views import LoginView
class MyLoginView(LoginView):
authentication_form = loginPlaceHolderForm
def get_redirect_url(self):
print(self.request.user)
# get data for user here
user_data_query_string = ''
url = '{}?{}'.format(
reverse('app:some-name')
user_data_query_string)
return url
In urls.py
url(r'^$', MyLoginView.as_view(), name='login'),
See also this question about adding GET querystring parameters to djangos HttpRedirect.
I am making a simple code editor. Each user is allocated a six character long id which needs to be appended to the URL. So, if some accesses the page on localhost:8000/myapp/, the URL needs to change to localhost:8000/myapp/<token>.
I am using the following function to generate that token key -
def id_generator(self,size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
I have created a middleware but I am confused how to proceed further. What should I use - process_request() or process_response()?
And how show I define either of them, so that URL changes but functionality remains the same.
If I am right :
Write a view for localhost:8000/myapp/ In this view generate your token and then redirect it to new url from the view .
def mytoken(request):
token = '0-wedfbdhfgm'
return redirect(localhost:8000/myapp/token='+token)
This is a two-step process. You need to create
a view with a matching url to retrieve your individual token
a view with a matching named url to provide the result to the user
urls.py
...
url(r'^myapp/(?P<token>\w+)/$', views.your_user_result_view, name='your-user-result-view'),
url(r'^myapp/$', views.your_token_appender_view, name='your-token-appender-view'),
...
views.py
...
def your_user_result_view(request):
...
def your_token_appender_view(request):
token = ...
redirect(reverse('your-user-result-view',kwargs={'token':token}))
...
If I send a link to a Django page which has #args in the URL, e.g.
http://localhost/someurl/?arg1=true&arg2=false#1970-01-01/2038-01-01/something_else
Then the person is not logged in - the login form appears. Unfortunately after successful login, it will redirect the person to:
http://localhost/someurl/?arg1=true&arg2=false
What I would like to keep somehow is also the #1970-01-01/2038-01-01/something_else
How can I do that in Django?
I would try modifying the code responsible for generating the link such that the # symbol is replaced by %23 (i.e. its percent encoding: https://en.wikipedia.org/wiki/Percent-encoding ).
The final URL would be:
http://localhost/someurl/?arg1=true&arg2=false%231970-01-01/2038-01-01/something_else
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.