Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to store and display data from array and (key,value) pair in django

how to store data in array and key-value pair
how to display array and key-value pair in template file from database
how to store data in array in django
how to store data in key value pair in django
how to display data from array django
how to display first value from array

To display only the values from a key-value pair stored in a database in django
To display data from a key-value pair stored in a database
how to display first key-value from key-value pai
r

how to store data in array key-value pair

Set up a Django project and create an app
Ensure you have Django installed and create a new Django project using the command django-admin startproject myproject. Next, create a new app within the project using the command python manage.py startapp myapp.

Define the model
Open the models.py file inside your app (myapp/models.py) and define the model for storing data with an array field and a key-value pair field:

from django.db import models

class MyModel(models.Model):
    normal_field = models.CharField(max_length=255)
    array_field = models.TextField()
    key_value_field = models.JSONField()

    def __str__(self):
        return self.normal_field
Enter fullscreen mode Exit fullscreen mode

In this example, we create a model called MyModel with three fields: normal_field, which is a normal CharField, array_field, which is a TextField to store the array data as a comma-separated string, and key_value_field, which is a JSONField to store the key-value pairs.

Perform database migrations
Run the following commands to create the necessary database tables for your app:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Define the view
Open the views.py file inside your app (myapp/views.py) and define the view for storing the data:

from django.shortcuts import render
from .models import MyModel

def store_data(request):
    if request.method == 'POST':
        normal_field = request.POST.get('normal_field')
        array_field = request.POST.get('array_field')
        array_data = array_field.split(',')  # Split the comma-separated string into a list

        key_value_field = {}
        for i in range(1, 6):
            key = request.POST.get(f'key{i}')
            value = request.POST.get(f'value{i}')
            if key and value:
                key_value_field[key] = value

        my_model = MyModel(normal_field=normal_field, array_field=array_data, key_value_field=key_value_field)
        my_model.save()

        return render(request, 'success.html')

    return render(request, 'store_data.html')
Enter fullscreen mode Exit fullscreen mode

In this example, we retrieve the normal_field and array_field from the POST data. We split the array_field string into a list using the comma as the delimiter. Then, we iterate over the key-value fields (key1 to key5) and create a dictionary key_value_field with the non-empty key-value pairs. We create an instance of MyModel, passing in the normal_field, array_data, and key_value_field, and save it to the database.

Define the URLs
Open the urls.py file inside your app (myapp/urls.py) and define the URL patterns:

from django.urls import path
from . import views

urlpatterns = [
    path('store-data/', views.store_data, name='store-data'),
]
Enter fullscreen mode Exit fullscreen mode

Here, we define a URL pattern that maps to the store_data view function.

Create the templates
Create two HTML templates inside a templates directory within your app:

store_data.html: The template for the form to enter the data.
success.html: The template to display a success message after storing the data.

<!DOCTYPE html>

<html>
<head>
    <title>Store Data</title>
</head>
<body>
    <h2>Store Data</h2>
    <form method="post" action="{% url 'store-data' %}">
        {% csrf_token %}
        <label for="normal_field">Normal Field:</label>
        <input type="text" name="normal_field" id="normal_field"><br><br>
        <label for="array_field">Array Field (comma-separated):</label>
        <input type="text" name="array_field" id="array_field"><br><br>

        <h3>Key-Value Pairs:</h3>
        {% for i in "12345" %}
            <label for="key{{ i }}">Key {{ i }}:</label>
            <input type="text" name="key{{ i }}" id="key{{ i }}"><br>
            <label for="value{{ i }}">Value {{ i }}:</label>
            <input type="text" name="value{{ i }}" id="value{{ i }}"><br><br>
        {% endfor %}

        <input type="submit" value="Submit">
    </form>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

how to display array and key-value pair in template file from database

Update the view function to retrieve the stored data and pass it to the template.

In your views.py file, modify the store_data view function as follows:

from django.shortcuts import render
from .models import MyModel

def store_data(request):
    if request.method == 'POST':
        normal_field = request.POST.get('normal_field')
        array_field = request.POST.get('array_field')
        array_data = array_field.split(',')  # Split the comma-separated string into a list

        key_value_field = {}
        for i in range(1, 6):
            key = request.POST.get(f'key{i}')
            value = request.POST.get(f'value{i}')
            if key and value:
                key_value_field[key] = value

        my_model = MyModel(normal_field=normal_field, array_field=array_data, key_value_field=key_value_field)
        my_model.save()

        return render(request, 'success.html')

    data = MyModel.objects.all()
    return render(request, 'store_data.html', {'data': data})
Enter fullscreen mode Exit fullscreen mode

In this example, after storing the normal field, array field, and key-value pairs data, we retrieve all the stored data using MyModel.objects.all() and pass it to the template as a context variable named data.

Step 2: Update the template file to display the stored data.

In your store_data.html template file, modify it to display the stored normal field, array field, and key-value pairs data:

<html>
<head>
    <title>Store Data</title>
</head>
<body>
    <h2>Store Data</h2>
    <form method="post" action="{% url 'store-data' %}">
        {% csrf_token %}
        <label for="normal_field">Normal Field:</label>
        <input type="text" name="normal_field" id="normal_field"><br><br>
        <label for="array_field">Array Field (comma-separated):</label>
        <input type="text" name="array_field" id="array_field"><br><br>

        <h3>Key-Value Pairs:</h3>
        {% for i in "12345" %}
            <label for="key{{ i }}">Key {{ i }}:</label>
            <input type="text" name="key{{ i }}" id="key{{ i }}"><br>
            <label for="value{{ i }}">Value {{ i }}:</label>
            <input type="text" name="value{{ i }}" id="value{{ i }}"><br><br>
        {% endfor %}

        <input type="submit" value="Submit">
    </form>

    <h2>Stored Data:</h2>
    <ul>
        {% for item in data %}
            <li>
                Normal Field: {{ item.normal_field }}<br>
                Array Field: {% for value in item.array_field %}{{ value }},{% endfor %}<br>
                Key-Value Pairs:
                <ul>
                    {% for key, value in item.key_value_field.items %}
                        <li>{{ key }}: {{ value }}</li>
                    {% endfor %}
                </ul>
            </li>
        {% endfor %}
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

how to store data in key value pair in django

Create a Django model to represent the form data:

from django.db import models

class FormData(models.Model):
    data_array = models.JSONField()
Enter fullscreen mode Exit fullscreen mode

Create a Django form to handle the input fields:

from django import forms

class MyForm(forms.Form):
    field1 = forms.CharField()
    field2 = forms.CharField()
Enter fullscreen mode Exit fullscreen mode

Create a view to handle the form submission and store the data:


from django.shortcuts import render, redirect
from .forms import MyForm
from .models import FormData

def form_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # Retrieve field values from the form
            field1_value = form.cleaned_data['field1']
            field2_value = form.cleaned_data['field2']

            # Create an array with the field values
            data_array = [field1_value, field2_value]

            # Create a new instance of the FormData model
            form_data = FormData(data_array=data_array)
            form_data.save()

            return redirect('success')
    else:
        form = MyForm()

    return render(request, 'form.html', {'form': form})

def success_view(request):
    return render(request, 'success.html')
Enter fullscreen mode Exit fullscreen mode

Create HTML templates for the form and success page:
form.html
:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

success.html:

<h1>Form submitted successfully!</h1>
Enter fullscreen mode Exit fullscreen mode

Add the URLs to your Django project's urls.py:

from django.urls import path
from .views import form_view, success_view

urlpatterns = [
    path('form/', form_view, name='form'),
    path('success/', success_view, name='success'),
]
Enter fullscreen mode Exit fullscreen mode

Now, when you access the form at /form/ and fill in the two input fields, the form data will be stored as an array in the data_array field of the FormData model. You can then retrieve and process

this data as needed.

Second way

Define the model

Open the models.py file inside your app (myapp/models.py) and define the model for the key-value pairs:

from django.db import models

class KeyValue(models.Model):
    key = models.CharField(max_length=255, unique=True)
    value = models.CharField(max_length=255)

    def __str__(self):
        return self.key
Enter fullscreen mode Exit fullscreen mode

In this example, we create a model called KeyValue with two fields: key and value. The key field is unique, meaning each key must be unique in the database.

Perform database migrations

Run the following commands to create the necessary database tables for your app:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Define the view

Open the views.py file inside your app (myapp/views.py) and define the view for storing the key-value pair:

from django.shortcuts import render
from .models import KeyValue

def store_data(request):
    if request.method == 'POST':
        key = request.POST.get('key')
        value = request.POST.get('value')
        KeyValue.objects.update_or_create(key=key, defaults={'value': value})
        return render(request, 'success.html')
    return render(request, 'store_data.html')
Enter fullscreen mode Exit fullscreen mode

In this example, we define a view function called store_data that handles the POST request. We retrieve the key and value from the request's POST data and use the update_or_create method to either update an existing key-value pair or create a new one. After storing the data, we render a success template.

Define the URLs

Open the urls.py file inside your app (myapp/urls.py) and define the URL patterns:

from django.urls import path
from . import views

urlpatterns = [
    path('store-data/', views.store_data, name='store-data'),
]
Enter fullscreen mode Exit fullscreen mode

Here, we define a URL pattern that maps to the store_data view function.

Create the templates

Create two HTML templates inside a templates directory within your app:

store_data.html: The template for the form to enter the key-value pair.
success.html: The template to display a success message after storing the data.
Here's an example of store_data.html:

<!DOCTYPE html>
<html>
<head>
    <title>Store Data</title>
</head>
<body>
    <h2>Store Data</h2>
    <form method="post" action="{% url 'store-data' %}">
        {% csrf_token %}
        <label for="key">Key:</label>
        <input type="text" name="key" id="key"><br><br>
        <label for="value">Value:</label>
        <input type="text" name="value" id="value"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
<head>
    <title>Success</title>
</head
Enter fullscreen mode Exit fullscreen mode

** Third way**

Define the view in views.py:

from django.shortcuts import render
from django.db import connection

def store_data(request):
    if request.method == 'POST':
        key = request.POST.get('key')
        value = request.POST.get('value')

        with connection.cursor() as cursor:
            cursor.execute("INSERT INTO myapp_keyvalue (key, value) VALUES (%s, %s)", [key, value])

        return render(request, 'success.html')

    return render(request, 'store_data.html')
Enter fullscreen mode Exit fullscreen mode

Define the URLs (same as before).

Create the templates (same as before).

Method 3: Using Django's get_or_create method

This method utilizes Django's get_or_create method to store the data.

Set up a Django project and create an app (same as before).

Define the model (same as before).

Perform database migrations (same as before).

Define the view in views.py:

from django.shortcuts import render
from .models import KeyValue

def store_data(request):
    if request.method == 'POST':
        key = request.POST.get('key')
        value = request.POST.get('value')

        kv_obj, created = KeyValue.objects.get_or_create(key=key, defaults={'value': value})

        if created:
            return render(request, 'success.html')
        else:
            # Handle the case where the key already exists
            return render(request, 'key_exists.html', {'key': key})

    return render(request, 'store_data.html')
Enter fullscreen mode Exit fullscreen mode

Define the URLs (same as before).

Create the templates (same as before).

Using Django's bulk_create method

This method uses Django's bulk_create method to store the data efficiently.

Set up a Django project and create an app (same as before).

Define the model (same as before).

Perform database migrations (same as before).

Define the view in views.py:

from django.shortcuts import render
from .models import KeyValue

def store_data(request):
    if request.method == 'POST':
        key = request.POST.get('key')
        value = request.POST.get('value')

        data_objects = [
            KeyValue(key=key, value=value),
        ]

        KeyValue.objects.bulk_create(data_objects)

        return render(request, 'success.html')

    return render(request, 'store_data.html')
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
<head>
    <title>Store Data</title>
</head>
<body>
    <h2>Store Data</h2>
    <form method="post" action="{% url 'store-data' %}">
        {% csrf_token %}
        <label for="key">Key:</label>
        <input type="text" name="key" id="key"><br><br>
        <label for="value">Value:</label>
        <input type="text" name="value" id="value"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And an example of success.html:

<html>
<head>
    <title>Success</title>
</head>
<body>
    <h2>Data stored successfully</h2>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

To display data from a key-value pair stored in a database
how to display first key-value from key-value pair

from django.shortcuts import render
from .models import KeyValue

def store_data(request):
    if request.method == 'POST':
        key = request.POST.get('key')
        value = request.POST.get('value')

        data = KeyValue.objects.create(key=key, value=value)
        data.save()

        return render(request, 'success.html')

    data = KeyValue.objects.all()
    return render(request, 'store_data.html', {'data': data})
Enter fullscreen mode Exit fullscreen mode

Here, after storing the key-value pair in the database, we retrieve all the key-value pairs using KeyValue.objects.all() and pass them to the template as a context variable named data.

Update the template file to display the stored key-value pairs.
In your store_data.html template file, modify it to display the stored key-value pairs:

<html>
<head>
    <title>Store Data</title>
</head>
<body>
    <h2>Store Data</h2>
    <form method="post" action="{% url 'store-data' %}">
        {% csrf_token %}
        <label for="key">Key:</label>
        <input type="text" name="key" id="key"><br><br>
        <label for="value">Value:</label>
        <input type="text" name="value" id="value"><br><br>
        <input type="submit" value="Submit">
    </form>

    <h2>Stored Data:</h2>
    <ul>
        {% for item in data %}
            <li>{{ item.key }}: {{ item.value }}</li>
        {% endfor %}
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)