django - how to reach username which is in url - regex

i have blog system which is every user have their own main page like ;
127.0.0.1/username
and every user's login screen located at : 127.0.0.1/username/panel
and again here is their admin panel : 127.0.0.1/username/admin
in login page ; when i submit ; it must redirect the user to admin panel.
but i need to reach the username which is in url at the moment. i think i shoud use regexp. but how? i am bad about regexp.
here is my urls.py:
urlpatterns = patterns('blog.views',
url(r'^blog/(?P<username>[-\w]+)/$',view='index', name='index'),
url(r'^blog/(?P<username>[-\w]+)/post/(?P<postslug>[-\w]+)',view='singlePost', name='view_blog_post'),
url(r'^blog/(?P<username>[-\w]+)/panel/$', view='loguserin'),
url(r'^blog/(?P<username>[-\w]+)/admin/$', view='adminView', name='admin'),
url(r'^blog/(?P<username>[-\w]+)/admin/loggedout/$', view='logout', name='logout'),
url(r'^blog/(?P<username>[-\w]+)/admin/addpost/$', view='addpost',name='addpost'),
url(r'^blog/(?P<username>[-\w]+)/admin/editpost/(?P<post_id>\d+)', view='editPost', name='editpost'),
url(r'^blog/(?P<username>[-\w]+)/admin/delete/(?P<post_id>\d+)', view='delete_post', name='deletePost'),
)
and here is my views.py [login part]:
def loguserin(request,username):
if request.method=='POST':
uname = request.POST['username']
password = request.POST['password']
user = authenticate(username=uname, password=password)
form = LoginForm(request.POST)
if form.is_valid():
if user is not None:
request.session['loggedin']="djangoo"
login(request, user)
return HttpResponseRedirect('/admin/') #--> ????
else:
form = LoginForm()
return render_to_response('login.html',{'form':form,},context_instance=RequestContext(request))

Actually, you already have the username:
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('admin', args=[uname]))

What you need is reverse with parameters:
from django.core.urlresolvers import reverse
def loguserin(request,username):
if request.method=='POST':
uname = request.POST['username']
password = request.POST['password']
user = authenticate(username=uname, password=password)
form = LoginForm(request.POST)
if form.is_valid():
if user is not None:
request.session['loggedin']="djangoo"
login(request, user)
return HttpResponseRedirect(reverse('admin', args=[uname])) #--> ????
else:
form = LoginForm()
return render_to_response('login.html',{'form':form,},context_instance=RequestContext(request))

Related

Django User Register, auto login & redirect

I collect two forms at signup - a register form and a user profile form.
The form submission works alright - I get to see the new user and their profile on the admin panel. The problem would be automatically logging them in and redirecting them to a specific page doesn't seem to work.
This is what my views.py file look like:
def registerView(request):
regForm = RegisterForm
proForm = UserProfileForm
if request.method == 'POST':
regForm = RegisterForm(request.POST)
proForm = UserProfileForm(request.POST)
if regForm.is_valid() and proForm.is_valid():
user = regForm.save(commit=True)
profile = proForm.save(commit=False)
profile.user = user
profile.save()
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return render (request, 'main/dashboard.html', {})
else:
return HttpResponse("There was a problem signing you up!")
regDic = {'regForm': regForm, 'proForm': proForm}
return render(request, 'person/register.html', context=regDic)
What would be the best way to automatically log in & redirect the registered user upon form submission?
Try using redirect instead of render.
from django.shortcuts import redirect
if user:
if user.is_active:
login(request, user)
return redirect('name of the url you want to redirect')
First use the cleaned_data from the valid form instead of getting the raw values and then instead of render the template redirect to some path after the successful login.
And also the authenticate function should have request as the first parameter.
username = regForm.cleaned_data.get('username')
password = regForm.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('some_path')

Redirect to the page from where user clicked signin after login in django3.0

i want to redirect the user to the page from where he clicked the login instead of home.
login view:
def login_view(request):
context = {}
user = request.user
if user.is_authenticated:
return redirect('home')
if request.POST:
form = AccountAuthenticationForm(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
login(request, user)
return redirect('home')
else:
form = AccountAuthenticationForm()
context['login_form'] = form
return render(request, "account/login.html", context)
You can preserve the the current url & redirect to it by using HTTP_REFERER. You can pass the url name as second parameter where you want to redirect if HTTP_REFERER fails.
from django.shortcuts import redirect
return redirect(request.META.get('HTTP_REFERER', 'secondary_url_name'))

Django.contrib.auth.login is not working after i redirect to a different url

The login function is not working , after i call login , authenticated is set 'true' but after i redirect to 'main' view authenticated is set 'false'. How to keep the user logged in even after redirection?
class LoginForm(forms.Form):
user = forms.CharField()
password = forms.CharField()
def login(self):
try:
cred = users.objects.get(username = user)
if password==cred.password):
return (True, cred)
return (False, 'Invalid Password.')
except:
return (False, 'Not exist')
from django.contrib.auth import login as auth_login
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
valid, message = form.login()
if valid:
auth_login(request, message)
print(request.user.is_authenticated)
# this is not working
return redirect(main)
else:
return redirect(login)
form = LoginForm()
args = {'form': form}
return render(request, 'accounts/login.html', args)
def main(request):
print(request.user.is_authenticated)
You shouldn't write check your user credentials in form class. Do it in your login view. Example:
# views.py
from django.contrib.auth import authenticate, login
from django.urls import reverse
from django.shortcuts import redirect, render
def login_view(request): #changed_the name shouldn't be login
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username, password)
if user:
login(user)
return redirect(reverse("main"))
else:
return redirect(reverse("login"))
form = LoginForm()
args = {"form": form}
return render(request, 'accounts/login.html', args)
# urls.py
urlpatterns = [
path("login/", views.login_view, name="login"), # <-- really important
path("main/", views.main_view, name="main")
]
To summarize - to redirect to another page use redirect function. If you set name parameter in url of you view, you can reffer to this view using reverse. Also don't reinvent the wheel and write your own authentication function. Django provides: authenticate(username, password) and login(user) function.

django customizing user view?

i make customizing user.
so i need to login with email.
user = authenticate(email=email, password=password) seems not working...
help me...
let me know of how to fix my views.py.
here is my view.
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.shortcuts import render
from LanguageExchange.forms import UserCreationForm,UserChangeForm
def index(request):
context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"}
return render(request, 'LanguageExchange/index.html', context=context_dict)
def register(request):
# A boolean value for telling the template
# whether the registration was successful.
# Set to False initially. Code changes value to
# True when registration succeeds.
registered = False
if request.method == 'POST':
user_form = UserCreationForm(data=request.POST)
# change_form = UserChangeForm(data=request.POST)
# if the two forms are valid..
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
#if change_form.is_valid():
# change = change_form.save()
# change.set_password(user.password)
# change.user = user
registered = True
else:
print(user_form.errors)
else:
user_form = UserCreationForm()
# change_form = UserChangeForm()
return render(request,
'LanguageExchange/register.html',
{'user_form': UserCreationForm,
'registered': registered})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(email=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Your Rango account is disabled.")
else:
print("Invalid login details: {0}, {1}".format(email, password))
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'LanguageExchange/login.html', {})
let me know of how to fix my views.py.
delete
user.set_password(user.password)
in register;
change
user = authenticate(email=email, password=password)
to
user = authenticate(username=email, password=password)
in user_login.

Django Creating custom URL for user profile

I have an app which allows users to create a profile and log in.
When a user login , he is redirected to 127.0.0.1:8000/profile/
The problem is , I want to customize the URL by adding the user's username to the end of URL e.g example 127.0.0.1:8000/profile/michael
This is a similar question to mine
Django - after login, redirect user to his custom page --> mysite.com/username
"get the username and then do a HttpResponseRedirect to the custom URL."
I just can't seem to figure out how could I pass a username as an argument for HttpResponseRedirect to process into a the custom URL properly.
return HttpResponseRedirect('/profile/?username=%s' % (username, request.path))
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
person = Person.objects.get(user=request.user)
return render(request,'profile.html',{'person':person})
my URL
url(
r'^profile/$',
'pet.views.Profile',
name = 'Profile'
),
NEW
my views.py
def LoginRequest(request):
if request.user.is_authenticated():
username = User.objects.get(username=request.user)
url = reverse('Profile', kwargs = {'username': username.username})
return HttpResponseRedirect(url)
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
Person = authenticate(username=username, password=password)
if Person is not None:
login(request, Person)
username= User.objects.get(username=request.user)
url = reverse('Profile', kwargs = {'username': username.username})
return HttpResponseRedirect(url)
return render(request, 'login.html',{'form': LoginForm()})
url(
r'^login/$',
'pet.views.LoginRequest',
name = 'LoginRequest'
),
url(
r'^profile/(?P<username>\w+)/$',
'pet.views.Profile',
name = 'Profile'
),
def Profile(request,username):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user__username=username)
return render(request,'profile.html',{'board':board ,'person':person})
This would be the proper regex for your redirect URL, ie. don't modify the one you have.
url(r'^profile/(?P<username>\w+)/$', 'pet.views.myprofileview', name="detail_profile")
And then to pass an argument to the redirect:
url = reverse('detail_profile', kwargs={'username': profile.firstname})
return HttpResponseRedirect(url)
This leads to also having to define a new view:
def myprofileview(request, username):
person = Person.objects.get(user = request.user)
return render(request,'profile.html',{'person':person})
This would eliminate two behaviours in one view, which I find to be very nice!
We do it this way because it's a string that HttpResponseRedirect accepts so we have to build it accordingly.
This will make a redirect to the myprofileview view and "style", if you could call it that, your url /profile/michael/.
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:Profile',
kwargs={'username': request.user.username}))
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
Person = authenticate(username=username, password=password)
if Person is not None:
login(request, Person)
return HttpResponseRedirect(reverse('world:Profile',
kwargs={'username': username}))
return render(request, 'login.html',{'form': LoginForm()})