【发布时间】:2018-04-14 09:29:02
【问题描述】:
在我的 Django 应用用户帐户中,我为我的注册创建了一个注册表单和一个模型。但是,当我运行 python manage.py makemigrations 时,遇到错误:AttributeError: module Django.contrib.auth.views has no attribute 'registration'。其次,我在 forms.py 中正确编码 SignUpForm 吗?我不想在模型中使用 User 模型,因为它会请求用户名,我不希望我的网站要求用户名。
这是我的代码:
models.py
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
class UserProfile(models.Model):
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
email = models.EmailField(max_length=150)
birth_date = models.DateField()
password = models.CharField(max_length=150)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.profile.save()
forms.py
from django.forms import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from useraccounts.models import UserProfile
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name',
'last_name',
'email',
'password1',
'password2', )
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from useraccounts.forms import SignUpForm
# Create your views here.
def home(request):
return render(request, 'useraccounts/home.html')
def login(request):
return render(request, 'useraccounts/login.html')
def registration(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.profile.birth_date = form.cleaned_data.get('birth_date')
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'registration.html', {'form': form})
urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.home),
url(r'^login/$', auth_views.login, {'template_name': 'useraccounts/login.html'}, name='login'),
url(r'^logout/$', auth_views.logout, {'template_name': 'useraccounts/logout.html'}, name='logout'),
url(r'^registration/$', auth_views.registration, {'template_name': 'useraccounts/registration.html'}, name='registration'),
]
【问题讨论】:
-
请发布您的完整错误回溯
-
原来我弄乱了 url.py 部分进行注册。感谢您的回答!
-
始终编写 Django 版本,因为版本中正在进行大量开发。
标签: python django django-models django-forms attributeerror