在Django中实现用户无效消息

0 投票
2 回答
3728 浏览
提问于 2025-04-16 14:42

我创建了一个django应用。这个应用在同一个registrationForm.html页面上有用户登录和注册功能。现在登录功能运行得很好。当用户输入正确的用户名(这里是邮箱)和密码后,用户会被重定向到另一个页面(logedIn.html),页面上会显示“用户已登录”的消息。而当用户输入的用户名或密码不正确时,页面会重新显示registrationForm.html。现在我想在这个页面上显示一条消息,内容是“检查你的用户名或密码”。作为一个django新手,我不知道该怎么做。有人能帮我解决这个问题吗?我会把我的代码贴在这里。

views.py

def registrationForm(request):
    if request.method == "POST":  
        firstName = request.POST.get("firstName")
        lastName = request.POST.get("lastName")
        email = request.POST.get("email")
        password = request.POST.get("password")
        sex = request.POST.get("sex")
        birthday = request.POST.get("birthday")
        print request.POST.get("sex")
        UniversityDetails(firstName=firstName,lastName=lastName,email=email,password=password,sex=sex,birthday=birthday).save()
        return render_to_response('registrationForm.html')
    return render_to_response("registrationForm.html")

def login(request):
    if request.POST:            
        email=request.POST.get("username")
        password = request.POST.get("password")                     
        user = UniversityDetails.objects.filter(email=email,password=password)          
        if(not user):
            return render_to_response("registrationForm.html")
        else:
            return render_to_response("logedIn.html")

html

<div align="center">
<form name="userInputForm" method="POST" id="myFormid" action="http://10.1.0.90:8080/login/">
<div style="float:left;width:100%;">
  <p style="float:left;margin-right:10px;width:auto;"><label style="float:left;">Email id</label><br/> <input type="text" name="username" size="25" /></p>
  <p style="float:left;margin-right:10px;width:auto;"><label style="float:left;">Password</label><br/><input type="password" name="password" size="25" /></p>
 </div> 
    <p style="clear:both;float:left;"><input type="submit" value="Log in" /></p>
</div>
</form>

2 个回答

2

我强烈建议你使用Django自带的用户认证系统。你可以为每个用户存储额外的信息,而且这个系统会帮你处理大部分工作,比如加密密码和管理用户权限。

如果这不行,那就考虑使用表单来收集和验证用户数据——这样做比自己手动处理要干净和简单得多。

最后,我建议你看看这个教程,了解如何在模板中使用变量。

我知道熟悉Django的操作需要一些时间(我自己也花了不少时间),但坚持下去哦 :).

3

你现在的做法有很多问题,比如把密码明文存储,这样很不安全。建议你看看Django自带的认证系统,了解一下怎么正确地让用户登录。这样做的好处是,用户信息会自动出现在request.user里。

不过,我也理解你想一步一步学习Django。根据你的代码,只需要在渲染模板时,给上下文添加一个变量,用来处理失败的情况。

def login(request):
    if request.POST:            
        email=request.POST.get("username")
        password = request.POST.get("password")                     
        user = UniversityDetails.objects.filter(email=email,password=password)          
        if(not user):
            return render_to_response("registrationForm.html", 
                       {'invalid': True }) # our template can detect this variable
        else:
            return render_to_response("logedIn.html")

模板

{% if invalid %}
    Your email/password combo doesn't exist. 
{% endif %}

撰写回答