1 回答

TA貢獻1859條經驗 獲得超6個贊
或if 'signup' in request.POST:
都不會elif 'login' in request.POST:
在您的視圖中觸發index()
,因為您的 HTML 表單實際上并不包含這些輸入。請注意,該name
元素已棄用該<form>
屬性。
相反,您可以在表單<input>
?中添加隱藏的內容,如下所示:
<form method="POST">
? ? {% csrf_token %}
? ? {{ formlog|crispy }}
? ? <input type="hidden" name="login" value="true" />
? ? <button class="log-button first" type="submit">Login</button>
</form>
還,
formlog = auth_views.LoginView.as_view(template_name='main/index.html')
將視圖保存到formlog,而不是表單,因此調用formlog.is_valid()將導致錯誤。
代替
elif 'login' in request.POST:
? ? if formlog.is_valid():
? ? ? ? formlog.save()
? ? ? ? username = form.cleaned_data.get('username')
? ? ? ? messages.success(request, f'Your account has been created! You are now able to log in')
? ? ? ? return redirect('main')
你可能只需要做
elif 'login' in request.POST:
? ? log_view = auth_views.LoginView.as_view(template_name='main/index.html')
? ? log_view(request)
調用is_valid()、save()、 以及進行重定向都已完成LoginView。如果您仍想進行自定義,message.success()則必須重寫一個或多個方法LoginView,但這是另一個主題。
更新:
您還需要將視圖中的這一行:(formlog = auth_views.LoginView.as_view(template_name='main/index.html')之前return render...)更改為:
formlog = AuthenticationForm(request)
將此線引至街區外else。
還要在您的頂部添加表單的導入views.py:
from django.contrib.auth.forms import AuthenticationForm
需要進行此更改,因為模板需要表單對象(默認情況AuthenticationForm下LoginView)而不是視圖對象。更新后的視圖函數將如下所示:
from django.contrib.auth.forms import AuthenticationForm
def index(request):
? ? if request.method == 'POST':
? ? ? ? form = UserRegisterForm(request.POST)
? ? ? ? if 'signup' in request.POST:
? ? ? ? ? ? if form.is_valid():
? ? ? ? ? ? ? ? form.supervalid()
? ? ? ? ? ? ? ? form.save()
? ? ? ? ? ? ? ? username = form.cleaned_data.get('username')
? ? ? ? ? ? ? ? messages.success(request, f'Dear {username} you have been created a new accound!')
? ? ? ? ? ? ? ? return redirect('main')
? ? ? ? elif 'login' in request.POST:
? ? ? ? ? ? log_view = auth_views.LoginView.as_view(template_name='main/index.html')
? ? ? ? ? ? log_view(request)
? ? else:
? ? ? ? form = UserRegisterForm()
? ? formlog = AuthenticationForm(request)
? ? return render(request, 'main/index.html', {'form': form, 'formlog': formlog})
請注意,這可以通過在登錄憑據無效時提供反饋來改進。事實上,如果提供的憑據不起作用,此更新的代碼只會重新加載空白登錄表單。
添加回答
舉報