Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"NoReverseMatch at" error when serving django site in iframe
My live site is running using Python (3.6.7), Django (2, 1, 0, 'final', 0), Nginx(1.14.0 (Ubuntu)) , Gunicorn (19.9.0), and Ubuntu (18.04.2 LTS) . Accessing the site outside of an iframe works as expected. Inside an iframe, I get the following error when trying to redirect: NoReverseMatch at /landing/ Reverse for '' not found. '' is not a valid view function or pattern name. Iframe setup: <iframe src="https://my-url/" ></iframe> Most things I've seen, reference the middleware as a potential solution to working in iframes (https://docs.djangoproject.com/en/2.2/ref/clickjacking/). This is my current Middleware setup in the settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] I've exempted the views that I want to be able to serve from the iframe. By following the suggested approach: from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def ok_to_load_in_a_frame(request): return HttpResponse("This page is safe to load in a frame on any site.") Expected result is the behavior in the iframe to be the same as accessing the site from it's allowed domain. Actual result in the iframe is that the initial view loads, but fails with the following error when trying to redirect to any other view within the iframe: NoReverseMatch at /otherview/ Reverse … -
How to use the Box-API in Django Framework
I am trying to create a web application using the Django framework (I am a beginner in web application creation and Django), and wanted to use the Box-api to access media/mp3 files. I need to authenticate using OAuth2, and I tried following the directions on this page (https://developer.box.com/docs/authenticate-with-oauth-2) but I am not sure where the blocks of code is supposed to go. For example, I assumed # Auth config client_id = 'YOUR CLIENT ID' client_secret='YOUR CLIENT SECRET' redirect_uri = 'http://127.0.0.1:5000/return' would go under settings.py, but I am not sure about the other chunks of code like from boxsdk import Client from boxsdk import OAuth2 import config_oauth # Create new OAuth client & csrf token oauth = OAuth2( client_id=config_oauth.client_id, client_secret=config_oauth.client_secret ) csrf_token = '' or global csrf_token auth_url, csrf_token = oauth.get_authorization_url(config_oauth.redirect_uri) return redirect(auth_url) and # Fetch access token and make authenticated request @app.route('/return') def capture(): # Capture auth code and csrf token via state code = request.args.get('code') state = request.args.get('state') # If csrf token matches, fetch tokens assert state == csrf_token access_token, refresh_token = oauth.authenticate(code) # PERFORM API ACTIONS WITH ACCESS TOKEN I think these should go under views.py but I get some syntax errors when I do so. Any help … -
How to receive Base64 string with django rest
I'm trying to receive an image as a base64 string through Django REST API and use it in my OpenCV image recognition program I've written up a program but it doesnt seem to be working at all views.py class ImageRecog(generics.ListAPIView): # API to query uploads serializer_class = ImageDBSerializer lookup_field = 'image_tags' def get_queryset(self): image_encoded = self.request.query_params.get('image') fh = open("imageToSave.png", "wb") fh.write(image_encoded.decode('base64')) fh.close() # location of the photo we want to test out original = cv2.imread(r"imageToSave.png") sift = cv2.xfeatures2d.SIFT_create() kp_1, desc_1 = sift.detectAndCompute(original, None) index_params = dict(algorithm=0, trees=5) search_params = dict() flann = cv2.FlannBasedMatcher(index_params, search_params) # Load all the images all_images_to_compare = [] titles = [] # location of all the photos # image store directory for f in glob.iglob(r"C:\Users\User\Desktop\django\StudyHome\studybuddy\*"): #directory of where images gets gaved from database image = cv2.imread(f) titles.append(f) all_images_to_compare.append(image) # 1) Check if 2 images are equals for image_to_compare, title in zip(all_images_to_compare, titles): if original.shape == image_to_compare.shape: difference = cv2.subtract(original, image_to_compare) b, g, r = cv2.split(difference) if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0: print("Similarity: 100% (equal size and channels)") print("Title: " + title) return ImageDB.objects.filter(title__iexact=title) break urls.py url('^image/$', ImageRecog.as_view()), # Upload search Api serializers.py class ImageDBSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ImageDB fields … -
Integrating Face Recognition System Using Opencv In Browser
I wanted to integrate a facial recognition inside my website i.e inside a browser using OpenCV Python and I was wondering how can that be achieved? I have surfed the internet and solutions I got are through using tensorflow.js but I don't know how to use it. So I figured, there could be an easier way instead of using tenorflow.js. Using OpenCV Python, I know how to identify a face via webcam run by the OpenCV. But I want the frame to appear inside my broswer(website). What I want to achieve is a face recognition that works inside my website i.e browser. -
How do you set up djangorestframework views with drf-writable-nested serializers?
How do you set up djangorestframework views with drf-writable-nested serializers using the fewest lines of code? Its docs show how to set up the serializers, but not the views or viewsets. I'm using djangorestframework 3.9.2 and drf-writable-nested 0.5.1. I tried the equivalent of: from rest_framework import routers, viewsets class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) (The UserSerializer is a WritableNestedModelSerializer defined in their docs.) However, this code doesn't allow POST, which seems odd. That's what would be used for create, right? This post shows setting up nested serializers, but it doesn't use drf-writable-nested serializers or viewsets. This question and this one don't use drf-writable-nested. (I also want create_or_update semantics to make it easier for the client to just give its data, but that may be another post.) -
How to create a periodic table dynamic in a web site using Django or some library? or using react js with yarn and Node
I need to build a web application for proposals and want to display with some UI like react show an Periodic Table(Chemistry) in my web site -
How to track ListView, other views and urls via Mixins in Django App
Friends, I have a Django app and I want to add some basic tracking for all my views. (Much like a counter or something similar) What I have so far is that I can track specific objects with mixins. So every time someone is clicking on an instance of my model (the DetailView) an entry is added to my database. I did this via the django content types. Now, to do this I need a get method to actually get a specific object back. But in my ListView I don't have that object. How could I implement something similar for either urls or just my ListView? Is that even possible? Here is what I have so far: my views class ListJobView(ObjectViewMixin, ListView): model = Job context_object_name = 'jobs' template_name = 'list_jobs.html' ordering = '-pub_date' # paginate_by = 1 class DetailJobView(ObjectViewMixin, DetailView): model = Job template_name = 'detail_job.html' queryset = Job.objects.all() def get_object(self): id = self.kwargs.get("id") return get_object_or_404(Job, id=id) my mixin from .signals import object_viewed_signal class ObjectViewMixin: def dispatch(self, request, *args, **kwargs): try: instance = self.get_object() except self.model.DoesNotExist: instance = None if instance is not None: object_viewed_signal.send(instance.__class__, instance=instance, request=request) return super(ObjectViewMixin, self).dispatch(request, *args, **kwargs) my signal from django.dispatch import Signal object_viewed_signal … -
Not getting token in the response from the react app.js fetch
I am linking django to react. I am trying to get the token from a Django-rest-framework endpoint http://127.0.0.1:8000/api/get-token which is using a tokenAuthentication, from react app.js . I have set up corsheaders and restframework all that. when I hit the endpoint through the command line with a token it works. Now I need the token in my react app.js. I get a response with status 200 but I can't find the token. As I am new to react I am not sure if I am missing something. //App.js componentDidMount() { try { const data = {username: 'user', password: 'password'}; fetch('http://127.0.0.1:8000/api/get-token/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(data) }).then(function(response) { console.log(response.token); }) } catch (e) { console.log(e); } } Let me know if you need more info I have tried both TokenAuthentication and BasicAuthentication in my settings.py REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], ... } -
django filter - How to search a phone number form 3 columns
Here is my model: HomePhone = models.CharField(max_length=12, null=True) Phone2 = models.CharField(max_length=12, null=True) Phone3 = models.CharField(max_length=12, null=True) Here is the filter: class optionFilter(django_filters.FilterSet): class Meta: model = option2019 fields = { 'LastName': ['icontains',], 'FirstName':['icontains',], 'aidecode':['exact',], 'SSN':['icontains',], 'HomePhone':['exact',], } From the model, every one would have 3 phone numbers. How do I get the filter to look for all 3 phone number columns and return all info for the 1 person? Thank you! -
How to take html input and use it in views.py?
I checked documentation and stack, but still can't make it. I want button from html to grab input data and inject to views.py as a city and make rest of the code which works when I hardcode city variable. And It shouldn't be made on new url. Thanks for help! html: <form method="POST "action="{% url 'weather' %}"> {% csrf_token %} <input type="text" name="city" id="city"><br> <button type="submit" class="btn btn-info">Get my weather</button> </form> views.py: def scrape_weather(request): if request.method == 'POST': old_weather = Weather.objects.all() old_weather.delete() api_adress = "http://api.openweathermap.org/data/2.5/weather?q=" api_key = "&appid=3a99cf24b53d85f4afad6cafe99d3a34" city = request.POST.get("city") url = api_adress + city + api_key json_data = requests.get(url).json() new_weather = json_data['weather'][0]['main'] degree_kelvin = int(json_data['main']['temp']) degree = degree_kelvin-273 pressure = json_data['main']['pressure'] new_weather = Weather() new_weather.degree = degree new_weather.pressure = pressure new_weather.weather = new_weather new_weather.save() return render(request, "news/home.html") urls.py: path('weather/', scrape_weather, name='weather'), -
Create formset using a queryset. Update the queryset and then return render.....works sometimes
I'm trying to create a page where a user is given a batch of 'Ads' to label using a formset. I don't want more than one user to both be given the same ad to work on at the same time so I have some logic to assign those ads to the user for a period of time. To do this, I grab a queryset of ads which need to be labeled. I then want to update the queryset to set their expiration time and the user's info so that the ads won't appear in another user's queryset. The code works as I expect when I have a random debug print() statement in there. It does not work as expected when I remove the print() statement. Here's the view code: def label_batch_view(request): AdFormSet = modelformset_factory(Ad, can_delete=False, extra=0, fields=('category', 'labeler', 'labeler_expiration', 'image_url')) if request.method == "POST": formset = AdFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() else: batch = Ad.objects.filter( (Q(labeler_expiration__lt = (datetime.now() - timedelta(minutes=60))) | Q(labeler_expiration__isnull=True)) & Q(category__isnull=True) ) formset = AdFormSet(queryset=batch) print(formset) batch.update(labeler=request.user.labeler, labeler_expiration=(datetime.now() + timedelta(minutes=45))) return render(request, 'label_ads_batch.html', {'formset': formset})``` When I leave the code as-is w/ the "print(formset)" in, the page returns the set of ads I am hoping to … -
CSV Download of User Info Django
I am trying to download some user data into a csv file. I am able to generate the User fields just fine but when I try to access the onetoone relation field I am running into issues! Tried numerous different way to get here. Just can't seem to figure out how to get the correct related data. def export_to_csv (modeladmin, request, queryset): try: from StringIO import StringIO except ImportError: from io import StringIO from wsgiref.util import FileWrapper cols = ['username','email','first_name','last_name','my_profile.dealer_num'] # get qs values data = list( queryset.values_list(*cols) ) if not data: messages.error(request, 'No data to export') return HttpResponseRedirect( request.get_full_path() ) # create empty csv csv_file = StringIO() csv_writer = csv.writer(csv_file, quoting = csv.QUOTE_ALL) # add headers csv_writer.writerow( cols ) # add qs values for row in data: csv_writer.writerow( [s.encode('utf-8') for s in row] ) csv_file.flush() csv_file.seek(0) response = HttpResponse(FileWrapper( csv_file ), content_type='text/csv') response['Content-Disposition'] = "attachment; filename=user-csv-export.csv" return response export_to_csv.short_description = "Export to CSV" Models.py class MyProfile(UserenaBaseProfile): user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name='my_profile') dealer_num = models.CharField(blank=True, max_length=15, verbose_name="Dealer Number") Should return everything including a 5 digit dealer number in a csv -
Django Bokeh - Uncaught TypeError: Bokeh.$ is not a function
Bokeh version , bokeh==0.12.3 CDN_Js version , https://cdn.pydata.org/bokeh/release/bokeh-0.12.3.min.js the Bokeh Script JS that gets embedded into the HTML template of Django as below :- Bokeh.$(function(){ Bokeh.safely(function(){ .... I can get the CDN_js and CDN_css to the DOM , but cant seem to get them into the innerHtml / Html of the correct DIV. Rest of the code as below :- <script> var call_bokehBar = "{% url 'call_bokehBar' %}" // var bokeh_text = document.getElementById('dynamic_bokeh_body_text1'); bokeh_text.onclick = function() { $.ajax({ url: call_bokehBar, type: 'GET', dataType: 'json', success: function(resultJSON) { alert(resultJSON) // -- YES OK console.log(resultJSON) // -- YES OK console.log("---------div_bokeh===============") // -- YES OK console.log(resultJSON.div_bokeh) // -- YES OK console.log("---------cdn_js===============") // -- YES OK console.log(resultJSON.cdn_js) // -- YES OK //var bokeh_data = JSON.parse(resultJSON); // Parse == NOT REQUIRED $('#second_bokehDiv').html(resultJSON.div_bokeh); $('#second_bokehDiv').html(resultJSON.js_bokeh); }, // Close == success: function(resultJSON) }) // Close == $.ajax({ }; </script> Code for the Modal that i need to have the Bokeh bar Chart in :- <div id="modal_bokeh_main" class="modal_bokeh_backdrop"> <!-- == modal_bokeh_backdrop == --> <div class="modal_bokeh_content"> <!-- modal_bokeh_content --> <div class="modal_bokeh_header"> <span class="modal_bokeh_close">&times;</span> <h2 id = "dynamic_bokeh_header_text"> BOKEH BAR CHART </h2> </div> <!-- ENDS div == modal_bokeh_header --> <div class="modal_bokeh_body"> <p id = "dynamic_bokeh_body_text1"> BOKEH BAR CHART </p> <br> <!-- … -
Unresolved reference 'addresses' in Pycharm Community Edition
My Pycharm Screenshot Hello, if you can see the attached screenshot of my Django project in Pycharm, you'll see that all the imports from other app folders have a red underline. When I hover mouse on them, it says "Unresolved reference 'addresses'". All the apps have been added to settings.py and the project is running fine without any errors. The red underlines are really bugging me though. What can I do to get rid of them? Thanks! -
Django send_mail() - 'tuple' object has no attribute 'splitlines'
In Django, I'm trying to send an email which contains all variables from a contact form but I get an error when "message" equals more than 1 POST variable. from django.core.mail import send_mail from django.conf import settings def home(request): if request.method == 'POST': message = request.POST['Name'], request.POST['Email'], request.POST['Subject'], request.POST['Message'] send_mail( 'Contact Form', message, settings.EMAIL_HOST_USER, ['django.reviewapp@zohomail.eu'], fail_silently=False ) return render(request, 'reviewApp/home.html', {'title': 'Home'}) -
Twitter API doesn't work in AJAX Success Call
Using Django, I'm building a search function that will subsequently display tweets. Based on user input, the AJAX posts to views, which returns a list of ids that should be used to fetch tweets with the twitter API. When twttr.widgets.createTweet() is called in the AJAX success function, I get: Refused to execute script from https://cdn.syndication.twimg.com/tweets.json?callback=__twttr.callbacks.cb0&ids=%2C%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined%2Cundefined&lang=en&suppress_response_codes=true&theme=light&tz=GMT-0400' because its MIME type ('') is not executable, and strict MIME type checking is enabled." The API call works perfectly when it's called onLoad. I have confirmed that the success function fires. I've tried to change the AJAX datatype, which doesn't work. Ajax call: $.ajax({ url: '/', type: 'POST', datatype : "json", data: { 'search': x, }, success: function(data) { a = data genTweets(a) }); genTweets(which generates elements to populate with tweets): function genTweets(a){ if (a.length < 30){ for (i = 0; i < a.length; i++){ var newDiv = document.createElement("div"); x = String(a[i]) document.body.appendChild(newDiv) newDiv.id = "tweet" + i newDiv.setAttribute("tweetID", x) newDiv.setAttribute("class", "offset-3 col-8") genTweet(newDiv.id) } } } genTweet: genTweet = function(tweet){ var tweet = document.getElementById(tweet); var id = tweet.getAttribute("tweetID"); $('.dropdown-toggle').dropdown('toggle'); twttr.widgets.createTweet( id, tweet) } -
Django CORS on static asset
I'm using Django as a backend, and have run into cross origin issues which I had fixed using the corsheaders package in settings. So far, all my GET endpoints work, thanks to: CORS_ORIGIN_ALLOW_ALL = True However, I'm now trying to access a static file from my front end server on the django backend, located as such: http://localhost:8000/static/image.jpg The browser client however gets the familiar error as before: Access to XMLHttpRequest at ... from origin ... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Any ideas? Thanks -
How to add class to a table from context in Django
I have a html file I am passing from my views.py as a context and I can load up a table in my html by simply writing {{loaded_data|safe}}. However, I want to add a bootstrap class to it so that it is formatted nicely. I've looked through the jinja2 documentation and tried <table class="table"> {{loaded_data}} </table> but none of my attempts worked and I can't seem to find an answer. So my question is: How should I go about formatting my table passed as a context from views.py? -
Bootstrap Datepicker not loading in a specific page - Django
I'm already using Bootstrap Datepicker on my Django project and all is working fine, but I have problems when loading it in a specific page. The package im using is django-bootstrap-datepicker-plus: https://pypi.org/project/django-bootstrap-datepicker-plus/ On all other pages, from the same project, that I use Datepicker works fine, here is an example: On this page, it isn't loading: I really don't know how I can fix this. Here is my index page when I'm loading all: <head> .... <!-- Custom fonts for this template--> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> <link href="{% static 'css/default.css' %}" rel="stylesheet"> <!-- Custom styles for Tables --> <link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> </head> <body> <div id="wrapper"> {% block content %} {% endblock %} </div> <!-- Bootstrap core JavaScript--> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> {% load bootstrap4 %} {# import bootstrap4/bootstrap3 #} {% bootstrap_css %} {# Embed Bootstrap CSS#} {% bootstrap_javascript jquery='full' %} {# Embed Bootstrap JS+jQuery #} {% block extrahead %} {# Extra Resources Start #} {{ form.media }} {# Form required JS and CSS #} {% endblock %} <!-- Core plugin JavaScript--> <script src="{% static 'vendor/jquery-easing/jquery.easing.min.js' %}"></script> <script src="{% … -
How do i get the CKeditor working on my actual Html page from Django admin
I have an issue with rendering what i've made in the admin to my actual Html page with CKeditor I followed the documentation of ckE (collectstatic, makemigrations ect..) this is what i've made with ckeditor admin page and this is what it is displaying. hmtl page setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web_app', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = 'uploads/' # CKEditor Configuration Settings CKEDITOR_CONFIGS = { 'default': { # 'toolbar': 'Custom', 'width': '800px', 'height': 'auto', # 'toolbar_Custom': [ # ['Bold', 'Italic', 'Underline'], # ['NumberedList', 'BulletedList'], # ], } } STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "web_app/static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR models.py from django.db import models from datetime import datetime from ckeditor.fields import RichTextField # Create your models here. class Article(models.Model): title = models.CharField(max_length=200) content = RichTextField() published = models.DateTimeField("date published", default= datetime.now()) image = models.ImageField(upload_to='images/', default="") urls.py (the main one not from the project it self) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('web_app.urls')), path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to share django blog post on whatapp with image
How to share django blog post on whatapp with image,description Plz help me fast -
Streaming OpenCV Human Detection video from python program to Django Webpage
Im currently developing a webpage that allows users to upload a video, run the video through opencv human detection program and display the video feed to a django webpage. I was wondering, is this possible and if possible could you send me in the right direction as ive looked and a lot of the sources ive looked at are just for normal video streams or streaming using flask which i have no experience in many thanks :) -
Django Rest Framework: pass user from view to serializer
I have such view for user change password: class ChangePasswordView(generics.UpdateAPIView): serializer_class = ChangePasswordSerializer permission_classes = [IsAuthenticated] def put(self, request, *args, **kwargs): data = request.data.copy() data['user'] = self.request.user serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] user.set_password(serializer.validated_data["new_password"]) user.save() return Response(status=status.HTTP_204_NO_CONTENT) And serializer for this view looks like this: class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField() new_password = serializers.CharField() new_password_retyped = serializers.CharField() def validate(self, data): old_password = data.get('old_password') new_password = data.get('new_password') new_password_retyped = data.get('new_password_retyped') user = data.get('user') # misc validation checks data['user'] = user return data and my problem is that user object is not being passed to serializer, tried printing it to see content of data inside put: <QueryDict: {'old_password': ['testpassword'], 'new_password': ['testpassword1'], 'new_password_retyped': ['testpassword1'], 'user': [<User: root>]}> and inside serializer: OrderedDict([('old_password', 'testpassword'), ('new_password', 'testpassword1'), ('new_password_retyped', 'testpassword1')]) As you can see, user is missing. First, I thought that it may have something to do with passing object to serializer so I changed data['user'] = self.request.user to data['user'] = self.request.user.username so it would only pass string with username, but with no luck -
HTML5 based mobile application with Django backend
i am new to Django and also mobile app development. I want to develop HTML5 mobile application with django on server side. I would like to know, if i can develop a web application as usual and then transfer it to mobile app, or if the REST framework is needed for this. -
Django Rest - custom serialiser/query - assert queryset is not None
im trying to create a custom serialiser and query based of a dictionary ive build manually in a viewset query set however im receiving the error, which doesn't help me identify which part of my view or serialiser is failing File "/itapp/itapp/api/urls.py", line 12, in <module> router.register(r'ss_monitoring_data', views.SiteSupernetMontioringDataROView) File "/usr/local/lib/python3.6/site-packages/rest_framework/routers.py", line 102, in register basename = self.get_default_basename(viewset) File "/usr/local/lib/python3.6/site-packages/rest_framework/routers.py", line 185, in get_default_basename assert queryset is not None, '`basename` argument not specified, and could ' \ AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. this is my serialiser: class SiteSupernetMonitoringDataROSSerializer(serializers.Serializer): site = serializers.CharField(max_length=50) subnet = serializers.CharField(max_length=50) mask = serializers.CharField(max_length=50) circuits = serializers.CharField() this is the view: class SiteSupernetMontioringDataROView(generics.ListAPIView): permission_classes = (IsAdminUser,) serializer_class = SiteSupernetMonitoringDataROSSerializer paginate_by = 20 def get_queryset(self): site_supernet_data = SiteSupernet.objects.filter(site__is_live=True, subnet_type__subnet_type__icontains='site aggregate').values() dcs_data = DeviceCircuitSubnets.objects.filter( device__site__is_live=True, circuit__decommissioned=False ) \ .select_related( 'device' 'device__site', 'subnet' 'circuit' ).values( 'id', 'subnet_id', 'circuit_id', 'device_id', 'device__site_id', 'circuit__name', 'subnet__subnet', 'subnet__mask' ) for supernet in site_supernet_data: if 'circuits' not in supernet.keys(): supernet['circuits']= [] for dcs in dcs_data: if dcs['device__site_id'] == supernet['site_id']: supernet['circuits'].append(dcs) return site_supernet_data