[Fixed]-Rendering django form in view

1👍

Remove the device field from the UserProfile form – you want to edit the existing device, not change it to a different device.

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

Then create a device form.

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

Then update your view to handle two forms. For example, you need to instantiate both forms, check that both are valid, save both forms if they are valid, and so on. In case the device does not exist, you can save the profile form with commit=False to get the profile, set the device, then finally save the 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)

Finally, in your template, include both forms in the same <form> tag.

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

Leave a comment