2012-09-27 2 views
0

문제가 있습니다.Python, Django. 사전 특성이있는 사용자 모델 확장

# 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' 

글쎄, 내 질문은 다음과 같습니다 : 왜 '인쇄 프로파일

# 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) 

지금 내가 loggin에의 할 때'게임 'ATTR을 변경하려면 : 이 메신저 기본 사용자 모델을 확장하려고하는 방법이다 .games 'prints'None '그리고 로그인 할 때 게임 attr을 어떻게 바꿀 수 있습니까?

+1

'저장'을 잊어 버리셨습니까? 내 추측이야. 게다가 디폴트로'games'는 None이고'{}'은 빈 dict이므로 None입니다. – user1012451

+0

@ user1012451 '저장'이 도움이되지 않은 것 같습니다. Btw,'d = {}; print d'는'None' 대신'{}'를 표시합니다 – malinoff

답변

2

나는 모델에서 필드를 만드는 방법이라고 생각하지 않습니다.

game = models.CharField(max_length=300, null=True, blank=True) 

그리고 None으로 재설정 또는 당신이 로그인 할 때마다 저장하고 저장 할 DICT : 당신은 그것을 할 필요가있다. 로그인보기에서

: 코드와

import json 
class LoginView(FormView): 
    .... 
    #your code 
    if user.is_active: 
     # default value for games is None 
     user.userprofile.games = json.dumps({}) # some dict you want to store 
     user.userprofile.save() #save it 

     # now it should be an empty dict 
     login(self.request, user) 
     return redirect('/game') 
    .... 
    #your other code 

문제 game의 값이 DB에 저장되지 않은 점이다. 그것은 단지와 인스턴스의 속성입니다. 따라서 다른 인스턴스에서 보존되지 않으며 인스턴스를 얻을 때마다 '없음'으로 재설정됩니다. . In 인덱스 view you are getting new instance of userprofile which has 'gameNone으로 설정됩니다.

+0

예, 고맙습니다. 나는 그것을 게임의 모델로 리펙토링 할 것이다. – malinoff

관련 문제