我有一個問題。 這是IM如何想擴展默認的用戶模式:Python,Django。用字典屬性擴展用戶模型
# 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)
現在我想改變「遊戲」 ATTR當洛在:
# 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'
好了,我的問題是: 爲什麼「印刷輪廓.games'打印'無',如何在登錄時更改遊戲屬性?
你忘了做'save'?我瘋狂的猜測。此外,默認情況下'遊戲'是None,'{}'是None,因爲它是一個空字典。 – user1012451
@ user1012451似乎'save'沒有幫助。順便說一句,'D = {};打印d'會顯示'{}'而不是'None' – malinoff