0
我正在使用django的auth模塊來處理用戶登錄,註銷以及在我的網站中註冊。在django中使用POST方法時將代碼添加到CreateView
問題是,當我註冊一個新用戶,我新重定向到另一個URL,然後,由於模型創建但不會自動登錄,我需要導航到/ login /並登錄手動。
我想我的網站自動執行此操作。我的意思是:
- 您點擊home.html中的註冊按鈕。填寫表格並提交。
- 該網站會自動創建新的用戶模型,讓您登錄並重定向你登錄的用戶home.html的
Urls.py看起來是這樣的:
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.contrib.auth.forms import UserCreationForm
from browse.views import UserCreate
urlpatterns = patterns('',
url(r'',include('browse.urls')),
url(r'^$', 'browse.views.home_page', name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', auth_views.login, {'template_name': 'browse/login.html'}),
url(r'^register/$', UserCreate.as_view(
template_name='browse/register.html',
form_class=UserCreationForm,
success_url='/register/'
)),
url(r'^logout/$', 'browse.views.logout_view', name='logout'),
url(r'^', include('django.contrib.auth.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
和意見.py看起來像這樣:
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView
from browse.models import Pattern
from django.contrib.auth.models import User
from django.contrib.auth import logout, login
class PatternCreate(CreateView):
model = Pattern
fields = ['name','description','license', 'xcheme', 'pictures', 'video']
class UserCreate(CreateView):
model = User
def post(self, request):
return login(request, User.objects.get(username=request.POST['username']))
def home_page(request):
return render(request, 'browse/home.html')
def pattern_detail(request, pk):
pattern = Pattern.objects.get(pk=pk)
return render(request, 'browse/pattern_detail.html', {'pattern': pattern})
def logout_view(request):
logout(request)
return redirect('/')
正如你所看到的,當你GET/register /寄存器窗體被渲染時。當我發佈到/註冊/,我要執行的視圖通常然後添加:
def post(self, request):
return login(request, User.objects.get(username=request.POST['username']))
,但它看起來像我重寫,而不是向它的默認視圖,因爲該模型並不得到保存,因爲我得到這個錯誤:
例外值:
用戶匹配查詢不存在。
我該如何解決?
非常感謝你事先。