J. Sax
J. Sax

Reputation: 15

NameError: name 'django_filters' is not defined

I am trying to use the Django package: Django Filter I installed it via Pip, made sure I was running supported versions of Python(3.6), and Django(2.0), but whenever I try to run my application, I get the following error:

class Table1(models.Model, django_filters.FilterSet):
NameError: name 'django_filters' is not defined

Here's a sample of my code, with the names changed to protect my work.

models.py:

from django.db import models
from django.contrib.postgres.search import SearchVectorField, SearchQuery
from django_filters import FilterSet



class Table1(models.Model, django_filters.FilterSet):
    field1 = models.IntegerField(db_column='field1', blank=True, null=True)  
    field2 = models.NullBooleanField(db_column='field2')  
    field3= models.IntegerField(db_column='field3', blank=True, null=True)  
    field4= models.TextField(db_column='field4', blank=True, null=False, primary_key=True)  

    #def __str__(self):
     #   return self.sid

    class Meta:
       managed = False
       db_table = 'Table1'
       unique_together = (('field1', 'field2', 'field3', 'field4'),)

filters.py:

from .models import Table1
import django_filters

class Table1Filter(django_filters.FilterSet):
    class Meta:
        model = Table1
        fields = ['field1', 'field2', 'field3', 'field4']

views.py:

from django.shortcuts import render 
from django_tables2 import RequestConfig
from django_tables2.export.export import TableExport
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.template import RequestContext
from django.views.generic import *

from .models import *
from .tables import *
from .forms  import *
from .filters import Table1Filter

def table1(request):
    filter = Table1Filter(request.GET, queryset=Table1.objects.all())
    return render(request, 'table1.html', {'filter': filter})

I wrote some basic filtering stuff manually and then realized that Django Filter(s) was a thing and figured I shouldn't reinvent the wheel. The goal with this is to display data from an exisiting database and allow the end user to filter it. If there's a better way to do this, I am all ears. Thanks for your input, and taking the time to read this!

Upvotes: 1

Views: 6396

Answers (2)

andilabs
andilabs

Reputation: 23351

Your problem is probably in circular imports...

in models.py you import from django_filters import FilterSet then you import in fitlers.py one of models from models.py and the same time django_filters.

This may causing problems. I guess you don't need importing that library and FilterSet in your models.py

Upvotes: 0

hspandher
hspandher

Reputation: 16753

Perhaps because you haven't imported django_filters in your models.py file.

import django_filters # instead of django_filters import FilterSet

or use it the other way around.

Upvotes: 2

Related Questions