Muhammad Zubair
Muhammad Zubair

Reputation: 574

ListField not found error in django

I am trying to use mongodb with django. My main poject name is 'mysite' and inside that there is an app named 'blog' and inside blog/models.py, I have written the following portion.

from django.db import models
from djangotoolbox.fields import ListField

class Post(models.Model):
    title = models.CharField()
    text = models.TextField()
    tags = ListField()
    comments = ListField()

I have installed djangotoolbox. When I run the command on python shell

from blog.models import Post

It shows the following error.

>>> from blog.models import Post
 Traceback (most recent call last):
File "<console>", line 1, in <module>
File "E:\Study\mysite\blog\models.py", line 2, in <module>
from djangotoolbox.fields import ListField
File "C:\Program Files (x86)\Python36-32\Lib\site-packages\djangotoolbox\fields.py", line 4, in <module>
from django.utils.importlib import import_module
ModuleNotFoundError: No module named 'django.utils.importlib'
>>>

Why is this error occurring? and what is its solution? Because I have seen all over the internet and could not find any.

Upvotes: 0

Views: 1285

Answers (2)

유소정
유소정

Reputation: 11

You can write

from .models import Post 

Upvotes: 1

Mike Pinkman
Mike Pinkman

Reputation: 169

ListField to override the formfield method:

models.py

from djangotoolbox.fields import ListField
from .forms import StringListField

class TagField(ListField):
    def formfield(self, **kwargs):
        return models.Field.formfield(self, StringListField, **kwargs)

class CommentField(ListField)
    def formfield(self, **kwargs):
        return models.Field.formfield(self, StringListField, **kwargs)

class Post(models.Model):
    title = models.CharField()
    text = models.TextField()
    tags = TagField()
    comments = CommentField()

Then, in forms.py, we define StringListField:

from django import forms

class StringListField(forms.CharField):
    def prepare_value(self, value):
        return ', '.join(value)

    def to_python(self, value):
        if not value:
            return []
        return [item.strip() for item in value.split(',')]

admin.py

from django.contrib.admin import site, ModelAdmin
from models import Post

def tags(instance):
    return ', '.join(instance.tags)

def comments(instance):
    return ', '.join(instance.comments)

class PostAdmin(ModelAdmin):
    list_display = ['title', 'text', tags, comments]

site.register(Post, PostAdmin)

This will covert the comma-separated input box contents into a Python list, and the list value that is fetched from the database int a comma-separated string which is then displayed in the input box.

>>> Post.objects.get(title='foo').comments
[u'foo', u'bar']

Upvotes: 1

Related Questions