user7761401
user7761401

Reputation:

django dictionary for loop not printing anything

There are already a lot of questions+answers regarding for loops in django, but none of the solutions work for me, so there must be something fundamentally wrong.

I have a dictionary in python/json (tried both) that I want to loop through and print.

Doing the following print a new line for each character

 {% for item in data.dict %}
    <p>{{item}}</p>
 {% endfor %}

so something like this get's printed

{
'
N
o
d
e
'
:

The following code straight up prints nothing

{% for key, values in data.dict.items %}
   <p>{{key}}</p>
{% endfor %}

Data is the name of my registered model and object is one of its variables. In my Views.py I have something similar to this:

Data.objects.create(
        dict=theDictIAmPassing
}.save

EDIT

models.py

from django.db import models

class Data(models.Model):
    dict1= models.TextField()
    dict2 = models.TextField()
    dict3 = models.TextField()
    dict4 = models.TextField()

views.py

def add(request):

    if request.method == 'POST':

        form = EntryForm(request.POST)

        if form.is_valid():
            ProjectName = form.cleaned_data['ProjectName']
            date = form.cleaned_data['date']
            folder = form.cleaned_data['folder']
            description = form.cleaned_data['description']

            myprog = program.program(folder)
            createMetrics(myprog)

            Entry.objects.create(
                ProjectName=ProjectName,
                date=date,
                folder=folder,
                description=description
            ).save()

            return HttpResponseRedirect('/')
    else:
        form = EntryForm()

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


def createMetrics(myprog):
    Metrics.objects.create(
        dict1=myprog.getDict1(),
        dict2=myprog.getDict2(),
        dict3=myprog.getDict3(),
        dict4=myprog.getDict4()
    ).save()

Upvotes: 1

Views: 203

Answers (1)

user7761401
user7761401

Reputation:

Solution found at https://stackoverflow.com/a/7469287/7761401

I needed to rewrite my Data model. Textfield (which I used because I couldn't find anything else that fits) does not suit dictionary types. Instead install django-picklefield and change type to PickledObjectField

from picklefield.fields import PickledObjectField

class Data(models.Model):
    dict1 = PickledObjectField()
    dict2 = PickledObjectField()
    dict3 = PickledObjectField()
    dict4 = PickledObjectField()

Upvotes: 1

Related Questions