【发布时间】: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