我有个问题。这就是我尝试扩展默认用户模型的方式:
# myapp models.py
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(User)
games = None
def create_user_profile(sender, instance, created, **kwargs):
if not created:
profile, created = UserProfile.objects.get_or_create(user=instance)
models.signals.post_save.connect(create_user_profile, sender=User)
现在我想在登录时更改“游戏”属性:
# myapp views.py
from django.views.generic.edit import FormView
from django.contrib.auth.forms import AuthenticationForm
class LoginView(FormView):
form_class = AuthenticationForm
template_name = 'registration/login.html'
def form_valid(self, form):
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# default value for games is None
user.userprofile.games = {}
# now it should be an empty dict
login(self.request, user)
return redirect('/game')
class Index(FormView):
def dispatch(self, request, *args, **kwargs):
profile = request.user.get_profile()
print profile.games # Prints 'None'
好吧,我的问题是:为什么“打印 profile.games”打印“无”以及登录时如何更改游戏属性?