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'

好吧,我的问题是:为什么“打印 profile.games”打印“无”以及登录时如何更改游戏属性?

4

1 回答 1

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未存储在数据库中。它只是实例的一个属性。所以它不会被保存在不同的实例上,每次你得到一个实例时,它都会被重置为 'None . InIndex view you are getting new instance ofuserprofile which has 'gameset to None.

于 2012-09-27T04:18:37.777 回答