Django-外键-以10为底的int()的无效文字:'123453-11-32'

时间:2018-07-23 01:15:30

标签: python django django-models foreign-keys

首先,我认为发生此错误是因为Django需要整数,而是传递了一个字符串。问题是,我不知道Django为什么期望在哪里以及在哪里期望整数。

错误消息

ValueError at /well_list/123453-11-32/contextual/bha/1
invalid literal for int() with base 10: '123453-11-32'

models.py

class WellInfo(models.Model):
    api = models.CharField(max_length=100, primary_key=True)
    well_name = models.CharField(max_length=100)

class BHA_List(models.Model):
    well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list')
    bha_number = models.CharField(max_length=100)

app / urls.py

app_name = 'contextual'

urlpatterns = [
    re_path(r'^$', base_views.ContextualMain_DetailView.as_view(), name='main'),
    re_path(r'^bha/(?P<pk_alt>[-\w]+)$', base_views.BHA_UpdateView.as_view(), name='bha'),
]

project / urls.py

urlpatterns = [
    path('well_list/', include([

        re_path(r'^$', views.WellList_ListView.as_view(), name='well_list'),
        re_path(r'^create/$', views.AddWell_CreateView.as_view(), name='create'),
        re_path(r'^(?P<pk>[-\w]+)/contextual/', include('contextual.urls')),

        ]))
]

context_processors.py

def add_context_to_base(request):

    print('context_processor was called')

    try:
        api = resolve(request.path_info).kwargs['pk']
        default_page_1 = '1'

        return {'api': api, 'default_page_1': default_page_1}

    except KeyError:

        return {}

我添加context_processor的原因是因为使用123453-11-32将URL context_processor中的字符串注入到 base.html 中。我不确定这是否是错误的根源。但是我不认为这是错误的根源,因为它没有在控制台上打印context_processor was called

最后,这是我的views.py给我的错误:

views.py

class BHA_UpdateView(UpdateView):
    template_name = 'bha_test.html'
    context_object_name = 'bha'
    model = models.BHA_List
    fields = '__all__'
    success_url = reverse_lazy('well_list')

但是,如果我更改模型并设置为model = models.WellInfo,它就可以正常工作。我的BHA_list模型似乎有问题,因为它具有ForeignKey。任何人都可以帮助解决我的代码有什么问题吗?

编辑:

我找出了错误的根源。默认情况下,Django设置pk_url_kwarg = 'pk'。调用(?P<pk>[-\w]+)时已经使用了ContextualMain_DetailView模式,所以我必须为pk_url_kwarg = 'pk_alt'声明一个单独的BHA_UpdateView

0 个答案:

没有答案