Reputation: 2809
I am new to django, and I want to extend the user model with another class. However, I am not sure how to get the form to work properly with the class Device. I would like temperature, and battery to show up in the form. Thank you very much in advance :)
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)
Upvotes: 0
Views: 90
Reputation: 308809
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>
Upvotes: 1