I have a model, that extends User. In that model I have an integer field, called user_balance
. When I put the form with it to a template, I can update balance with user_profile.user_balance
field. But I don't want to just update balance. I need the sum between value, that already exist in balance, and value, that user can input... How can I do that? Am I need an additional fields in models? Or I just need something in my view?
My userprofile
model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
user_picture = models.ImageField(upload_to='users', blank=False, null=False, default='users/big-avatar.jpg')
user_balance = models.IntegerField(default=0)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u) [0])
My forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
first_name = forms.CharField(label='')
fields = ('first_name', 'last_name', 'email', )
widgets = {
'first_name': forms.TextInput(attrs={'placeholder': 'First Name', 'required': True}),
'last_name': forms.TextInput(attrs={'placeholder': 'Last Name', 'required': True}),
'email': forms.TextInput(attrs={'placeholder': 'E-Mail', 'required': True}),
}
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('user_picture', 'user_balance')
widgets = {
'user_picture': forms.FileInput(attrs={'class': 'upload_img'}),
}
And my views.py
def userprofile(request, username):
u = User.objects.get(username=username)
if request.POST:
user_form = UserForm(request.POST, instance=request.user)
user_profile = UserProfileForm(request.POST, request.FILES, instance=request.user.profile)
if user_form.is_valid():
user_form.save()
if user_profile.is_valid():
user_profile.save()
else:
user_form = UserForm(instance=request.user,
initial={
'first_name': request.user.first_name,
'last_name': request.user.last_name,
'email': request.user.email,
})
user = request.user
profile = user.profile
user_profile = UserProfileForm(instance=profile)
return render_to_response('profile.html', {'user_form': user_form, 'user_profile': user_profile}, context_instance=RequestContext(request))
Aucun commentaire:
Enregistrer un commentaire