Templateview in django has gone error "Field 'id' expected a number but got 'form_file' "

Viewed 39

This is my view.py file

class UploadTemplateView(TemplateView):
    template_name = 'reports/from_file.html'

This is my urls.py file

urlpatterns = [
    path('save/', create_report_view, name='create-report'),
    path('', ReportListView.as_view(), name='main'),
    path('from_file/', UploadTemplateView.as_view(), name='form-file'),
    path('<pk>/', ReportDetailView.as_view(), name='detail'),
    path('upload/', csv_upload_view, name='upload'),
    path('<pk>/pdf/', render_pdf_view, name='pdf'),
    
]

When I try to access my page it cost an error "Field 'id' expected a number but got 'form_file' The only way to fix it is by changing the pathname to number. How can I define pathname as a string

1 Answers

If you do not specify the type of a path converter, Django will assume that you meant <str:…, so <pk> will match with all strings, not only numerical ones.

You can restrict it to <int:…> and thus fire the csv_upload_view only when it does not match a number:

urlpatterns = [
    path('save/', create_report_view, name='create-report'),
    path('', ReportListView.as_view(), name='main'),
    path('from_file/', UploadTemplateView.as_view(), name='form-file'),
    path('upload/', csv_upload_view, name='upload'),
    path('<int:pk>/', ReportDetailView.as_view(), name='detail'),
    path('<int:pk>/pdf/', render_pdf_view, name='pdf'),
    
]

In your template you also made a mistake for the URL: it is from_file, not form_file, you thus should either update the path(…), or the link in the template.

Related