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

2024-09-30 16:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用CreateView上URL中的值

我的模型是这样的:Categoria>;意甲

我已经创建了一个path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'),

创建新系列的URL如下所示:/nova Serie/3

我正在尝试使用form_valid,但收到以下消息:

无法分配“'3'”:“Serie.categoria”必须是“categoria”实例。

views.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) 

forms.py

class SerieForm(forms.ModelForm):
    class Meta:
        model = Serie
        fields = (
            'serie',

        )
        widgets = {
            'title': forms.TextInput(),  # attrs={class="title"}
        }

这里有人能帮我吗


Tags: pathnamepyformurlformsclassnova
1条回答
网友
1楼 · 发布于 2024-09-30 16:26:59

不需要在路径上执行字符串处理。您可以使用self.kwargs获取URL参数。此外,如果要指定.categoriaid,则应设置.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)

我还建议将categoriaURL参数指定为int

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

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

相关问题 更多 >