问题
I'm kind of new to django generic FormView. I'm missing something obvious, the form renders correctly but it is not saving the data:
forms.py
from perfiles.models import Perfil
class FormEditarPerfil(forms.ModelForm):
class Meta:
model = Perfil
fields = ('descripcion',)
views.py
from django.views.generic.edit import FormView
from forms import FormEditarPerfil
class EditarPerfil(FormView):
template_name = "perfiles/editar_perfil.html"
form_class = FormEditarPerfil
def get_success_url(self):
url = reverse_lazy('perfiles:propio', kwargs={'username': self.request.user.username})
return url
回答1:
You're on the right path! But FormView
doesn't save your model, as the documentation indicates:
A view that displays a form. On error, redisplays the form with validation errors; on success, redirects to a new URL.
You are looking for UpdateView. This way you don't need to create a separate form, just use the fields
attribute in your view:
from django.views.generic.edit import UpdateView
from perfiles.models import Perfil
class EditarPerfil(UpdateView):
template_name = "perfiles/editar_perfil.html"
model = Perfil
fields = ['descripcion']
def get_success_url(self):
url = reverse_lazy('perfiles:propio', kwargs={'username': self.request.user.username})
return url
回答2:
You need to change the view's form_valid
method because the FormView
class does not call form.save()
and instead, just redirect the user to the success url.
def form_valid(self, form):
form.save()
return super(EditarPerfil, self).form_valid(form)
Although, I would agree with @Filly's answer. If you are creating a new object, use CreateView
, otherwise, use UpdateView
.
来源:https://stackoverflow.com/questions/31978740/django-simple-formview-not-saving