Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model field verbose name in template array
How would you approach getting a Field verbose name to show up in a template when you are iterating over the fields via a custom array? Suppose you have #models.py class Letter (models.Model): a = models.CharField(max_length=1, verbose_name=u'The Letter and Vowel A') b = models.CharField(verbose_name=u'The Letter and Consonant B') ... y = models.CharField(verbose_name=u'The Letter, Consonant, and sometimes Vowel Y') def vowel_array(self): return [self.a,self.e,self.i,self.o,self.u,self.y,] # [a,e,i,o,u,y] # but there is no context to the field name (model.a, model.e, ...) nothing special in the view: ... return render(request, 'app/view.html', { 'language' : language, 'letters' : letters, }) and in the template {% for letter in letters.vowel_array %} <div>{{letter}}:{{letter.verbose_name}}</div> <!-- for 'a' => A:The Letter and Vowel A --> {% endfor %} The trouble I am having in this answer is that I don't know how to pass the context of the 'field_name' in the iterated function. ie {% get_verbose_field_name letters "which_letter_model_field_name" %} My current implementation seems problematic? def vowel_array(self): return [ [self.a, self._meta.get_field('a').verbose_name.title()], [self.e, self._meta.get_field('e').verbose_name.title()], [self.i, self._meta.get_field('i').verbose_name.title()], [self.o, self._meta.get_field('o').verbose_name.title()], [self.u, self._meta.get_field('u').verbose_name.title()], [self.y, self._meta.get_field('y').verbose_name.title()] ] and {% for letter in letters.vowel_array %} <div>{{letter.1}}</div> <!-- for 'a' => The Letter and Vowel A --> {% endfor %} Notes : using Django 1.11 and Python 2.7 -
Different languages in django WITHOUT using translation
I want a project in english and spanish, but I want to have MY translations inst of using django's. So, is it possible and practical? Where would these copies be located and how do I switch betweem them in my templates? How do I work with my database for translations? Do you think django's translator works well and maybe I'd better use it? -
Django bulk_create pairs of one-to-one objects
I have pair of one-to-one relationships, say: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(models.Model): place = models.OneToOneField(Place, on_delete=models.CASCADE) Suppose I want to (in my view) create several Restaurants at once, but these restaurant don't have associated Places yet. Is it possible to use bulk_create in such a way (i.e. using only O(1) queries)? Unfortunately I am stuck with MySQL, so I can't simply bulk_create the Place and access that ID list. -
Django, UnboundLocalError: local variable 'nombre' referenced before assignment in view.py
im having a problem with a with a post request of a form, this is how the models.py is: class Invitaciones(models.Model): class Meta: verbose_name_plural = "Invitaciones" tipos_cedula = ( ("Venezolano", "Venezolano"), ("Extranjero", "Extranjero"), ) estados = ( ("Disponible", "Disponible"), ("Usado", "Usado"), ) def random_string(): return str(random.randint(10000, 99999)) año = int(datetime.datetime.now().year) nombre = models.CharField(max_length=300, null=False, blank=False) apellido = models.CharField(max_length=300, null=False, blank=False) tipo_cedula = models.CharField(choices=tipos_cedula, max_length=50, null=False, blank=False) cedula = models.PositiveIntegerField(null=False, blank=False) codigo = models.CharField(max_length=99999999, default = random_string, null=False, blank=False, editable=False) usuario = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) estado = models.CharField(max_length=250, choices=estados, default="Disponible", null=False, blank=False) fecha = models.DateField(default=timezone.now, validators=[validators.MaxValueValidator(datetime.date(año, 12, 31),message="No puedes elegir una fecha que este mas alla de este año"), validators.MinValueValidator(datetime.date.today(),message="No puedes elegir una fecha anterior a la de hoy")]) envio = models.DateField(auto_now=True) def __str__(self): return '%s %s %s %s %s' % (self.usuario, self.nombres, self.apellidos, self.cedula, self.codigo,) And this is how the views.py is: from cuentas.models import Invitaciones from cuentas.forms import InvitacionesForm from django.views.generic import TemplateView from django.contrib import messages from django.shortcuts import render, redirect, HttpResponse, render_to_response class InvitacionesView(TemplateView): template_name = 'socios/pases.html' def get(self, request): form = InvitacionesForm() invitaciones = Invitaciones.objects.all() args = {'form': form, 'titulo': 'Pases de Invitación', 'invitaciones': invitaciones} return render(request, self.template_name, args) def post(self, request): form = InvitacionesForm(request.POST) … -
django ORM AND-lookups on ManyToMany
How do I implement AND-lookups on Q() of the same field. I tried: Foo.objects.filter(Q(name='any'), Q(name='some')) and Foo.objects.filter(Q(name='any') & Q(name='some')) However they both deliver empty querysets. I am aware, that this will work: Foo.objects.filter(name='any').filter(name='some') However when creating more complex queries where Q1, Q2, Q3 are Q() objects then Foo.objects.filter(Q1).filter(Q2).filter(Q3) could deliver different results than Foo.objects.filter(Q2).filter(Q3).filter(Q1) due to the order in which the filter is applied. -
Django accessing CHOICES = () from Model
Just wondering, I have the following model schema: class Location(models.Model): SERVICE_CHOICES = ( ('bus_station', 'Bus Station'), ('cafe', 'Café'), ('cinema', 'Cinema'), ('gardens', 'Public Gardens'), ('library', 'Library'), ('public_services', 'Public Services'), ('railway_station', 'Railway Station'), ('restaurant', 'Restaurant'), ('school', 'School'), ('shop', 'Shop'), ('supermarket', 'Supermarket'), ('tourist_attractions', 'Tourist Attractions'), ('transit_station', 'Transit Station'), ('walks', 'Walks'), ('woodland', 'Woodland'), ) title = models.CharField("Title", max_length=60, default='') description = models.TextField("Description") service_type = models.CharField("Service Type", max_length=80, choices=SERVICE_CHOICES, default='public_service') I'm just wondering how I would loop over the SERVICE_CHOICES tuple list on the frontend template? {% for service_choice in location.SERVICE_CHOICES %} ? -
create OleFile type file from uploaded file
So I am using Message class from this repo to parse .msg file. I have a test file that works with that class. I am trying to use that class in custom parser I am writing for my Django rest framework app. But when I read stream.body, it additionally adds the following content ----------------------------488071469102781097692083 Content-Disposition: form-data; name="file"; filename="email_test.msg" Content-Type: application/vnd.ms-outlook < actual content here > ----------------------------488071469102781097692083-- and I have a doubt that, because of this additional content, Message class is throwing following error. not an OLE2 structured storage file Is my doubt right? How do I solve this? -
Dynamically set the attributes of a class in python [duplicate]
This question already has an answer here: How do you programmatically set an attribute? 3 answers I have a Django model defined as follows: class Customer(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128, blank=False, null=False) address = models.CharField(max_length=256, blank=False, null=False) Can I dynamically set the attributes of the class using a dictionary like this? # cleaned_data is a dictionary for key, value in cleaned_data.items(): if customer.get(key) != value: # how do I check this? customer.set(key) = value # how do I set the attribute here? I've tried the following: >>> customer = Customer() >>> key = 'first_name' >>> value = 'Aby' >>> eval('customer.' + eval('key') + '=' + "'" +eval('value')+ "'") Traceback (most recent call last): File "<console>", line 1, in <module> File "<string>", line 1 customer.first_name='Aby' ^ SyntaxError: invalid syntax -
Django Import Excel Endpoint
I'm trying to create an endpoint for loading an excel file into server and importing the data in it. To do it I'm using django-import-export package. This is the view code: def create(self, request, *args, **kwargs): file_serializer = self.get_serializer(data=request.data) file_serializer.is_valid(raise_exception=True) if file_serializer.is_valid(): from tablib import Dataset from workflows.submittals.admin import ItemImportResource item_model_resource = ItemImportResource() file_serializer.save() dataset = Dataset() file_obj = request.FILES['file'] imported_data = Dataset().load(open(file_obj).read()) result = item_model_resource.import_data(dataset, dry_run=True) if not result.has_errors(): item_model_resource.import_data(dataset, dry_run=False) return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) When loading the file into the (tablib) Dataset, I'm getting this error: 'invalid file: <InMemoryUploadedFile: Import_Sample_test1.xls (application/vnd.ms-excel)>' I tried reffering the name of the file, so replaced imported_data = Dataset().load(open(file_obj).read()) with imported_data = Dataset().load(open(file_obj.name).read()) Then it seems like the Dataset does loads the file, because in the response I see some byte representation of the file, but I also get this error message: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) Any idea? -
How do I render a Django template when there are many models?
I have this hierarchical order of models: courses, study programmes, departments and faculties. I have 2 columns in bootstrap. First column lists all faculties, with their specific departments and the study programmes of each department. Second column lists all courses. I want that when someone clicks on a faculty,to display the specific courses for that faculty in the second column by replacing all courses, same for departments or study programmes. Now, I tried something, but I don't know how to achieve this result. I don't know how to list courses for each faculty, as you can notice, I put faculties.0 as a test. <script> $('#btnClick').on('click', function () { if ($('#1').css('display') != 'none') { $('#2').show().siblings('div').hide(); } else if ($('#2').css('display') != 'none') { $('#1').show().siblings('div').hide(); } }); </script> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <ul> {% for faculty in faculties %} <li id="btnClick">{{ faculty.name }}</li> <ul> {% for department in departments %} {% if department.faculty == faculty %} <li>{{ department.name }}</li> <ul> {% for study in studies %} {% if study.department == department %} <li>{{ study.name }}</li> {% endif %} {% endfor %} </ul> {% endif %} {% endfor %} </ul> {% endfor %} </ul> </div> </div> <div class="col-md-9"> … -
Confused about how TimedRotatingFileHandler rollover works
I have an issue about how rollover occurs in a TimedRotatingFileHandler logging setup in a remote Django server. I have log files setup in this configuration, to rotate itself to a new log file and date stamp the old file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'deals.vip_session': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': 'sessions.log', 'when': 'midnight', 'interval': 1, 'backupCount': 7, }, ... What I am confused about is how the date rollover is handled. According to the documentation: If delay is true, then file opening is deferred until the first call to emit(). This implies that the default setting of delay=False would automatically create the new file at midnight exactly on the web server. In practice, I am seeing that the new log file is not created until the first write operation past midnight is executed. If I am mis-understanding how this function works, then the documentation is not being very clear here. I would prefer a file being created at midnight exactly over waiting for a write operation that may never come. (I have some log files set aside for specific events that may not occur within a 24 hour cycle). I=Can someone clarify my mis-understanding … -
Django: How to detect inactivity session time out?
I am using django.auth.db connection and have created a table which contains username of a user who is logged in and when the user logged out manually (by clicking logout button) I am removing his/her username from that table. The problem arises when a user logged out due to session out and I am not able to remove his/her username from that table. So I wanted to know that is there any way to detect when the users' session/cookies out so that I can remove his/her username from that table? -
Django How in inline Foreign key data can not add can only see
Django How in inline Foreign key data can not add can only see -
Cycle thru a ModelForm fields and indetify FileField and ImageField
I'm creating a generic save method for a form. In the save I want to iterate over the field and if the field is an instance of FileField to to some operations def save(self, commit=True): obj = super().save(commit=False) for field in self.fields: if isinstance(field, forms.FileField) and obj: This is not working because, if I check the type of field is str. How can I get the real model type ? -
Django:datepicker is not a function error in modal but works fine on normal template
I get this error in Chrome console. I have been working for hours to fix it but couldn't. I am new to all of this. My first website: VM86540:37 Uncaught TypeError: $(...).datepicker is not a function at HTMLDocument.eval (eval at <anonymous> (jquery-1.11.3.min.js:2), <anonymous>:37:21) at j (jquery-1.11.3.min.js:2) at Object.add [as done] (jquery-1.11.3.min.js:2) at m.fn.init.m.fn.ready (jquery-1.11.3.min.js:2) at new m.fn.init (jquery-1.11.3.min.js:2) at m (jquery-1.11.3.min.js:2) at eval (eval at <anonymous> (jquery-1.11.3.min.js:2), <anonymous>:30:3) at eval (<anonymous>) at jquery-1.11.3.min.js:2 at Function.globalEval (jquery-1.11.3.min.js:2) My modal code: {% load staticfiles %} <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'flatly.css' %}"> <link rel="stylesheet" href="{% static 'main.css' %}"> <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script> $(function() { var date1 = new Date; date1.setHours(0, 0, 0, 0); date1.setDate(10); var date2 = new Date; date2.setHours(0, 0, 0, 0); date2.setDate(23); $("#datepicker").datepicker({ beforeShowDay: function(date) { return [date < date1 || date > date2, ""]; } }); }); </script> </head> <body> <div class="row"> <form action="" method="post" accept-charset="utf-8" class="form" role="form"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="title-doc">Add a Patient</h4> </div> <div class="modal-body"> {% csrf_token %} <div class="row"> <input id="datepicker" type="text"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button class="btn btn-primary " type="submit">Add</button> </div> </form> </div> </body> … -
Django 1.11 - Static files not served - PythonAnywhere
I am deploying a django 1.11 app to a PythonAnywhere enviroment. The settings file has 'django.contrib.staticfiles' added to the INSTALLED_APPS and the static config STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_col') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] Folder structure of static folder: ├── css ├── fonts ├── img ├── jquery.templates └── js └── jquery When developing the app locally I was using "/static/jquery.templates/jquery.templates.js" without problems when doing manage.py runserver, but it doesn't work in deployment where I got no static files served whatsoever. I executed manage.py collectstatic which worked without errors, but it moved the folder "jquery.templates" to js one: static_col/ ├── admin ... ├── css ├── fonts ├── img └── js ├── jquery └── jquery.templates Problem The other static files are served, apparently, but the problem is that the link /static/js/jquery.templates/jquery.templates.js is not found. Obviously neither the /static/jquery.templates/jquery.templates.js link does not work. I have not idea how to approach this. Serving static files is a pain with Django and I haven't found yet a working guide for this. Thank you -
django admin 2 stacked inline
I have 3 models: Book, Chapter (with FK to Book) and Sentence (with FK to Book and Chapter). Is there a way to show in the admin site of a book, all the chapters it has (I know it is with inlines) BUT also the Sentences each Chapter has? Of course I want it all to be in the view of each book, so only the model Book would be registered in the admin. It would be great to show all chapters, and once you click, all sentenes are shown, is that even possible? -
Abstract user django migration error
I am trying to add two fields to user model of Django. Migrations and models are: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_prostudent = models.BooleanField( default=False ) is_teacher = models.BooleanField( default=False) My migration looks like this: # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-02-11 11:07 from __future__ import unicode_literals import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('students', '0005_auto_20180118_1508'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('is_prostudent', models.BooleanField(default=False)), ('is_teacher', models.BooleanField(default=False)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions … -
Django 2 + PostgreSQL FullText search not matching what it should
I am experiencing a problem I hope someone can enlighten me about. I need to perform a full-text search on a table with multiple columns and sorting the results by rank, using Django 2 and PostgreSQL 10.1. So far this is my code: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector # other unrelated stuff here vector = SearchVector("very_important_field", weight="A") + \ SearchVector("tags", weight="A") + \ SearchVector("also_important_field", weight="B") + \ SearchVector("not_so_important_field", weight="C") + \ SearchVector("not_important_field", weight="D") query = SearchQuery(search_string, config="italian") rank = SearchRank(vector, query, weights=[0.4, 0.6, 0.8, 1.0]). # D, C, B, A full_text_search_qs = MyEntry.objects.annotate(rank=rank).filter(rank__gte=0.4).order_by("-rank") The strange fact is that some search_string return nothing as a result, while if I perform a simple query such as SELECT * FROM my_entry WHERE very_important_field LIKE '%search_string%' OR tags LIKE '%search_string%' OR ... I get tons of results, also if I limit the search just to the important fields. I already tried to play with filter(rank_gte=0.4) and also removing it. Still same result. As of now I am not using GIN o GIST indexing, since I am just experimenting. Any clues about what am I missing? Thanks in advance -
multiple values for keyword argument when using **kwargs
The arguements of _mget_search function are - def _mget_search(query, with_scores=False, count=False, record_term=True, **kwargs): I am calling this function in this way - _mget_search(**search_kwargs) I printed the search_kwargs and it contains this - {'count': False, 'min_score': 20, 'end': 49, 'with_scores': False, 'start': 0, 'query': u'ouuuuu', 'max_score': inf, 'record_term': True} I am getting this error - _mget_search() got multiple values for keyword argument 'query' I am unable to understand why it is happening and how to correct it. -
operational error: no such table django Every Time I create models
I am using Django 2.0, Python Every Time I am creating new Model when I do python3 manage.py makemigrations it shows no changes detected and on migrate no migrations to apply Even I tried python3 manage.py makemigrations home shows Migrations for 'home': home/migrations/0001_initial.py - Create model FAQ - Create model Topic and then on python3 manage.py migrate home It still shows Operations to perform: Apply all migrations: home Running migrations: No migrations to apply. and when I try to open that table in admin. it shows OperationalError at /admin/home/faq/ no such table: home_faq however it'd worked when I'd deleted migrations and database and re migrated everything. But I can't delete everything Every Time. my models.py from django.db import models # Create your models here. class Topic(models.Model): topic_title = models.CharField(max_length=200,unique=True) topic_discription = models.TextField() no_of_posts = models.IntegerField() def __str__(self): return self.topic_title class FAQ(models.Model): question = models.CharField(max_length=800,unique=True) answer = models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) author = models.CharField(max_length=100) author_info = models.TextField() def __str__(self): return self.question I've registered it on admin.py from django.contrib import admin from .models import Topic,FAQ # Register your models here. admin.site.register(Topic) admin.site.register(FAQ) -
redirect() can't seem to working properly
redirect function can't seem to be working though the data entered seemed to be saved to the database. Already tried putting in absolute url from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login from django.views.generic import View from .forms import UserForm from .models import Album class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' title = "Register" def get(self,request): form = self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) #normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns user objects user = authenticate(username = username ,password = password) if user is None: if user.is_active: login(request,user) return redirect('index') #This line though return render(request,self.template_name,{'form':form}) -
The urlpatterns generated by Django vs their official page
In the official documentations of Django, the urlpatters have an incipit of "path" The Django generated urls.py, it has an incipit of "url". This makes it hard for me to follow tutorials, could you tell me how this is possible? I'm having problems making urlpatters. Thank you in advance! -
Get corresponding time and value from json using Djangon (python2)
The following is a sample of the JSON that I'm fetching from the source. I need to get certain values from it such as time, value, value type. The time and value are in different arrays and on different depth. So, my aim is to get the time and value like for value 1, I should get the timestamp 1515831588000, 2 for 1515838788000 and 3 for 1515845987000. Please mind that this is just a sample JSON so ignore any mistakes that I may have made while writing this array. { "feed":{ "component":[ { "stream":[ { "statistic":[ { "type":"DOUBLE", "data":[ 1, 2, 3 ] } ], "time":[ 1515831588000, 1515838788000, 1515845987000 ] } ] } ] }, "message":"", "success":true } Here is a function, that I have written to get the values but the timestamp that I'm getting on the final step is incorrect. Please help to resolve this issue. get_feed_data() is the function that is giving the above JSON. # Fetch the component UIDs from the database component_uids = ComponentDetail.objects.values('uid') # Make sure we have component UIDs to begin with if component_uids: for component_uid in component_uids: # Fetch stream UIDs for each component from the database stream_uids = StreamDetail.objects.values('uid').filter(comp_id=ComponentDetail.objects.get(uid=component_uid['uid'])) for stream_uid … -
Using Sql and MongoDb with Django rest framework for apis
I am new to django and it to use sql db as default but also connect it to mongoldb. In my models.py i from mongoengine import Document, EmbeddedDocument, fields class ToolInput(EmbeddedDocument): name = fields.StringField(required=True) value = fields.DynamicField(required=True) class Tool(Document): label = fields.StringField(required=True) description = fields.StringField(required=True, null=True) inputs = fields.ListField(fields.EmbeddedDocumentField(ToolInput)) In my serializers.py I have :- from .models import Tool from rest_framework_mongoengine import serializers as mongoSerializers from .models import Tool class ToolSerializer(mongoSerializers.DocumentSerializer): class Meta: model = Tool fields = '__all__' In my api.py I have :- from .serializers import ListSerializer, CardSerializer, ToolSerializer from rest_framework.generics import ListAPIView from rest_framework_mongoengine import viewsets as mongoViewsets from .models import List, Card, Tool class ToolApi(mongoViewsets.ModelViewSet): #lookup_field = 'id' queryset = Tool.objects.all() serializer_class = ToolSerializer In my urls.py I have :- from django.conf.urls import include, url from .api importToolApi urlpatterns = [ url(r'Tool', ToolApi.as_view({'get': 'Tool'})), ] When I hit this api, error says :- 'ToolApi' object has no attribute 'Tool' Earlier I was using ListAPIView class from rest_framework.generics to create api to acess data from sql. Is the error because I have used ModelViewSet for ToolApi? PS - Please refer me to some git project using both mongoldb and sql