Python,Django。使用字典属性扩展用户模型

时间:2012-09-27 03:30:26

标签: 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'

好吧,我的问题是: 为什么'print profile.games'打印'无'以及如何在登录时更改游戏attr?

1 个答案:

答案 0 :(得分:2)

我认为这不是在模型中创建字段的方法。你需要这样做:

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

并将其重置为None或每次登录时都要存储并保存。

在您的登录视图中:

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 'game设置为None