i have a problem.
This is how im trying to extend default User model:
# 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)
Now i want to change ‘games’ attr when loggin in:
# 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'
Well, my questions are:
Why ‘print profile.games’ prints ‘None’ and How can i change games attr when loggin in?
I don’t think that is a way to create field in the model. You need to do it as:
And reset it to
Noneor dict you want to store each time you login and save it.In your login view:
Problem with your code is that, value of
gameis not stored in DB. It is just an attribute of and instance. So it will not be preserved over different instances and every time you get an instance it will be reset to ‘None. InIndexview you are getting new instance ofuserprofilewhich has 'gameset toNone.