我正在尝试使用CreateView上URL中的值
我的模型是这样的:Categoria>;意甲
我已经创建了一个path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'),
创建新系列的URL如下所示:/nova Serie/3
我正在尝试使用form_valid
,但收到以下消息:
无法分配“'3'”:“Serie.categoria”必须是“categoria”实例。
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)
class SerieForm(forms.ModelForm):
class Meta:
model = Serie
fields = (
'serie',
)
widgets = {
'title': forms.TextInput(), # attrs={class="title"}
}
这里有人能帮我吗
不需要在路径上执行字符串处理。您可以使用
self.kwargs
获取URL参数。此外,如果要指定.categoria
的id
,则应设置.categoria_id
:我还建议将
categoria
URL参数指定为int
:这样,如果该值不是整数,则不会激发视图
相关问题 更多 >
编程相关推荐