Я хочу изменить некоторые из моего объекта 'Location' с помощью UpdateView.
class LocationUpdateView(UpdateView):
#form_class = LocationForm
model = LocationTemplate
fields = ['address','district','grid_x','grid_y']
#template_name = 'locationTemplate_update_form'
def get_success_url(self):
return reverse('location_detail', kwargs={'pk': self.object.pk})
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
self.object = self.get_object()
for loc in Location.objects.all():
if self.object.location_name == loc.location_name:
setattr(loc,'address',(form.cleaned_data['address']))
setattr(loc,'district',(form.cleaned_data['district']))
setattr(loc,'grid_x',(form.cleaned_data['grid_x']))
setattr(loc,'grid_y',(form.cleaned_data['grid_y']))
loc.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
Однако вместо обновления объектов вышеуказанный l oop создает новый объект с информацией об обновлении ( кроме location_name это None). Я ожидал, что setattr () изменит атрибуты этого специфика c lo c вместо создания новых экземпляров.
models.py
class LocationTemplate(models.Model):
location_name = models.CharField(max_length=50, null=True, blank=True)
address = models.CharField(max_length=300, null=True, blank=True)
district = models.CharField(max_length=300, null=True, blank=True)
grid_x = models.IntegerField(null=True, blank=True)
grid_y = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.location_name + ", Address: " + self.address + ", District: " + self.district + ", Coordinates: (" + str(self.grid_x) + ", " + str(self.grid_y) + ")"
forms.py
class LocationForm(forms.ModelForm):
class Meta:
model = LocationTemplate
#exclude = ('patient',)
fields=['location_name', 'address','district', 'grid_x','grid_y']