Форма недействительна при публикации на сервер. Django - PullRequest
0 голосов
/ 06 марта 2020

На мой взгляд, метод запроса опубликован, но форма недействительна. В HTML он уже показывает форму, тогда, когда я нажимаю кнопку отправить запрос, но я не знаю, почему форма недействительна. поправьте меня пожалуйста И это ошибка появляется, когда я наследую модель User. Вот мой исходный код. models.py

class UserAccountManager(BaseUserManager):

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user( email, password, **extra_fields)

    def create_superuser(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

    def get_by_natural_key(self, email):
        return self.get(email=email)

class User(PermissionsMixin,AbstractBaseUser):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=256, blank=True)
    last_name = models.CharField(max_length=256, blank=True)
    # username = models.CharField(max_length=150, blank=True)
    phone = PhoneNumberField(null=True, blank=True, unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=now, editable=False)
    password = models.CharField(blank=False, null=False, editable=True, max_length=100)
    description = models.TextField(null=True, blank=True)
    token = models.UUIDField(default=get_token, editable=False, unique=True)
    objects = UserAccountManager()
    USERNAME_FIELD = "email"

    def save(self, *args, **kwargs):
        self.password = make_password(self.password)
        super(User, self).save(*args, **kwargs)

forms.py

class LoginForm(forms.Form):
    username = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "placeholder" : "Username",                
                "class"       : "form-control form-control-lg"
            }
        ))
    password = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "placeholder" : "Password",                
                "class"       : "form-control form-control-lg"
            }
        ))

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError("You do not have permission to get this page!")
            if not user.check_password(password):
                raise forms.ValidationError("Incorrect Password!")
            if not user.is_active:
                raise forms.ValidationError("This user is not active!")
            return super(LoginForm, self).clean(*args, **kwargs)

views.py

def login_view(request):
    msg = None
    next_page = request.GET.get('next')
    if request.method == "POST":
        form = LoginForm(request.POST or None)
        print(form.is_valid())
        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)
                if next_page=="/dashboard/" and not request.user.is_staff:
                    return redirect("home")
                if next_page is not None:
                    return redirect(next_page)
                else:
                    return redirect("home")
            else:    
                msg = 'Invalid credentials'    
        else:
            msg = 'Error validating the form'    
    else:
        form = LoginForm()
    return render(request, "dashboard/accounts/login.html", {"form": form, "msg" : msg})

login. html

<form role="form" method="post" action="" class="pt-3" id="loginForm">

                      {% csrf_token %} 

                      <div class="form-row">
                        <div class="form-group col-md-6">
                          <label for="feFirstName">Username</label>
                          {{ form.username }}
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="form-group col-md-6">
                          <label for="feEmailAddress">Password</label>
                          {{ form.password }}
                        </div>
                      </div>
                      <button type="button" name="login" class="btn btn-accent" onclick="document.getElementById('loginForm').submit();">Login</button>
                       &nbsp; &nbsp; 
                       Don't have an account? <a href={% url 'accounts:register' %} class="text-primary">Register</a>
                    </form>

Спасибо заранее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...