我正在尝试添加一项功能,以便新用户在初次登录时需要更新他/她的密码。我在我的Profile模型中添加了一个隐藏的BooleanField,其中default = True。
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
force_password_change = models.BooleanField(default=True)
但是,当我在views.py中尝试使用force_password_change时,它永远不会返回我在django管理页面中设置的正确值。
views.py
if request.method == 'POST':
...
user = authenticate(request, username=username, password=password)
changepass = UserProfile.objects.get(user=request.user)
if user:
if changepass.force_password_change == True:
changepass.force_password_change = False
changepass.save()
return HttpResponseRedirect('/login/register/')
elif changepass.force_password_change == False:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/main/')
else:
return HttpResponse("Your account has been disabled.")
目前正在给我这个错误
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\core\handlers\exception.py", line
41, in inner
response = get_response(request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 187,
in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 185,
in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "start\views.py", line 20, in user_login
changepass = UserProfile.objects.get(user=request.user)
File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85,
in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 380, in
get
self.model._meta.object_name
start.models.DoesNotExist: UserProfile matching query does not exist.
我还在我的settings.py中添加了AUTH_PROFILE_MODULE = 'start.UserProfile'
,这似乎不是问题所在。
答案 0 :(得分:1)
您忘记使用受尊敬的用户
创建UserProfilefrom django.db.models.signals import post_save
from models import UserProfile
from django.contrib.auth.models import User
def register(request):
if request.method == 'POST':
uf = UserForm(request.POST, prefix='user')
upf = UserProfileForm(request.POST, prefix='userprofile')
if uf.is_valid() and upf.is_valid():
user = uf.save()
userprofile = upf.save(commit=False)
userprofile.user = user
userprofile.save() # Are you missing this line ??
return django.http.HttpResponseRedirect(…something…)
答案 1 :(得分:0)
这与布尔字段无关。该错误告诉您,您的特定用户在UserProfile表中没有相关条目。