我花了好几个小时查看文档,并在这里以及我仍然无法找到我的问题的答案。如果你知道一个人直接告诉我。否则请看下面的问题。当我尝试将用户注册为开源民宿项目的主机时,我收到一个KeyError:https://github.com/castaway2000/OpenStay这还没有推送到主分支。我也试过setattr()和实例。在这一点上,我只是没有点击。用模型保存django OneToOneField当前用户
models.py
class HostRegistration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=30)
zipcode = models.CharField(max_length=15)
country = models.CharField(max_length=30)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user
forms.py
class HostForm(forms.ModelForm):
#no need for charfields here because we refrence the model with the fields
class Meta:
model = HostRegistration
fields = ['address', 'city', 'state', 'zipcode', 'country']
views.py - 这里的问题开始XD
# become a host
def host_register(request):
user = request.user
if user.is_authenticated:
if request.method == 'POST':
host_form = HostForm(data=request.POST)
if host_form.is_valid():
host_form.fields['user'].instance = user.id # this is where its failing.
host = host_form.save(commit=False)
print host
host.save()
return HttpResponseRedirect('/edit_userpage/')
else:
print host_form.errors
else:
return HttpResponseRedirect('/')
guide_form = HostForm()
context = {'guide_form': guide_form}
return render(request, 'users/host.html', context)
请让我知道如何访问模型对象'用户'在我的意见,并保存当前登录的用户作为与模型的参考。这将是很大的帮助。
我假定这是进入views.py?如果是的话就开始抛出NameErrors:self没有被定义,而且清空数据没有被定义。 – castaway2000
糟糕,我的意思是host_form.cleaned_data。我修正了我的评论。 – user6731765
它会抛出None并返回完整性错误。 'Django的版本:\t 1.7.6 异常类型:\t IntegrityError 异常值:\t NOT NULL约束失败:users_hostregistration.user_id' – castaway2000