Nice programing

장고 등록 후 자동으로 로그인하는 방법

nicepro 2020. 11. 21. 09:15
반응형

장고 등록 후 자동으로 로그인하는 방법


이것은 현재 등록에 사용하고있는 것입니다.

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. Please login to continue.")
            return HttpResponseRedirect("/dashboard/")
    else:
        form = UserCreationForm()
    return render_to_response("accounts/register.html", {
        'form': form,
    }, context_instance=RequestContext(request))

사용자가 계정을 만든 후 수동으로 로그인하도록 요구하지 않고 단순히 자동으로 로그인하는 것이 가능합니까? 감사.

편집 : 나는 성공하지 않고 login () 함수를 시도했습니다. 문제는 AUTHENTICATION_BACKENDS가 설정되지 않았다는 것입니다.


은 Using authenticate()login()기능 :

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/")

여기에 클래스 기반 뷰의 경우 나를 위해 일한 코드가 있습니다 (원래 Django 1.7, 2.1로 업데이트 됨)

from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.views.generic import FormView

class SignUp(FormView):
    template_name = 'signup.html'
    form_class = UserCreateForm
    success_url='/account'

    def form_valid(self, form):
        #save the new user first
        form.save()
        #get the username and password
        username = self.request.POST['username']
        password = self.request.POST['password1']
        #authenticate user then login
        user = authenticate(username=username, password=password)
        login(self.request, user)
        return HttpResponseRedirect(self.get_success_url)

Django의 UserCreationForm을 하위 클래스로 만들고 commit = True 일 때 로그인하도록 save 메소드를 재정의 할 수 있습니다.

forms.py

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

class CustomUserCreationForm(UserCreationForm):
    """
    A ModelForm for creating a User and logging 
    them in after commiting a save of the form.
    """

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta(UserCreationForm.Meta):
        pass

    def save(self, commit=True):
        user = super().save(commit=commit)
        if commit:
            auth_user = authenticate(
                username=self.cleaned_data['username'], 
                password=self.cleaned_data['password1']
            )
            login(self.request, auth_user)

        return user

양식을 인스턴스화 할 때 요청 객체를 전달했는지 확인하기 만하면됩니다. 뷰의 get_form_kwargs 메소드를 재정 의하여이를 수행 할 수 있습니다.

views.py

def get_form_kwargs(self):
    form_kwargs = super().get_form_kwargs()
    form_kwargs['request'] = self.request
    return form_kwargs

Or, make sure when you instantiate a form_class you do CustomUserCreationForm(data=request.POST, request=self.request).

참고URL : https://stackoverflow.com/questions/3222549/how-to-automatically-login-a-user-after-registration-in-django

반응형