使用django 1.5.1我尝试将django表单用于我的一个模型。 我不想在代码中的某处添加“user”字段(Foreignkey),而不是让用户自欺欺人地使用新角色。
我的代码: 型号:
class Character(models.Model):
user = models.ForeignKey(User)
creation = models.DateTimeField(auto_now_add=True, verbose_name='Creation Date')
name = models.CharField(max_length=32)
portrait = models.ForeignKey(Portrait)
faction = models.ForeignKey(Faction)
origin = models.ForeignKey(Origin)
表格:
class CreateCharacterForm(forms.ModelForm):
class Meta:
model = Character
fields = ['name', 'portrait', 'faction', 'origin']
观点:
def create_character(request, user_id):
user = User.objects.get(id=user_id)
if request.POST:
new_char_form = CreateCharacterForm(request.POST)
if new_char_form.is_valid():
new_char_form.save()
return HttpResponseRedirect('%s/characters/' % user_id)
else:
return render_to_response('create.html',
{'user': user, 'create_char':new_char_form},
context_instance=RequestContext(request))
else:
create_char = CreateCharacterForm
return render_to_response('create.html',
{'user': user, 'create_char': create_char},
context_instance=RequestContext(request))
我已经尝试使用实例来包含用户ID。我已经尝试在保存之前将userid保存到表单,或者从表单中更改save()。 我一直得到character.user不能为null的错误 我必须告诉我这对django来说很新,并且我确定这种方式应该是可能的
有人可以帮帮我吗?
答案 0 :(得分:1)
在文件model form selecting fields to use中解释得很清楚 你必须在你的视图中做这样的事情
...
if request.POST:
new_char_form = CreateCharacterForm(request.POST)
if new_char_form.is_valid():
#save form with commit=False
new_char_obj = new_char_form.save(commit=False)
#set user and save
new_char_obj.user = user
new_char_obj.save()
return HttpResponseRedirect('%s/characters/' % user_id)
else:
...