考虑这个简单的用户个人资料:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
onboarding_step = models.SmallIntegerField(default='1')
每次提交与不同模型的单独表单时,在UserProfile中递增onboarding_step
的最简单方法是什么?例如:
这是我提交的ModelForm(来自一个单独的模型,Site):
class OnBoardingProgressForm(forms.ModelForm):
class Meta:
model = Site
fields = ( 'abc', 'xyz', )
以下是表单的view.py:
if request.method == "POST":
form = OnBoardingProgressForm( request.POST )
if form.is_valid():
....
THIS CODE DOES NOT WORK BUT IS MY BEST GUESS:
last = request.user.profile
last.onboarding_step = 2
....
obj = form.save(commit=False)
obj.user = current_user
obj.save()
return render(request, "nextpage.html", {'form': form })
如何通过user.onboarding_step
增加1
?
答案 0 :(得分:1)
if request.method == "POST":
form = OnBoardingProgress( request.POST )
if form.is_valid():
....
// Can I increment the code here? //
....
obj = form.save(commit=False)
obj.user = current_user
obj.save()
user_obj = UserProfile.objects.get(user=request.user)
user_obj.onboarding_step = user_obj.onboarding_step + 1
user_obj.save()
return render(request, "nextpage.html", {'form': form })
或者你也可以制作自动增量字段。
答案 1 :(得分:0)
获取当前用户的UserProfile
对象,然后增加onboarding_step
属性的值。
试试这个:
if request.method == "POST":
form = OnBoardingProgress(request.POST)
current_user = request.user
if form.is_valid():
user_profile = UserProfile.objects.filter(user=current_user)[0] # get the user profile object for the current user
user_profile.onboarding_step += 1 # increment the value
user_profile.save() # save the object
obj = form.save(commit=False)
obj.user = current_user
obj.save()
return render(request, "nextpage.html", {'form': form })