代码views.py:from django.shortcuts import renderfrom django.http import HttpResponsefrom django.views.decorators.csrf import csrf_exemptfrom home.models import Post@csrf_exemptdef home(request): context = {'request_method': request.method} if request.method == 'POST': context['request_payload'] = request.POST.dict() post_data = dict(request.POST) print(post_data) for key, value in post_data.items(): for subvalue in value: print(key, subvalue) if key == 'name': m = Post.name(subvalue) m.save() if key == 'description': print(subvalue) p = Post.description(subvalue) p.save() if request.method == 'GET': context['request_payload'] = request.GET.dict() return HttpResponse()代码模型.pyfrom django.db import modelsclass Post(models.Model): name = models.CharField(max_length=150) description = models.CharField(max_length=150)结果中print(post_data)的{'name': ['luca', 'jeams'], 'description': ['all', 'all2']}. 结果提取值print(key, value)是:name Lucaname jeamsdescription alldescription all2我想将这些数据保存在数据库中,但它不起作用。我能怎么做?
2 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
替换您的 post 方法代码,如下所示:
if request.method == 'POST':
for ind, obj in enumerate(request.POST.getlist('name')):
desc = request.POST.getlist('description')[ind]
Post.object.create(name=obj, description=desc)
这对你有用
添加回答
举报
0/150
提交
取消