使用modelform

时间:2017-04-06 19:04:03

标签: python django django-models django-forms

我花了好几个小时查看文档,并在这里,我仍然无法找到我的问题的答案。如果你知道有人直接告诉我,请。否则请看下面的问题。当我尝试将用户注册为开源家庭寄宿项目的主机时,我收到了一个KeyError:https://github.com/castaway2000/OpenStay这还未被推送到主分支。我也试过了setattr()和实例。在这一件事上我没有点击我的东西。

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)

请告诉我如何访问模型对象'用户'在我的视图中,使用modelform将当前登录的用户保存为对它的引用。这将是很大的帮助。

2 个答案:

答案 0 :(得分:1)

我找到了答案。

我将我的model.py改为

class HostRegistration(models.Model):
    # user is the changed variable
    user = models.OneToOneField(settings.AUTH_USER_MODEL, 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

我将views.py更新为:

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():
                instance = host_form.save(commit=False)  # this is the trick.
                instance.user = request.user  # and this to get the currently logged in user
                instance.save()  # to commit the new info
                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)

答案 1 :(得分:0)

如果您执行host_form.cleaned_data.get("user")而不是host_form.fields['user'].instance吗?