Django логин (запрос, пользователь) не вернуть - PullRequest
0 голосов
/ 16 июня 2020

Когда я отправляю действительное имя пользователя и пароль с формой входа, он перенаправляется на ту же страницу со следующим URL-адресом и пользователем, не вошедшим в систему. Я понятия не имею, почему это происходит. :(

Код Views.py

def sign_in(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            if form.user_cache is not None:
                user = form.user_cache
                if user.is_active:
                    login(request, user)
                    next_url = request.GET.get('next')
                    if next_url:
                        return HttpResponseRedirect(next_url)
                    return HttpResponseRedirect('/user_dashboard_url/')
            else:
                messages.add_message(
                    request, messages.ERROR,
                    "Username or password is incorrect."
                )

    return render(request, 'sign_in.html', {'form': form})

HTML Форма

{% load crispy_forms_tags %}
                <form method="POST" class="form"> 
                    {% crispy form %}
                    <div class="form-action mb-3">
                        <input type="submit" name="submit" value="Sign In" class="btn btn-primary btn-rounded btn-login">
                    </div>
                </form>

Ответы [ 3 ]

0 голосов
/ 16 июня 2020
delete this:
if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            if form.user_cache is not None:
                user = form.user_cache
                if user.is_active:
                    login(request, user)
                    next_url = request.GET.get('next')
                    if next_url:
                        return HttpResponseRedirect(next_url)
                    return HttpResponseRedirect('/user_dashboard_url/')

replace with:
if request.method == 'POST':
            form = AuthenticationForm(data=request.POST)
            if form.is_valid() and form.user_cache is not None:
                user = form.user_cache
                if user.is_active:
                     login(request, user)
                     return HttpResponseRedirect(reverse('appname:viewname'))

убедитесь, что вы включили urls.py в свое приложение, включите в него app_name и сделайте URL-адрес для вашего представления, чтобы он выглядел примерно так:

    from django.urls import path
    from . import views
    app_name = 'finance'
urlpatterns = [
    path('user_dashboard_url/', views.dashboard, name='dashboard'),]

    reverse would be: reverse('finance:dashboard'), given the example of the urls.py

    add to your view:

    @login_required < this wil make sure that if a user is not valid its not possible to use this view ;)
    def view_name(request):
          blablablabla

>

     btw, go and use the django authentication that wil save you alot of headache.
>     [https://docs.djangoproject.com/en/3.0/topics/auth/default/][1]


  [1]: https://docs.djangoproject.com/en/3.0/topics/auth/default/
0 голосов
/ 10 июля 2020

Вы должны передать request на AuthenticationForm(). То есть используйте AuthenticationForm(request=request, data=request.POST).

0 голосов
/ 16 июня 2020

проверьте метод ниже. В нем не используются встроенные формы django. Он имеет отдельный html для. Проверьте изображения ниже.

https://i.stack.imgur.com/RnLu5.jpg https://i.stack.imgur.com/4C3eT.jpg

...