Django Страница входа - PullRequest
       4

Django Страница входа

0 голосов
/ 10 апреля 2020

Когда я запускаю сервер, все работает, но у меня есть проблема на веб-сайте:

Идея состоит в том, что, когда кто-то нажимает на «логин», пользователь go на странице «логин» и на самом деле он идет на localhost / login, но когда он находится на странице / login, он показывает форму «регистрации», а не страницу «login», которая должна быть файлом login. html. Вместо этого он показывает файл регистра. html. Код кажется правильным, и я несколько раз возвращался к нему, но не вижу ошибки.

account / login. html

{% extends 'base.html'%}

{% block content %}

<h2> Login</h2>
<form method='post'> {% csrf_token%}
    {% for field in login_form %}
    <p>
        {{field.label_tag}}
        {{field}}

        {% if field.help_text %}
        <small style="color: grey;"> {{field.help_text}}</small>
        {% endif %}

        {% for error in field.errors %}
         <p style='color:red;'> {{field.help_text}} </p>
         {% endfor %}

         {% if login_form.non_field_errors %}
             <div style="color: red">
               <p>{{login_form.non_field_errors}}</p>
             </div>

           {% endif %}

</p>
        {% endfor %}
     <button type="submit"> Login </button>
     </form>


{% endblock content %}

account / register. html

{% extends 'base.html'%}

{% block content %}

<h2> Register</h2>
<form method='post'> {% csrf_token%}
    {% for field in registration_form %}
    <p>
        {{field.label_tag}}
        {{field}}

        {% if field.help_text %}
        <small style="color: grey;"> {{field.help_text}}</small>
        {% endif %}

        {% for error in field.errors %}
         <p style='color:red;'> {{field.help_text}} </p>
         {% endfor %}
    </p>
        {% endfor %}
     <button type="submit"> Register </button>
     </form>


{% endblock content %}

account / admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import Account


class AccountAdmin(UserAdmin):
    list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff')
    search_fields = ('email','username',)
    readonly_fields=('date_joined', 'last_login')

    filter_horizontal = ()
    list_filter = ()
    fieldsets = ()


admin.site.register(Account, AccountAdmin)

account / forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm  #CustomUserCreationForm
from django.contrib.auth import authenticate



from account.models import Account


class RegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Required. Add a valid email address.')

    class Meta:
        model = Account
        fields = ('email', 'username', 'password1', 'password2', )


class AccountAuthenticationForm(forms.ModelForm):

    password = forms.CharField(label='Password', widget=forms.PasswordInput)

    class Meta:
        model = Account
        fields = ('email', 'password')

    def clean(self):
        if self.is_valid():
            email = self.cleaned_data['email']
            password = self.cleaned_data['password']
            if not authenticate(email=email, password=password):
                raise forms.ValidationError("Invalid login")

account / models.py

   from django.db import models
    from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

    # Create your models here.

    class MyAccountManager(BaseUserManager):
        def create_user(self, email, username, password=None):
            if not email:
                raise ValueError('Users must have an email address')
            if not username:
                raise ValueError('Users must have a username')

            user = self.model(
                email=self.normalize_email(email),
                username=username,
            )

            user.set_password(password)
            user.save(using=self._db)
            return user

        def create_superuser(self, email, username, password):
            user = self.create_user(
                email=self.normalize_email(email),
                password=password,
                username=username,
            )
            user.is_admin = True
            user.is_staff = True
            user.is_superuser = True
            user.save(using=self._db)
            return user


    class Account(AbstractBaseUser):
        email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
        username                = models.CharField(max_length=30, unique=True)
        date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
        last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
        is_admin                = models.BooleanField(default=False)
        is_active               = models.BooleanField(default=True)
        is_staff                = models.BooleanField(default=False)
        is_superuser            = models.BooleanField(default=False)


        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['username']

        objects = MyAccountManager()

        def __str__(self):
            return self.email


        def has_perm(self, perm, obj=None):
            return self.is_admin


        def has_module_perms(self, app_label):
            return True

account /urls.py

  from django.conf.urls import url,include
    from django.contrib import admin
    from . import views



    urlpatterns = [
        url(r'^', views.registration_view, name = 'register'),
        url(r'^', views.logout_view, name = 'logout'),
        url(r'^', views.login_view, name = 'login'),

    ]

account / views.py

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from account.forms import RegistrationForm


def registration_view(request):
    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)
            return redirect('/quiz')
        else:
            context['registration_form'] = form

    else:
        form = RegistrationForm()
        context['registration_form'] = form
    return render(request, 'account/register.html', context)


def logout_view(request):
    logout(request)
    return redirect('/quiz')


def login_view(request):

    context = {}

    user = request.user
    if user.is_authenticated:
        return redirect("/quiz")

    if request.POST:
        form = AccountAuthenticationForm(request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(email=email, password=password)

            if user:
                login(request, user)
                return redirect("/quiz")

    else:
        form = AccountAuthenticationForm()

    context['login_form'] = form

    # print(form)
    return render(request, "account/login.html", context)

викторина / база. html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{% block title %} {% endblock %}</title>

    {% if request.user.is_authenticated%}
    <p> <a href="{% url 'logout'%}">Logout</a></p>

    {% else %}
    <p> <a href="{% url 'login'%}">Login</a></p>

    {% endif %}


    {% load static %}
    <link rel="stylesheet" href="{% static 'Bootstrap/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'mystyle.css' %}">
    <link rel="stylesheet" href="{% static 'style.css' %}">
    <script type="text/js" src = "{% static 'Bootstrap/js/bootstrap.min.js'%}">

    </script>






  </head>
  <body>



    <nav class="navbar navbar-default">
     <div class="container">
       <div class="navbar-header">
         <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
           <span class="sr-only">Toggle navigation</span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
         </button>
         <a class="navbar-brand" href="/quiz">Quiz</a>
       </div>
       <div id="navbar" class="collapse navbar-collapse">
         <ul class="nav navbar-nav navbar-right">

           <li><a href="/quiz">Home</a></li>
           <li><a href="/quiz/quizz">Jobs</a></li>
                <li><a href="/quiz/about">ExploreCareers</a></li>
           <!-- <li><a href="/quiz/contact">Contact</a></li> -->
         </ul>
       </div><!--/.nav-collapse -->
     </div>
   </nav>
   <div id="content" class = "container">
  <!-- <img src='{%static "img/robot.jpg"%}' -->



      {% block content %}

      {% endblock %}

    </div>
    <footer class="footer">
      <div class="container">
     <!-- <p style='font-size:25px' > MIBE THESIS 2020  </p> -->
      <p class='ok' > MIBE THESIS 2020 / MATTIA MINAFO'  </p>
      <style>
      .ok{
          font-size: 20px;
          font-family: ;
      }
      </style>
      </div>
    </footer>
  </body>

</html>

quizapp / urls.py

"""quizapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from django.views.generic import RedirectView
from account.views import registration_view,login_view,logout_view



urlpatterns = [
    url(r'^$', include('quiz.urls')),
    url(r'^quiz/', include('quiz.urls')),
    url(r'^register/', include('account.urls')),
    url(r'^logout/', include('account.urls')),
    url(r'^login/', include('account.urls')),
    url(r'^admin/', admin.site.urls),


]

1 Ответ

0 голосов
/ 10 апреля 2020

Ваш account/urls.py имеет проблему. любой запрошенный URL будет обслуживаться registration_view, поскольку он находится в верхней части списка URL. исправление

 urlpatterns = [
        url(r'^register/', views.registration_view, name = 'register'),
        url(r'^logout/', views.logout_view, name = 'logout'),
        url(r'^login/', views.login_view, name = 'login'),
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...