Задать вопрос
Entropie
@Entropie

Почему не работает login() в Django?

Авторизация работает только для админа (и обычная, и через админку). Для любого другого пользователя, для которого точно прошла регистрация, не находится соответствий пароля и логина, хотя они точно правильные Авторизация стандартная (функция login)
urls.py
from .views import *
from django.contrib import admin
from django.contrib.auth.views import logout, login
from django.contrib.auth.decorators import login_required

urlpatterns = [
    url(r'^$', home, name = 'main'),
    url(r'^users/$', UserList.as_view(), name = 'users'),
    url(r'^users/user/(?P<slug>\w+)/', AccountView.as_view(), name = 'user'),
    url(r'^blogs/blog/(?P<slug>\w+)/', BlogView.as_view(), name = 'blog'),
    url(r'^login/', login, {'template_name':'login.html'}, name = 'login'),
    url(r'^logout/', login_required(logout), {'template_name': 'logout.html'}, name = 'logout'),
    url(r'^registration/', register, name = 'registration'),
]

forms.py
# *-* coding:utf-8 *-*
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User

class RegisterForm(UserCreationForm):

    class Meta:
        model = User
        fields = ('username',
                    'email',)


    def save(self, commit = True):
        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

views.py
# *-* coding: utf-8 *-*
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.views import login
from django.shortcuts import render, render_to_response
from django.shortcuts import HttpResponse, HttpResponseRedirect, reverse, redirect
from django.template import RequestContext
from django.views.generic import DetailView, ListView
from django.views.generic.edit import FormView,CreateView
from .models import User, UserManager
from .forms import RegisterForm

# Create your views here.
class AccountView(DetailView):
    model = User
    template_name = "users/account.html"
    context_object_name = 'user'
    slug_field = 'username'


class UserList(ListView):
    template_name = "users/user_list.html"
    context_object_name = 'users'
    model = User

class BlogView(DetailView):
    template_name = "users/blog.html"
    context_object_name = 'blog'
    model = User
    slug_field = 'username'

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = User(username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email'])
            user.save()
            us = authenticate(username = user.username, password = user.password)  
            login(request, us)
            return HttpResponseRedirect('/')
    form = RegisterForm()
    return render(request, 'registration.html',{'form':form}) 

def home(request):
    return render(request, 'main.html')
  • Вопрос задан
  • 2624 просмотра
Подписаться 3 Простой 2 комментария
Решения вопроса 1
gordon_shamway
@gordon_shamway
#forms
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)


class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username',  'email')

    def clean_password2(self):
        cd = self.cleaned_data
        if cd['password'] != cd['password2']:
            raise forms.ValidationError('Passwords don\'t match.')
        return cd['password2']

#views
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'], password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('/blog/')
                else:
                    return render(request,
                          'account/disabled_password.html')
            else:
                return render(request,
                          'account/disabled_password.html')
    else:
        form = LoginForm()
    return render(request, 'account/login.html', {'form': form})


def register(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)

        if user_form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = user_form.save(commit=False)
            # Set the chosen password
            new_user.set_password(user_form.cleaned_data['password'])
            # Save the User object
            new_user.save()
        
           
            return redirect('/account/login/')
    else:
        user_form = UserRegistrationForm()
    return render(request, 'account/register.html', {'user_form': user_form})

Простой пример регистрации и входа
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы