1

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
M.javid
  • 6,387
  • 3
  • 41
  • 56
Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180

2 Answers2

3

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.

Rod Xavier
  • 3,983
  • 1
  • 29
  • 41
2

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
Aylen
  • 3,524
  • 26
  • 36