Django не принимает действительные учетные данные - PullRequest
0 голосов
/ 25 февраля 2020

views.py. Мой шаблон входа пользователя по умолчанию, я попробовал оба метода, перечисленных ниже, и не знаю, где я делаю ошибку - я получаю сообщение об ошибке, что мои учетные данные неверны каждый раз

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.profile.university = form.cleaned_data.get('university')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            #user_login(request, user)
            return redirect('main:main_page')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

def user_login(request):
    '''
    Using different method for getting username, tried this and didn't work either
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:              
                login(request,user)
                messages.info(request, "Successfully signed in")
                return redirect('main:home')
            else:
                message = 'Sorry, the username or password you entered is not valid please try again.'
                return render(request, 'login.html', {'message':message})
        else:
            message = 'Invalid'
            return render(request, 'login.html', {'message':message})
    else:
        form=AuthenticationForm()
        return render(request, 'login.html', {"form":form})
    '''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account was inactive.")
        else:
                message = 'Sorry, the username or password you entered is not valid please try again.'
                return render(request, 'login.html', {'message':message})
    else:
        message = 'Request failed please try again.'
        return render(request, 'login.html', {'message':message})

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    email = models.EmailField(max_length=150)
    bio = models.TextField()
    university = models.CharField(max_length=30)


    def __str__(self):
        return self.user.username

    @receiver(post_save, sender=User)
    def update_profile_signal(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

forms.py

class SignUpForm(UserCreationForm):
    university = forms.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email','university', 'password1', 'password2',)

app urls.py

app_name = 'main'

urlpatterns=[
    path('signup/',views.signup,name='signup'),
    path('user_login/',views.user_login,name='user_login'),
    path('main_page/',views.main_page,name='main_page'),
]

логин. html форма

<form method="POST" action="{% url 'main:user_login' %}/" class="form-signin">
                {%csrf_token%}
                <div class="form-label-group">
                  <input type="text" name="username" id="inputText" class="form-control" placeholder="Username" required autofocus>
                  <br/>
                </div>
                <div class="form-label-group">
                  <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>

                </div>

                <div class="custom-control custom-checkbox mb-3">
                  <input type="checkbox" class="custom-control-input" id="customCheck1">
                  <label class="custom-control-label" for="customCheck1">Remember password</label>
                </div>
                <input type="submit" class="form-control" name="" value="Login">
                <hr class="my-4">
                <p>Don't have account? <a href="{% url 'main:signup' %}" id="signup">Sign up here</a></p>
                {% if message %}<p style="color: red;">{{message}}</p>{% endif %}
                <a href="{% url 'password_reset' %}" id="signup">Forgot Password</a>
              </form>

Я не могу понять, почему мой Django не принимает правильные учетные данные. Какая часть моего кода кажется неправильной?

1 Ответ

0 голосов
/ 25 февраля 2020

убедитесь, что вы выбрали правильную модель пользователя для django настроек, добавьте

# AUTH_USER_MODEL = 'YOUR_APP_NAME.YOUR_CUSTOM_USER_MODEL'

к вашим django настройкам. Like # AUTH_USER_MODEL = 'users.User'

и вам нужно написать абстрактная модель пользователя.

from django.contrib.auth.models import AbstractUser
class RightsSupport(models.Model):
    class Meta:

        managed = False  # No database table creation or deletion  \
        # operations will be performed for this model.

        permissions = (

            ("add_user", "Can Create User"),
            ("view_user", "Can View Single User"),
            ("change_user", "Can Change User"),
            ("list_user", "Can View User List"),

            ("add_plan", "Can Create Plan"),
            ("view_plan", "Can View Single Plan"),
            ("change_plan", "Can Change Plan"),
            ("list_plan", "Can View Plan List"),
  )


class User(AbstractUser):
    CREATED = 0
    ACTIVE = 1
    BANNED = 2
    KICKED = 3
    UPGRADE = 4
    STS = (
        (CREATED, 'Just Created'),
        (ACTIVE, 'Activated'),
        (BANNED, 'Disabled'),
        (KICKED, 'Disabled'),
        (UPGRADE, 'Active'),
     )
    status = models.IntegerField(choices=STS, default=CREATED, blank=True, null=True)
    def __str__(self):
        return self.username

также обновите ваше мнение, в этом коде есть огромная ошибка. Вы забыли закрыть строку документации.

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.profile.university = form.cleaned_data.get('university')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            #user_login(request, user)
            return redirect('main:main_page')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

def user_login(request):
    '''
    Using different method for getting username, tried this and didnt work either
    '''
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:              
                login(request,user)
                messages.info(request, "Successfully signed in")
                return redirect('main:home')
            else:
                message = 'Sorry, the username or password you entered is not valid please try again.'
                return render(request, 'login.html', {'message':message})
        else:
            message = 'Invalid'
            return render(request, 'login.html', {'message':message})
    else:
        form=AuthenticationForm()
        return render(request, 'login.html', {"form":form})





...