如何使用html表单而不是Django表单将数据插入表中?

时间:2015-07-29 17:46:52

标签: html django forms

我是Django的新手。我想从我的html表单中插入数据库表中的一些数据,我实际上不想使用django表单,只是在html文件中创建的简单表单。我不知道如何做到这有什么办法吗?如果是的话,请帮助我。

由于

1 个答案:

答案 0 :(得分:0)

要使用POST参数data1,data2,... dataN处理POST请求,您可以执行以下操作。这使用基于类的视图(CBV)。

from django.views.generic.base import View
from django.http import HttpResponse

class MyView(View):

    def get(self, request):
        do_something()
        return HttpResponse('GET Success!')

    def post(self, request):
        # Retrieve POST parameters
        data1 = request.POST.get('data1', '')
        data2 = request.POST.get('data2', '')
        # ...
        dataN = request.POST.get('dataN', '')

        # Perform whatever validations you need
        perform_validations()

        # Create your object based on validated user input.
        YourModel.objects.create(
            data1=data1,
            data2=data2,
            # ...
            dataN=dataN
        )

        # Do whatever else you need to.
        do_something_else()

        # Return a response.
        return HttpResponse('POST Success!')

您也可以使用基于功能的视图(FBV)编写一个,但就个人而言,我只使用FBV来轻松测试想法或使用CBV时很痛苦。

from django.views.generic.base import View
from django.http import HttpResponse

def my_view(request):

    if request.method == 'GET':
        do_something()
        return HttpResponse('GET Success!')

    elif request.method == 'POST':
        # Retrieve POST parameters
        data1 = request.POST.get('data1', '')
        data2 = request.POST.get('data2', '')
        # ...
        dataN = request.POST.get('dataN', '')

        # Perform whatever validations you need
        perform_validations()

        # Create your object based on validated user input.
        YourModel.objects.create(
            data1=data1,
            data2=data2,
            # ...
            dataN=dataN
        )

        # Do whatever else you need to.
        do_something_else()

        # Return a response.
        return HttpResponse('POST Success!')

其他资源hereherehere