Django temporary view - python

In my Django Project user is redirect to specific template with content:
"Thanks for your registration"
def success_signup(request):
"""Account created with success."""
return render(request, "account/success.html")
when he register new account with success.
I want to make this template/view temporary.
I.E When the user/somebody go to
"account/success.html"
again should be redirected to the homepage instead of the success.html template.
Unfortunately, I can not find this in the documentation. Thanks in advance!

For the first time pass a get variable first_time=yes. Then check if first_time == "yes", Show this page elif request.user.is_authenticated return back to index page else redirect to login page.
url should look like this
localhost:8000/success-signup/?first_time=yes
views.py
def success_signup(request):
first_time = request.GET.get('first_time')
if first_time == "yes":
"""Account created with success."""
return render(request, "account/success.html")
elif request.user.is_authenticated:
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponseRedirect(reverse('signup'))

Related

How to reload the current page when form was sent?

Hey,
after the form was sent the page needs to be automatically reloaded / refreshed. Either just the current page is going to be reloaded or the variable slug_title (which would be part of the current page url) needs to be passed into the (' ') from HttpResponseRedirect.
Do you have any suggestions? I would really appreciate it. :)
views.py
def posts(request, slug_titel):
post = get_object_or_404(Thread, slug_titel=slug_titel)
form = ThreadForm()
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(' ') # <- here I need to put in slug_title from above
You can redirect to a view with variables that way:
from django.shortcuts import redirect
return redirect('some-view-name', slug=slug_titel)
Well if the form is valid, you have access to cleaned_data, from there you can fetch the slug value entered by user:
if form.is_valid:
slug = form.cleaned_data.get(“slug_titel”)
return redirect(“your-view”, slug = slug)

Previous pages display after logout and session deleted

Login code:
def login(request):
if request.method == 'POST':
user = request.POST['uname']
password = request.POST['psw']
log = User.objects.filter(username=user, password=password)
if log:
request.session['login'] = True
return HttpResponseRedirect('/page')
else:
return render(request, 'login.html')
else:
return render(request, 'login.html')
Logout code:
del request.session['login']
request.session.modified = True
return HttpResponseRedirect("/")
After logout when I move back I am able to see the previous pages but as soon as I refresh the page it redirects me to login page and restricts me to access previous page.
def page(request):
if not request.session.get('login', False):
return HttpResponseRedirect("/tnp_admin/")
else:
#access page
How to not display previous pages after logout and why is session working only after refreshing page?
You can either use if user.is_authenticated in the view or import login_required property from django.contrib.auth.decorators and put #login_required on top of your view for that template.

Redirect not able to send response

I'm using redirect in Django to send the user to another page but it is not able to do so.
views.py
def func1(request):
if not request.user.is_authenticated():
return render(request, 'login/login/login.html')
else:
if request.method == "POST":
return redirect('base:func2')
return render(request, 'base/home/index.html')
def func2(request):
if not request.user.is_authenticated():
return render(request, 'login/login/login.html')
else:
if request.method == "POST":
....
return render(request,
'bla_bla_bla.html',
{'location': location})
elif request.method == 'GET':
print('COntrol is here')
some_details_form = SomeDetailsForm()
return render(request, 'some_url/index.html',
{'some_details_form': some_details_form})
urls.py
app_name = 'base'
url(r'^another_url/$', views.func2, name='func2'),
url(r'^some_url/$', views.func1, name='func1'),
base/home/index.html
<div class="button" onclick="clicked_it()">
<span id="forward"> Go Further </span>
</div>
index.js
function clicked_it()
{
$.post( "/base/some_url/");
};
So the control does go to func2 since I can see the print statement output COntrol is here but I don't see that the func2 is able to render the page in the return statement. Where is the control getting stuck?
The whole point of using Ajax is that it overrides the browser navigation handling. If you want your Ajax to redirect, you need to do it in js - or, don't use Ajax at all.
redirect either needs the relative or absolute url that you need to redirect to.
You need to use django reverse url resolver
from django.core.urlresolvers import reverse
def func1(request):
if not request.user.is_authenticated():
return render(request, 'login/login/login.html')
else:
if request.method == "POST":
return redirect(reverse('base:func2'))
return render(request, 'base/home/index.html')

Moving Between Pages

I am trying to move from a web page to another when the user submits a POST.
The problem is that the url doesn't change when I submit the POST and the view function that corresponds to the new page doesn't fire but the template loads and it show only the inputs I hard coded inside it without those I pass in the view function of course.
The Code:
In the urls file:
url(r'^addcross/phase1', views.new_cross_phase_1, name='new_cross_phase_1'),
url(r'^addcross/phase2', views.new_cross_phase_2, name='new_cross_phase_2'),
The view function of the 1st page:
def new_cross_phase_1(request):
if request.method == 'POST':
# my code here
return render_to_response('New/New_Cross_Phase_2.html', {'crosses_names': crosses_names, 'creation_methods' : creation_methods},
context_instance=RequestContext(request))
The view function of the 2nd page:
def new_cross_phase_2(request):
print('Phase 2')
if request.method == "GET":
return render_to_response('New/New_Cross_Phase_2.html', {'cross_form': new_cross_form},
context_instance=RequestContext(request))
You should be redirecting in view 1, not rendering the template from view 2.
return redirect('new_cross_phase_2')

Django - login required for POST but not GET?

So I'm trying to do a site with user editable tags on items. I want users to be able to edit tags on the page only if they are logged in, but everyone should be able to view the page. The edits are done through a modelform. I can't use the login_required decorator on the whole view because then only authenticated users would be able to see the page at all, which is not what I want. The edit element will be a little slide out dongle that will be done with AJAX later on, is there any way to make sure if a user is logged in if they click the edit button?
What my view looks like for the page:
def show_gallery(request, gallery_id):
gallery = get_object_or_404(Gallery, id=gallery_id)
print gallery.name
if request.method == 'POST':
form = GalleryEditForm(request.POST, instance=gallery)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
print "invalid"
else:
form = GalleryEditForm(instance=gallery)
return render(request, "gallerypage.html", {
'gallery': gallery,
'tags': gallery.misc_tags.names(),
'form': form
})
Thanks.
You can use is_authenticated property of user in template in this way by making field readonly:
{% if user.is_authenticated %}
fields
{% else %}
read only value
{% endif %}
OR
replace a code in view
if request.method == 'POST' and request.user.is_authenticated():
I believe this can help solve this issue. Also check django.sessions documentation.
if request.user.is_authenticated(): ...
required settings.py:
INSTALLED_APPS = [
...
'django.contrib.sessions',
...
]
MIDDLEWARE_CLASSES = [
...
# middleware attaches user object to request
'django.contrib.sessions.middleware.SessionMiddleware'
...
]
I write this here because i'm not able to post comments yet.
In newer versions of Django, you have to use is_authenticated without the parentheses (at least when doing this on a view):
if request.user.is_authenticated:
# Do something for authenticated users.
...
else:
# Do something for anonymous users.

Categories