0

私は問題があります。これは、デフォルトのユーザーモデルを拡張しようとしている方法です:

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

さて、私の質問は次のとおりです。「print profile.games」が「None」を出力する理由と、ログイン時にゲームの属性を変更するにはどうすればよいですか?

4

1 に答える 1

2

それがモデルにフィールドを作成する方法だとは思いません。次のようにする必要があります。

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

Noneそして、ログインして保存するたびに、保存したい dict または 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

コードの問題は、の値がgameDBに保存されていないことです。これはインスタンスの単なる属性です。そのため、異なるインスタンス間で保持されることはなく、インスタンスを取得するたびに、「None . InIndex view you are getting new instance ofuserprofile which has 'gameset to None.

于 2012-09-27T04:18:37.777 に答える