在我的项目中,每个用户都可以拥有多个敌人,例如:
模型
class EnemyModel(models.Model):
name = models.CharField(max_length=128)
weapon = models.CharField(max_length=128)
related_user = models.ForeignKey(UserProfile)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
只有用户可以在他的个人资料中添加敌人,所以我制作了这样的表格:
形式
class AddEnemyForm(forms.ModelForm):
class Meta:
model = EnemyModel
exclude = ['related_user'] # only current user
我的想法是修改视图中的排除字段,但它不起作用:
视图
def add_enemy(request):
args={}
if request.method == "POST":
form = AddEnemyForm(request.POST)
form.related_user = request.user # error
# form.related_user_id = request.user.id # also error
if form.is_valid():
form.save()
return HttpResponse("<h1>Done!</h1>")
else:
args.update(csrf(request))
args["form"]=form
return render_to_response("add_enemy.html",args)
args.update(csrf(request))
args["form"]=AddEnemyForm()
return render_to_response("add_enemy.html",args)
如何在保存之前修改表单?
答案 0 :(得分:3)
使用form.instance
:
def add_enemy(request):
args={}
if request.method == "POST":
form = AddEnemyForm(request.POST)
# form.instance is the instance to be saved
form.instance.related_user = request.user.userprofile
if form.is_valid():
form.save()
return HttpResponse("<h1>Done!</h1>")
else:
args.update(csrf(request))
args["form"]=form
return render_to_response("add_enemy.html",args)
args.update(csrf(request))
args["form"]=AddEnemyForm()
return render_to_response("add_enemy.html",args)
请注意,enemymodel.related_user
应为UserProfile
,request.user
为User
。您需要使用request.user.userprofile
。