簡體   English   中英

'UserCreationForm'對象沒有屬性'get_username'django 1.8

[英]'UserCreationForm' object has no attribute 'get_username' django 1.8

所以我是django的新手,知道python足以不稱自己為初學者,但我絕不是專業人士。 我只是想在小型django應用程序上進行用戶身份驗證。 我正在使用默認身份驗證系統https://docs.djangoproject.com/en/1.8/topics/auth/default/ ,內置表單,登錄,注銷等都有自己的視圖,但UserCreationForm沒有有它自己的看法,所以我想我必須自己做。 不知道我做錯了什么。

這是我的views.py

  1 from django.shortcuts import render
  2 from django.http import HttpResponse
  3 from django.contrib.auth.forms import UserCreationForm
  4 from django.contrib.auth import login
  5
  6 def home(request):
  7         return HttpResponse("This is a barebones homepage")
  8
  9 def register(request):
 10         registered = False
 11
 12         if request.method == 'POST':
 13                 user_form = UserCreationForm(data=request.POST)
 14
 15                 if user_form.is_valid():
 16                         user = user_form.save()
 17                         username = user_form.get_username()
 18                         password = user_form.clean_password2()
 19                         login(request,user)
 20                 else:
 21                         print user_form.errors
 22         else:
 23                 user_form = UserCreationForm()
 24
 25         return render(request, 'registration/register.html', {'user_form': user_form, 'registered': registered}    )
~

這是我的register.html

<!DOCTYPE html>

<html>
        <head>
                <title>Jet!</title>
        </head>

        <body>
                {% if registered %}
                        Jet! says Thank you for registering!
                        <a href='/'>Return to the homepage.</a><br />
                {% else %}
                <form method="post" action="/register/">
                {% csrf_token %}
                {{ user_form.as_p }}
                <input type="submit" name="submit" value="Register" />
                </form>
                {% endif %}
        </body>
</html>

首先,行username = user_form.get_username()給出錯誤,因為正如消息所示,表單沒有get_username方法。 您可以使用user_form.cleaned_data ['username']訪問用戶名

其次,行password = user_form.clean會給出錯誤,因為表單沒有屬性clean 如果需要,可以使用user_form.cleaned_data['password1']password1字段中獲取值。

在您login用戶之前,您必須對它們進行身份驗證,否則您將收到有關沒有屬性backend的用戶的錯誤。

把它放在一起,你有:

if user_form.is_valid():
    user_form.save()
    username = user_form.cleaned_data['username']
    password = user_form.cleaned_data['password1']
    user = authenticate(username=username, password=password)
    login(request, user)

您必須通過將導入更改為以下內容來導入authenticate方法:

from django.contrib.auth import authenticate, login

請注意,您尚未在代碼中的任何位置設置registered=True 通常,在成功提交表單后重定向是一種好習慣,以防止重復提交。

將user_form.get_username()更改為request.user.username

username = user_form.get_username() = request.user.username

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM