【问题标题】:Django form_valid error. Can anyone find the error?Django form_valid 错误。任何人都可以找到错误吗?
【发布时间】:2020-12-30 11:25:50
【问题描述】:

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

我的模型是这样的:类别>系列

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

创建新 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"}
        }

这里有人可以帮我吗?

【问题讨论】:

  • 在 url 路径中必须包含数据类型,例如:path('patient/appointment/<int:pk>/update/', PatientAppointmentUpdateView.as_view(), name="patientappointmentupdate"), 在我的看到它显示 i 并发送一个 int,它将是主键。
  • @bryant 谢谢...但它不是主键...在我的情况下是外键...

标签: python django django-forms django-generic-views


【解决方案1】:

路径上不需要做字符串处理。可以通过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)

我还建议将categoria URL 参数指定为int

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

这样,如果值不是整数,它不会触发视图。

【讨论】:

  • 感谢分享...但是随着这些更改,Django 向我发送了一条错误消息:'super' object has no attribute 'form_valid'
  • @AndreNevares:是的,你用错了super。在 Python-2.x 中使用 self,但在 Python-3.x 中,您可以简单地使用 super()
  • 消息错误:FOREIGN KEY 约束失败 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)
  • 感谢您的宝贵时间...非常感谢
  • @AndreNevares:这意味着没有 Categoriaid=3,因此 URL 不包含可引用的有效内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
相关资源
最近更新 更多