Django登录/输入字段不显示/错误消息

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (532)

试着忽略了这个视频的错误(这是我的输入字段没有显示),并试图转移到下一个错误,这是登录页面背后的逻辑。但是我知道还有另外一个错误。现在,错误消息不起作用了,每当我单击Submit时,什么都不会发生。

远程接近的唯一方法是我手动地放入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",{})

表单.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 %}

表单-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>

{%结束%}

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>

设置.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'),
]

如图所示,一切都是关闭的,我不想再次重新启动,因为没有足够的时间,我会让类失败。

更新底座

{% 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>
提问于
用户回答回答于

下面是显示默认登录表单的方式(添加{{form.as_p}})

form.html

{% extends 'accounts/base.html' %}
{% block main_content %}
    <div class="container">
        <div class='col-sm-6 col-sm-offset-3'>
        <h1>{{ title }}</h1>
        <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
            {{ form.as_p }}
            <input type='submit' class='btn btn-default' value='{{ title }}' />
        </form>
    </div>
    </div>
{% endblock %}

也是在base.html中,包括完整的引导+jQuery

<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>

然后在views.py中

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')
        user = authenticate(request, username=username, password=password)      
        if user is not None:
          login(request, user)
          # or any other success page
          return HttpResponse("Logged in")
    return render(request, "accounts/form.html", {"form":form, "title": title})
用户回答回答于

问题是,即使提交了表单,也要呈现模板。试试这个:

 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')
            user = authenticate(request, username=username, password=password)      
            if user is not None:
              login(request, user)
              # Redirect to a success page.


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

将form.html输入更改为:

<input name="username" type="username" id="username" class="form-control" placeholder="Username" required autofocus>
<input name="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>

同样,在UserLoginForm中,如果不有效(),则会失败:

fields = ("username", "password")

扫码关注云+社区

领取腾讯云代金券