1
Existing fields are erased because you’re creating new Phone
object with existing id. You should instead retrieve existing Phone
model and update it:
phone_model = Phone.objects.get(id=1)
phone_model.num_calls = NumberOfCalls
phone_model.time_btwn_calls = TimeBetweenCalls
phone_model.psap = PSAP
phone_model.save()
Or update it using queryset update method:
Phone.objects.filter(id=1).update(
num_calls=NumberOfCalls,
time_btwn_calls=TimeBetweenCalls,
psap=PSAP,
)
First one will touch database twice. Once for loading existing phone, and then for saving new values. Second will touch database only once, updating fields without touching rest of them.
1
You should be retrieving the existing Phone object and updating it where necessary.
if form.is_valid():
number_of_calls = form.cleaned_data.get('NumberOfCalls')
time_between_calls = form.cleaned_data.get('TimeBetweenCalls')
psap = form.cleaned_data.get('PSAP')
phone = Phone.objects.get(pk=1)
phone.num_calls = number_of_calls
phone.time_btwn_calls = time_between_calls
phone.psap = psap
phone.save()
Even better, make your form a ModelForm, and include only the fields you want to update:
class Send2phone(forms.ModelForm):
class Meta:
model = Phone
fields = ['num_calls', 'time_btwn_calls', 'psap']
now your view is just:
phone = Phone.objects.get(pk=1)
if request.method == 'POST':
form = Send2tcu(request.POST, instance=phone)
if form.is_valid():
form.save()
return redirect(reverse('gracias'))
else:
form = Send2tcu(instance=phone)
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
- [Answered ]-2 OneToOneField defined for two tables. One got deleted but not other
- [Answered ]-Django REST Framework, working with list of objects after get_queryset
Source:stackexchange.com