简体   繁体   English

Django的。 简单的FormView不保存

[英]Django. Simple FormView not saving

I'm kind of new to django generic FormView. 我是django通用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 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

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. 您需要更改视图的form_valid方法,因为FormView类不会调用form.save() ,而是将用户重定向到成功URL。

def form_valid(self, form):
    form.save()
    return super(EditarPerfil, self).form_valid(form)

Although, I would agree with @Filly's answer. 虽然,我同意@Filly的回答。 If you are creating a new object, use CreateView , otherwise, use UpdateView . 如果要创建新对象,请使用CreateView ,否则请使用UpdateView

You're on the right path! 您在正确的道路上! But FormView doesn't save your model, as the documentation indicates: 但是FormView不会保存您的模型,如文档所示:

A view that displays a form. 显示表单的视图。 On error, redisplays the form with validation errors; 错误时,重新显示带有验证错误的表格; on success, redirects to a new URL. 成功后,重定向到新的URL。

You are looking for UpdateView . 您正在寻找UpdateView This way you don't need to create a separate form, just use the fields attribute in your view: 这样,您无需创建单独的表单,只需在视图中使用fields属性即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM