Answer the question
In order to leave comments, you need to log in
Why is form_valid not updating the object but creating a new record?
Please tell my friends how to save instance correctly after form validation.
#forms.py
from django import forms
from clinic.models import Doctor
class DoctorForm(forms.ModelForm):
class Meta:
model = Doctor
fields = [_all_]
#views.py
class DoctorDetailView(FormMixin, DetailView):
form_class = DoctorForm
model = Doctor
def get_success_url(self):
return reverse('doctor_detail', kwargs={'pk': self.object.pk})
def get_context_data(self, **kwargs):
#Получаем непосредственно сам объект
objectDoctor = Doctor.objects.get(pk =self.object.pk)
context = super(DoctorDetailView, self).get_context_data(**kwargs)
#Передаем инстанс объекта в форму
context['form'] = self.form_class(instance = objectDoctor)
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
#Сохраняем данные полученные из POST
# self.object = form.save(commit = False)
instance = form.save()
instance.save()
return super(DoctorDetailView, self).form_valid(form)
Answer the question
In order to leave comments, you need to log in
look here:
UpdateView
CreateView
Look at the differences between Create and Update View, namely self.get_object() and self.get_form_kwargs().
The get_form_kwargs function returns a dictionary with the keys 'initial', 'instance', 'data', 'files', and 'instance' defined in the ModelFormMixin (and in your case you don't use it). When get_form_kwargs value is 'instance' the model object - the form updates the object, when None - creates a new one.
Addition:
Yes, in ModelFormMixin instance is already passed to the form from self.object. Open ModelFormMixin and expand "def get_form_kwargs(self):" and what's in it. ModelFormMixin inherits FormMixin, calls super() in the overridden get_form_kwargs method,
def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = super(ModelFormMixin, self).get_form_kwargs()
if hasattr(self, 'object'):
kwargs.update({'instance': self.object})
return kwargs
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question