代码之家  ›  专栏  ›  技术社区  ›  Andre Nevares sj95126

Django form_有效错误。有人能找到错误吗?

  •  1
  • Andre Nevares sj95126  · 技术社区  · 5 年前

    我做了一个网址 path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'),

    创建新系列的URL如下所示:

    我试着用 form_valid 但我收到的信息是:

    视图.py

    class NovaSerie(CreateView):
        model = Serie
        form_class = SerieForm
        template_name = 'nova_serie.html'
        success_url = reverse_lazy('home')
    
        def form_valid(self, form):
            url = self.request.path_info
            parte_final_url = url.replace('/nova-serie/', '')
            form.instance.categoria = parte_final_url
            return super(NovaSerie).form_valid(form) 
    

    表单.py

    class SerieForm(forms.ModelForm):
        class Meta:
            model = Serie
            fields = (
                'serie',
    
            )
            widgets = {
                'title': forms.TextInput(),  # attrs={class="title"}
            }
    

    这里有人能帮我个忙吗?

    1 回复  |  直到 5 年前
        1
  •  1
  •   willeM_ Van Onsem    5 年前

    不需要在路径上进行字符串处理。您可以使用 self.kwargs . 此外,如果要指定 id .categoria 你应该准备好 .categoria_id

    class NovaSerie(CreateView):
        model = Serie
        form_class = SerieForm
        template_name = 'nova_serie.html'
        success_url = reverse_lazy('home')
    
        def form_valid(self, form):
            form.instance.categoria_id = self.kwargs['categoria']
            return super().form_valid(form)

    我还建议具体说明 categoria URL参数作为 int

    path('nova-serie/<int:categoria>', NovaSerie.as_view(), name='nova_serie'),

    这样,如果值不是整数,则不会激发视图。