【问题标题】:Django UpdateView using the validation of a custom create viewDjango UpdateView 使用自定义创建视图的验证
【发布时间】:2015-02-02 09:41:00
【问题描述】:

已解决:阅读 Daniel Roseman 的简洁答案。效果很好。

我不是 Django 方面的专家:抱歉,如果我的问题答案很简单。
我正在使用 Django 开发(1.8?)。
我的应用程序管理需要验证和连贯的某些 DATE 类型的条目。因此在

views/create_fest.py

我有如下:

class Formulario_nuevo_festivo(forms.ModelForm):

class Meta:
    model = Festivo
    fields = ('nombre_festivo','fecha_unica','fecha_inicio','fecha_fin')
def clean(self):
    cleaned_data=super(Formulario_nuevo_festivo,self).clean()
    fecha_unica     =cleaned_data.get("fecha_unica","")
    fecha_inicio    =cleaned_data.get("fecha_inicio","")
    fecha_fin       =cleaned_data.get("fecha_fin","")
    if fecha_unica and fecha_inicio and fecha_fin:
        raise forms.ValidationError(u"some message")
    elif not fecha_unica and not fecha_inicio and not fecha_fin:
        raise forms.ValidationError(u"some message")
    elif (fecha_unica and (fecha_inicio!=None or fecha_fin!=None)) or (fecha_inicio and not fecha_fin) or (fecha_fin and not fecha_inicio):
        raise forms.ValidationError(u"some message.")
    else:
        if (fecha_unica and (fecha_inicio==None or fecha_fin==None)):
            pass
        elif fecha_inicio > fecha_fin or fecha_inicio==fecha_fin:
            raise forms.ValidationError(u"some message.")
        else:
            pass
    return cleaned_data

def page(request):
    if request.POST:
        form = Formulario_nuevo_festivo(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse_lazy('listado_festivos'))
        else:
            return render(request, 'crear_festivo.html',{'form':form})
    else:
        form=Formulario_nuevo_festivo()
        return render(request,'crear_festivo.html',{'form':form})

效果很好:验证工作正常,用户只能通过完成验证来创建对象- 当我使用 UPDATEVIEW 管理对此模型的更改时,问题就出现了: 这是views.pysn-p内部的一段代码:

...
class FestivoUpdateView(UpdateView):
model           = Festivo
fields          = ['nombre_festivo','fecha_unica','fecha_inicio','fecha_fin']
template_name   = "editar_festivo.html"
success_url     = reverse_lazy('listado_festivos')
def post(self, request, *args, **kwargs):
    if "cancel" in request.POST:
        self.object = self.get_object()
        url = self.get_success_url()
        return HttpResponseRedirect(url)
    else:
        return super(FestivoUpdateView, self).post(request, *args, **kwargs)
...

问题是用户可以在没有任何验证的情况下将任何数据输入到这个 UdateView 中。

我搜索了很多(因为我不是以英语为母语的人),但我没有找到答案。
一个懒惰的程序员会说“嘿,你可以在 views.py 中重复验证代码并再次进行验证”,但这会违反 DRY 理念,我很确定必须有一种简单的方法来强制 UpdateView 使用 create查看验证。

如果我把它放在像“core/validate.py”这样的地方然后将它作为一个函数导入呢? 我不知道如何解决这个问题,任何帮助将不胜感激。
先谢谢了

【问题讨论】:

  • 不要使用开发版。坚持使用稳定的 1.7 版本。

标签: django django-views django-generic-views django-validation


【解决方案1】:

您只需将您的观点告诉use your form

class FestivoUpdateView(UpdateView):
    form_class = Formulario_nuevo_festivo
    ...etc...

请注意,您的表单中似乎没有任何内容使其仅适用于节日,因此您可能希望将其重命名为更通用(且符合 PEP8)的名称,例如FormularioFestivo。

【讨论】:

  • 感谢您如此快速、简洁地回答。该死!解决方案似乎很明显......确实我之前在搜索文档时遇到过......但我的导入没有成功。无论如何,我明天会再试一次。您的意思是从 Formulario_nuevo_festivo 更改为 FormularioFestivo? :)
  • 已解决!谢谢丹尼尔。
猜你喜欢
  • 2017-10-25
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
  • 2011-05-24
相关资源
最近更新 更多