简体   繁体   English

如何保存在数据库上

[英]how to save on database

Django Django的

code views.py: 代码views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from home.models import Post

@csrf_exempt
def 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()

code models.py 代码模型

from django.db import models

class Post(models.Model):
    name = models.CharField(max_length=150)
    description = models.CharField(max_length=150)

Result in print(post_data) are {'name': ['luca', 'jeams'], 'description': ['all', 'all2']}. print(post_data)中的结果为{'name': ['luca', 'jeams'], 'description': ['all', 'all2']}. Result extract value in print(key, value) are : print(key, value)中的结果提取值是:

name Luca
name jeams
description all
description all2

I would like to save this data on database, but it does not work. 我想将此数据保存在数据库中,但不起作用。 How can i do? 我能怎么做?

Take a look at the doc first. 首先看一下文档 Use getlist to get a list of values with same name. 使用getlist获取具有相同名称的值的列表。 Then iterate over them and save the data in your table. 然后遍历它们并将数据保存在表中。

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from home.models import Post

@csrf_exempt
def home(request):
    context = {'request_method': request.method}
    if request.method == 'POST':
        context['request_payload'] = request.POST.dict()

        names = request.POST.getlist('name')
        descriptions = request.POST.getlist('description')

        for i in range(len(names)):
            post = Post.objects.create(name=names[i], description=descriptions[i])

    if request.method == 'GET':
        context['request_payload'] = request.GET.dict()
    return render(request, 'your_template_name_here', context)

replace your code for post method as below: 将您的代码替换为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)

It would work for you 它会为你工作

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

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