简体   繁体   English

Django-将外键传递给第二模型

[英]Django - Pass Foreign Key to Second Model

I'm trying to create a fairly simply input view for a django webapp. 我正在尝试为Django Web应用程序创建一个相当简单的输入视图。 I have the following simply models set up. 我有以下简单的模型设置。 At the end I've included the traceback as well. 最后,我还包括了追溯。 The question is how do I create an object in the CreateView class and pass the foreign key of the parent object? 问题是如何在CreateView类中创建对象并传递父对象的外键?

#models.py
#imports...

class Client(models.Model):

    client_id = models.AutoField(
        primary_key=True)

class Item(models.Model):

    client = models.ForeignKey(
        Client,
        on_delete=models.CASCADE)
    item_id = models.AutoField(
        primary_key=True)

The idea is to have a list of unique clients and then each client can have a list of unique items. 这个想法是要有一个唯一客户列表,然后每个客户都可以有一个唯一项目列表。 The items are linked to the client. 这些项目链接到客户端。

#views.py
#imports...

class ItemCreate(CreateView):
    model = Item
    fields = [
        #list of fields
        ]

    def form_valid(self, form):
        form.instance.client_id = self.request.client.client_id
        return super(PermCreate, self).form_valid(form)

Given these two class models, I'm trying to CreateView that will create a new Item and have it attached to the respective Client . 给定这两个类模型,我尝试创建将创建一个新Item并将其附加到相应Client CreateView I have a ListView that will iterate through Items for a given Client . 我有一个ListView ,它将迭代给定Client Items The ListView has a link to the CreateView (Add New Item). ListView具有指向CreateView (添加新项)的链接。 I am not having a problem with the pk 's in the views or even getting to the CreateView . 我对视图中的pk甚至是CreateView I can't get the CreateView to save the object. 我无法获得CreateView来保存对象。 I get an error that says... 我收到一条错误消息,说...

'WSGIRequest' object has no attribute 'client'

The code above is derived from this question. 上面的代码是从这个问题派生的。 I've tried several iterations of the argument to set form.instance.client_id but a request is likely the wrong call. 我已经尝试过对参数进行多次迭代来设置form.instance.client_id但是request可能是错误的调用。 The examples given are using user calls not per se the table foreign key information. 给出的示例是使用user调用本身而不是表的外键信息。

I've also tried this (using the primary keys for my models) and I've tired accessing the URL pk from the template tags - but figured if I can't access them in the the views object that getting from the template would be more difficult. 我也尝试过此操作 (使用模型的主键),并且我已经很累了从模板标签访问URL pk-但想出如果我无法在views对象中访问它们,那么从模板获取将是更加困难。

Traceback 追溯

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  142.             return self.form_valid(form)

File "/Users/billarmstrong/Documents/GitHub/Core/WebDataCollect/Pro/ProWP/views.py" in form_valid
  55.         form.instance.client_id = self.request.client.client_id

Exception Type: AttributeError at /ProWP/2/additem/
Exception Value: 'WSGIRequest' object has no attribute 'client'

Update 更新

# urls.py

    path('<int:pk>/additem/', views.ItemCreate.as_view(), name='item-add'),
    path('<int:pk>/item/', views.ItemView.as_view(), name='itemview'),

I've also made some progress. 我也取得了一些进步。 I've started working with example 1 code and found that if I set form.instance.client_id = 2 that it will appropriately add the object with the foreign key of 2 . 我开始使用示例1代码,发现如果我设置form.instance.client_id = 2 ,它将适当地添加外键为2的对象。 So the issue is trying to get the originating POST pk . 因此,问题在于尝试获取原始POST pk I've tried example 2 and it throws (1048, "column 'client_id' cannot be null") which i interpret to mean that I'm not getting the Item object. 我尝试了示例2,并抛出了错误(1048, "column 'client_id' cannot be null") ,这意味着我没有得到Item对象。 So, I tried example 3 and (1048, "Column 'client_id' cannot be null") . 因此,我尝试了示例3和(1048, "Column 'client_id' cannot be null")

# views.py
# Example 1

    def form_valid(self, form):
        form.instance.client_id = 2
        return super(PermCreate, self).form_valid(form)

# Example 2

    def form_valid(self, form):
        pk = self.kwargs.get("perm_id", None)
        form.instance.client_id = pk
        return super(PermCreate, self).form_valid(form)


# Example 3

    def form_valid(self, form):
        pk = self.kwargs.get("client_id", None)
        form.instance.client_id = pk
        return super(PermCreate, self).form_valid(form)

Update 2 更新2

after testing and print ing - I think the issue is in my request or kwargs.get variable. 经过测试和print后-我认为问题出在我的requestkwargs.get变量中。 Since the entire thing works when I hard code the client_id in the instance - I've concluded that the instance does in fact exist with all the appropriate information - including the URL primary key - but I'm not getting the right variable name to access it. 由于当我在实例中对client_id进行硬编码时,整个过程都可以工作-我得出的结论是,该实例实际上与所有适当的信息一起存在-包括URL主键-但我没有获得正确的变量名来访问它。 I know it isn't item_id or client_id . 我知道它不是item_idclient_id

Update 3 更新3

Both request and KWARGS work. requestKWARGS工作。 After working through every possible variable to get to the primary key it turned out to be pk . 处理完所有可能的变量以获取主键后,结果就是pk

So rather than using either the client_id or the item_id , the value is held in pk . 因此,该值不使用client_iditem_id ,而是保存在pk Any explanation would be helpful. 任何解释都会有所帮助。 I'm guessing that the URL actually sets the variable from my urls.py file - but not 100 certain. 我猜想URL实际上是从我的urls.py文件中设置了变量-但不是100肯定的。

form.instance.client_id = self.request.client.client_id

this line should be like, 这条线应该像

form.instance.client_id = self.request.POST['client'].client_id

or 要么

form.instance.client_id = self.request.GET['client'].client_id

Depending upon request type. 根据请求类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM