authenticate a user in django pybb app - python

I have successfully installed pybb app and all is good except the fact that I don't how to 'tell' pybb app that a user has been authenticated by my main app. I'm using function based views and the normal authenticate -> login routine as described in the django documentation.
My authentication function looks like this:
def index_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user_name = form.cleaned_data['username']
password = form.cleaned_data['password']
person = authenticate(username=user_name, password=password)
if person is not None:
login(request, person)
if request.user.is_authenticated:
return HttpResponseRedirect("/forum")
form = LoginForm()
return render(request, 'index.html', {'loginform': form})
And my main urls.py has this included as per directed in the pybb documentation
url(r'^forum/', include('pybb.urls', namespace='pybb'))
I can verify that a user has been authenticated before I do the HttpResponseRedirect("/forum") but that seems to get lost once the pybb app is loaded . I just don't know where I should start looking into. Any help is greatly appreciated.
Thanks

Related

Is it possible to feed data from a React POST request into a Django form without rendering that form on the frontend?

I am working on a basic login form for a hybrid React/Django web app. I would like to use the built in data-cleaning and validating methods of the Django Form models, but our frontend is pure React. Everything works as far as logging in, but I am feeding the raw body data into the authenticate function as shown here.
def login_view(request):
if request.method == "POST":
form_data = json.loads(request.body.decode('utf-8'))
user = authenticate(request, email=form_data["username"], password=form_data["password"])
if user == None:
request.session["invalid_user"] = 1
logging.warning("Login form contains no user")
login(request, user)
My question is, is there any way to feed this form_data into the Django native LoginForm when I instantiate it? I would prefer to not recode all of the input validation that Django does already.
I've tried instantiating a LoginForm like so:
form = LoginForm(data=form_data)
And then tried running form.full_clean(), but it doesn't seem to work. Any help would be greatly appreciated, thank you!
The issue was actually a difference in the variable names between the rendered React form and the Django LoginForm I had defined. One was username and password, the other email and password. With that in mind the usual way of working with forms works great!
if request.method == "POST":
form_data = json.loads(request.body.decode('utf-8'))
form = LoginForm(data=form_data)
if form.is_valid():
email = form.cleaned_data["email"]
password = form.cleaned_data["password"]
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)

Why do we need to login user in signup_view an login_view function? Django

So I need a theoretical answer here, not practical, I've been following this tutorial on Django anf everything seems quite understandable, but I'm not sure about one thing, so here are the views for signup page and login page:
def signup_view(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
#log the user in
login(request, user)
return redirect("articles:list")
else:
form = UserCreationForm()
return render(request, 'account/signup.html', {"form": form})
def login_view(request):
if request.method == "POST":
form = AuthenticationForm(data = request.POST)
if form.is_valid():
#log in the user
user = form.get_user()
login(request, user)
return redirect('articles:list')
else:
form = AuthenticationForm()
return render(request, "account/login.html", {"form":form})
So my question is, why do I need to write login(request, user) twice, isn't the signup function saving the user in database and log in function simply logging it in?
In the code, for post request and valid forms, the response is always a redirect to articles:list page.
If we assume the view articles:list as login required, users need to have an active session in order to view the page.
In the login_view function after authenticate is quite obvious that next step is to log the user in and redirect to articles:list
In the signup_view the logic might be, add user to database and redirect to articles:list, but since articles:list is login required, we need to log the user in.
Maybe that's the way they thought the logic for the example, it all depends on what you need since is not a rule to log the user in after register.

Django can't identify the user after registering an account *AnonymousUser*

So the goal is for a new user to register an account and then get redirected to the home page and recognized. So that the user does not have to register for their account then go through the process of logging in right after. I want a standard registration, like Instagram, Twitter, and other professional applications.
So far, I'm where the user can register and redirect them to the homepage, but when I try to print their name on the screen, I get AnonymousUser. The user's information is written to the database after registering, but Django doesn't know who the user is. For Django to know who is logged in after registering, they have to log out and then log in right after registering their account. If anyone could help, I would be much appreciated it.
Views.py
from django.shortcuts import render, redirect
from .forms import RegisterForm
from django.contrib import messages
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/")
else:
form = RegisterForm()
return render(response, "register/register.html", {"form": form})
Using the authenticate() and login() functions:
from django.contrib.auth import authenticate, login
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
messages.info(request, "Thanks for registering. You are now logged in.")
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
)
login(request, new_user)
return HttpResponseRedirect("/dashboard/")
originally answered
after successful registration POST REQUEST explicitly log in the users using the login method and you can access the name of the user without having the user to login again...

Django - Custom Login Page on index

I'm using Django and I'm creating an backend web application. Is it possible to create the URLs and functions for the login page but on index?
Without using default Django auth framework for authentication/login. I'm just about to write the function for this, but I have got no idea if it will work. I have also looked at other tutorials but I do tend to find these are out of date.
What I want is once the application loads, the user is prompted with a login box, once they login their details, then they are re-directed to the custom dashboard area (without using the built in Django).
Urls.py File
path('', auth_views.LoginView.as_view(template_name='index.html')),
Views.py File
#login_required
def index(request, user):
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user, 'index.html')
return HttpResponseRedirect ('dashboard.html')
In short, I wanted to know if it was possible to overwrite the custom Django 'accounts/login' part. It is possible, but alot of tweaking is needed and making sure that everythings correct.
I can only hope that this helps others in the future.
Urls.py
path('', LoginView.as_view(template_name='index.html'), name="login"),
Views.py
#login_required
def index(request):
return render(request, 'index.html')
def login(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return render(request, 'admin/dashboard.html')
def dashboard(request):
return render(request, 'admin/dashboard.html')
Settings.py
LOGIN_REDIRECT_URL = '/admin/dashboard'
I still have a few more features to implement but I hope this helps others.

How to use django UserCreationForm correctly

I am new to Django and am just starting my first website. I am trying to set registration for new users.
I used the built in view for login and logout but there is none for registration, in the doc, it says that I should use built in form : UserCreationForm.
The code of my view is :
def register(request):
if request.method =='POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(form.cleaned_data['username'], None, form.cleaned_data['password1'])
user.save()
return render_to_response('QCM/index.html') # Redirect after POST
else:
form = UserCreationForm() # An unbound form
return render_to_response('register.html', {
'form': form,
},context_instance=RequestContext(request))
It works fine but I am not satisfied as this code is written in the views.py that handles the core of my application (multiple choice question).
My questions are :
Is this the correct way of using the UserCreationForm
Where could I put this code so it would be separated from the rest of
my app
Thank you for your answers.
Django is modular, so you can write a separate accounts or user management app that can handle user creation, management.
In that case, you put the code for register in the views.py of accounts app.
You can directly save the UserCreationForm which will give you user object.
example:
...
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
...

Categories