首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >DJANGO登录//输入字段不工作//错误消息不显示

DJANGO登录//输入字段不工作//错误消息不显示
EN

Stack Overflow用户
提问于 2018-05-31 23:10:50
回答 2查看 1.1K关注 0票数 1

*听我说完,我知道这听起来有点长,我讨厌听起来像这样,但我已经4天没有睡觉了,这是我应该上学的项目的一部分,所以我真的很感激在这个<代码>E29上任何输入*

你好,我是Django的新手,但尽管如此,我一直在youtube和Django文档上跳来跳去,试图弥补这一点。我已经创建了polls应用程序,也在创建其他几个应用程序,但两次当我几乎完成时,它们都变成了空白,我不得不从头开始。在这一点上,我已经厌倦了Django,但我愿意继续,因为我真的讨厌放弃。

无论如何,这不是这个问题的内容(尽管如果你能帮助我的应用程序重新启动和运行,那就太好了!)我将在下面放一个链接)。

在我最近的应用程序崩溃后,我试图学习如何做一个登录页面。我启动了另一个名为accounts的应用程序,它将专门用于登录/注销/注册。然而,到目前为止,事情并没有很好地发展。

我开始在youtube上学习一个教程,但后来有一大堆我无法摆脱的错误,不得不处理缩进和其他东西。所以我用另一个教程开始了我的应用程序,这个教程就在这里:https://www.youtube.com/watch?v=BIgVhBBm6zI

我试着忽略这段视频的错误(我的输入字段没有显示),并尝试进入下一个错误,这是登录页面背后的逻辑。然而,我知道还有一个错误。现在,错误消息不起作用,每当我单击submit时,什么都不会发生。页面基本上就会刷新。我知道我还没有深入到注册部分,这将允许我实际登录,但我预计会有某种错误消息告诉我,我没有帐户或其他什么。

对于我的输入域,我已经尝试了几种方法(包括这个post),但都不起作用。唯一可以远程实现的是,要么手动将字段放入Html (我知道我不应该这样做),要么将form.html链接到表单模板,该模板只检查用户是否在字段中输入内容(这也不起作用)。

这是我的代码的样子,如果你还在阅读这篇文章,非常感谢你到目前为止对我的容忍。(还请注意,注释掉的部分是我以前尝试过的东西)

views.py

    from django.contrib.auth import (
    authenticate,
    get_user_model,
    login,
    logout,

    )
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .forms import UserLoginForm

# Create your views here.
def login_view(request):
    title = "Login"
    form = UserLoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get('password')

    return render(request, "accounts/form.html", {"form":form, "title": title})


# def authentication(request):
#     if request.method == 'POST':
#         title = "Login"
#         form = UserLoginForm(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 HttpResponse('Authenticated ' \
#                      #       'successfully')
#                     return HttpResponseRedirect('accounts/home.html/')
#             else:
#                 return HttpResponse('Disabled account')

#         else:
#             return HttpResponse('Invalid login')
#     else:
#         form = UserLoginForm()

#     return render(request, 'accounts/form.html', {'form': form})



def register_view(request):
    return render(request,"accounts/form.html",{})

def logout_view(request):
    return render(request,"accounts/form.html",{})

forms.py

from django import forms
from django.contrib.auth import (
    authenticate,
    get_user_model,
    login,
    logout,

    )

User = get_user_model()

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput) 

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

    def clean(self,*args,**kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        user = authenticate(username=username,password=password)
        if not user:
            raise forms.ValidationError("This user does not exist")
        if not user.check_password(password):
            raise forms.ValidationError("Incorrect Password")
        if not user.is_active:
            raise forms.ValidationError("This user is no longer active.")
        return super(UserLoginForm, self).clean(*args,**kwargs)

form.html

{% extends 'accounts/base.html' %}


{% block main_content %}

    <div class="container">
        <h2 class="form-signin-heading">{{ title }}</h2>
        <form method='POST' action='' enctype='multipart/form-data' class="form-signin">
                {% csrf_token %}
                <!--{% include 'accounts/form-template.html' %}-->
                <h2 class="h3 mb-3 font-weight-normal">Please sign in</h2>

                <label for="username" class="sr-only">Username</label>
                <input type="username" id="username" class="form-control" placeholder="Username" required autofocus>
                <label for="inputPassword" class="sr-only">Password</label>
                <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
                <button class="btn btn-lg btn-primary btn-block" type="submit" value="{{ title }}">Sign In</button>
            </form>

    </div>


    <!--<div class='col-sm-6 col-sm-offset-3'>-->
    <!--    <h1>{{ title }}</h1>-->
    <!--    <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}-->
    <!--        <input type='submit' class='btn btn-default' value='{{ title }}' />-->
    <!--    </form>-->
    <!--</div>-->

{% endblock %}

form-template.html

{% for field in form %}

<div class="form-group">
    <div class="col-sm-12">
        <span class="text-danger small">{{ field.errors }}</span>
    </div>
    <label class="control-label col-sm-2">{{ field.label_tag }}</label>
    <div class="col-sm-10">{{ field }}</div>
</div>

{% endfor%}

base.html

{% load staticfiles %}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Accounts</title>
    <link rel="stylesheet" type="text/css" href="{% static 'accounts/bootstrap-3.3.7-dist/css/bootstrap.min.css' %}" />
    <link rel="stylesheet" type="text/css" href="{% static 'accounts/signin.css' %}" />
    <link rel="stylesheet" type="text/css" href="{% static 'accounts/style.css' %}" />
</head>

<body>


    <div class="jumbotron">
        <div class="container">

            {% block main_content %} 
            {% endblock %} 
        </div>
    </div>

</body>

</html>

settings.py (重要比特的小预览)

    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

INSTALLED_APPS = [
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',]

urls.py (适用于我的网站而不是应用程序)

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

from accounts.views import (login_view, register_view, logout_view)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', login_view, name='login'),
    # url(r'^login/', authentication, name='authentication'),
]

我的网站图片:

This what it looks like with the StackOverflow fix from the post I was talking about (yes that's it and the white square is actually button)

This is me manually putting in the fields

This is when I include the form template

如图所示,一切都关闭了,我不想再重新启动,因为根本没有足够的时间,我会导致课程不及格。

已更新基本

{% load staticfiles %}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Accounts</title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{% static 'accounts/signin.css' %}" />
</head>

<body>


    <div class="jumbotron">
        <div class="container">

            {% block main_content %} 
            {% endblock %} 
        </div>
    </div>

</body>

</html>
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50627516

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档