Django在视图中调用API后保存并输入数据

时间:2018-01-25 03:12:47

标签: django django-rest-framework

我有2个django项目,D1和D2。 D1有一个表调用T1,D2有一个表调用T2。

所以我在D1中有一个视图api调用D2中的api并将POST后的请求值保存到T1中。但我也希望能够在表T1的其他字段中输入数据。

示例:t2只有$config['base_url'] = '/'; $config['index_page'] = ''; $config['uri_protocol'] = 'REQUEST_URI'; 字段,t1有bookbook字段。当D1在D2中对t2执行post方法时,它将返回author值,该值将保存到book但我还希望用户自己输入t1。我该怎么做 ?

这是我的代码

models.py

在D1中:

author

在D2

class T1(models.Model):
    book = models.CharField(max_length=10, blank=True, null=True)
    author = models.CharField(max_length=10, blank=True, null=True)

views.py

class T2(models.Model):
    book = models.CharField(max_length=10, blank=True, null=True)

1 个答案:

答案 0 :(得分:2)

我相信您可以在对my_django_view发出的同一POST请求中执行此操作。您可以将request.POST视为字典。它基本上具有请求中所有用户输入的键值对,也可能是您的CSRF令牌之类的东西。在任何情况下,在您的前端,您都希望有一个表单或其他内容与您的其他现有request.POST数据一起发送,以便您可以在视图中将其解压缩。

@csrf_exempt
def my_django_view(request):

    author = None  # let author be None at the start

    if request.method == 'POST':
        post_data = request.POST.copy()  # make a copy
        author = post_data.dict().pop("author", None)  # Extract out the author here and remove it from request.POST
        r = requests.post('http://127.0.0.1:8000/api/test/', data=post_data)
    else:
        r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET)

    if r.status_code == 201 and request.method == 'POST':
        data = r.json()
        testsave_attrs = {
            "book": data["book"],
            "author": author
        }
        # You should probably do some validation that author is not None here
        # before you actually attempt to create T1.
        # You could do it here or anywhere else before creating T1.
        testsave= T1.objects.create(**testsave_attrs)
        return HttpResponse(r.text)
    elif r.status_code == 200:  # GET response
        return HttpResponse(r.json())
    else:
        return HttpResponse('Could not save data')