在视图中渲染django表单

时间:2016-07-12 20:38:05

标签: python django forms

我是django的新手,我想用另一个类扩展用户模型。但是,我不知道如何让表单与类Device一起正常工作。我希望温度和电池显示在表格中。非常感谢您提前:))

models.py

class Device(models.Model):
    temperature = models.IntegerField()
    battery = models.IntegerField()

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    deviceNb= models.CharField(max_length=50)
    device = models.OneToOneField(Device, null=True) 

User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])

forms.py

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('deviceNb', 'device', )

views.py

def user_profile(request):
    if request.method == 'POST':            
        form = UserProfileForm(request.POST, instance=request.user.profile)


        if form.is_valid:
            form.save()
            #to go back to check that the info has changed
            return HttpResponseRedirect('/accounts/loggedin')

    else: # when this is a get request
        user = request.user
        profile = user.profile
        form = UserProfileForm(instance=profile)

    args = {}
    args.update(csrf(request))
    args['form'] = form

    return render(request, 'profile.html', args)

1 个答案:

答案 0 :(得分:1)

device表单中删除UserProfile字段 - 您要编辑现有设备,而不是将其更改为其他设备。

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('deviceNb',)

然后创建一个设备表单。

class DeviceForm(forms.ModelForm):
    class Meta:
        model = Device
        fields = ('temperature', 'battery',)

然后更新您的视图以处理两个表单。例如,您需要实例化两个表单,检查两个表单是否有效,如果表单有效则保存两个表单,依此类推。如果device不存在,您可以使用commit=False保存个人资料表单以获取profile,设置设备,然后最终保存个人资料。

def user_profile(request):
    user = request.user
    profile = user.profile
    device = profile.device
    if request.method == 'POST':            
        form = UserProfileForm(request.POST, instance=profile)
        device_form = DeviceForm(request.POST, instance=device)

        if form.is_valid() and device_form.is_valid():
            device = device_form.save()
            profile = form.save(commit=False)
            profile.device = device
            profile.save()
            #to go back to check that the info has changed
            return HttpResponseRedirect('/accounts/loggedin')

    else: # when this is a get request
        form = UserProfileForm(instance=profile)
        device_form = DeviceForm(instance=device)

    args = {}
    # Delete the following line - you don't need it now that you use render
    # args.update(csrf(request))
    args['form'] = form
    args['device_form'] = device_form

    return render(request, 'profile.html', args)

最后,在您的模板中,将两个表单包含在同一个<form>标记中。

<form method='post'>
   {{ form }}
   {{ device_form }}
    <input type="submit" value="submit" />
</form>