Marco
Marco

Reputation: 55

how to save on database

Django

code 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']}. Result extract value in print(key, value) are :

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?

Upvotes: 0

Views: 49

Answers (2)

Parth Modi
Parth Modi

Reputation: 291

replace your code for post method as below:

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

Upvotes: 1

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

Take a look at the doc first. Use getlist to get a list of values with same name. 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)

Upvotes: 1

Related Questions