Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, HttpResponse, HTML
I have checkboxes after selecting several queries and the page is generated according to the selected checkboxes. question: to use HttpResponse and to make the page in parts, whether it is possible to use a template? -
Getting database error while using django-paypal
Im using Mongodb (djongo engine) for the database for my django project, I can't work out I always get this error when paypal posts to my website: [13/Dec/2021 15:59:44] "POST /paypal/ HTTP/1.1" 500 28196 Internal Server Error: /paypal/ Traceback (most recent call last): File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__ super().__init__(*args) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse self.where = WhereConverter(self, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__ self.parse() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse self.op = WhereOp( File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 475, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op op = ParenthesisOp(SQLStatement(tok), self.query) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op op = ParenthesisOp(SQLStatement(tok), self.query) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 438, in _statement2ops if prev_op.lhs is None: AttributeError: 'NoneType' object has no attribute 'lhs' The above exception was … -
Generator expression must be parenthesized if not sole argument: using join
I'm getting following exception while run the server:- SyntaxError: Generator expression must be parenthesized if not sole argument to the following line: return '\n'.join(' | '.join(value.rjust(width) for value, width in row, widths) for row in table I'm using a Python 3 version. I also tried to upgrade the django but still it returns same exception. Can anyone help me to solve this problem? Thanks in advance. -
404 error : no comment matches the given query
I've searched enough about this problem, but haven't been able to find a solution. Please help me. View.py class comment_delete(DeleteView): model = Comment success_url = reverse_lazy('board_list.html') urls.py path('', views.home, name="home"), path('board/', views.board.as_view(), name="board"), path('board/<int:pk>/', views.board_detail.as_view(), name="board_detail"), path('board_write/', views.board_write, name="board_write"), path('board_insert', views.board_insert.as_view(), name="board_insert"), path('board_edit/', views.board_edit, name="board_edit"), path('board_update/', views.board_update, name="board_update"), path('board_delete/', views.board_delete, name="board_delete"), ####### comment ######### path('board/comment/update/', views.comment_update, name="comment_update"), path('board/<int:pk>/comment/<int:id>/delete/', views.comment_delete.as_view(), name="comment_delete") comment.html <form action="{% url 'comment_delete' pk=i.Board_id id=i.id %}" method='POST'> -
Django save request.POST to JSONField picks last item from list instead of saving the list
I have a view that receives a post request from client.post() data = { "token": create_hash(customer_name), "images": [image_1, image_2], "name": customer_name, "email": "test@email.com", "phone": "0612345678", "product": "product-sku0", "font_family": "Helvetica", "font_size": 12, "colors_used": ( "#AAAAAA|White D", "#FFFFFF|Black C" ) } I am trying to save the post request as a whole to a model.JSONfield(). The post request key-value pair looks like this: 'colors_used': ['#AAAAAA|White D', '#FFFFFF|Black C'] When I save and later retrieve the value it looks like this: 'colors_used': '#FFFFFF|Black C' Instead of saving the nested list in the JSONfield it only saved the last value. I am using SQLite. -
How to properly override get_queryset in a modelviewset without breaking the query by pk?
I have a ModelViewSet: class OrderViewSet(viewsets.ModelViewSet): serializer_class = OrderSerializer pagination_class = DefaultPagination queryset = Order.objects.all() def get_queryset(self): userId = self.request.query_params.get('userId') if userId is not None: query = Order.objects.filter(owner__id=userId).order_by('-createdAt') else: query = Order.objects.order_by('-createdAt') return query Here is the url registration router = routers.DefaultRouter() router.register('api/v1/order', OrderViewSet, basename='order') I found that after overriding the get_queryset, I can no longer query by one order id like the following anymore: /api/v1/order/1,it just returns detail: not found I do see django saying it supports: ^api/v1/order/$ [name='order-list'] ^api/v1/order\.(?P<format>[a-z0-9]+)/?$ [name='order-list'] ^api/v1/order/(?P<pk>[^/.]+)/$ [name='order-detail'] ^api/v1/order/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='order-detail'] what should be the correct way to do this? Thanks! -
Django/React 415 (Unsupported Media Type)
I'm getting POST http://localhost:8000/api/reports/ 415 (Unsupported Media Type) when I try to submit the form from React and I don't understand what's the problem. Here's the code. models.py class Report(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) description = models.TextField() address = models.CharField(max_length=500) reporter_first_name = models.CharField(max_length=250) reporter_last_name = models.CharField(max_length=250) reporter_email = models.CharField(max_length=250) reporter_phone = models.CharField(max_length=250) report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) date = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date',) def __str__(self): return self.description I also tried to put default values for images, but I still get the error. serializers.py class ReportSerializer(serializers.ModelSerializer): categoryName = CategorySerializer(many=False, read_only=True, source='category') class Meta: model = Report fields = '__all__' views.py class ManageReports(viewsets.ModelViewSet): serializer_class = ReportSerializer parser_classes = [MultiPartParser, FormParser] def get_object(self, queryset=None, **kwargs): id = self.kwargs.get('pk') return get_object_or_404(Report, id=id) def get_queryset(self): return Report.objects.all() This is the code responsible for the submit. report.js const initialPostData = Object.freeze({ category: '', address: '', description: '', reporter_first_name: '', reporter_last_name: '', reporter_email: '', reporter_phone: '', }); const [postData, updatePostData] = useState(initialPostData); const [postImage1, setPostImage1] = useState({image: null}); const [postImage2, setPostImage2] = useState({image: null}); const [postImage3, setPostImage3] = useState({image: null}); const handleChange = (e) => { if([e.target.name] == 'reporter_image_1') { setPostImage1({ image: … -
Creating a chart from sentiments of user tweets using chart.js
I’m new to Django. I’m currently doing sentiment analysis on real-time user tweets via Twitter API. I have managed to do the analysis and display the sentiments. Now, I want to visualize the sentiments using charts in my Django app (perhaps bar chart or pie chart) but I’m not sure how. I was thinking of using Chart.js to make it responsive but most of the examples are using static data so I wasn’t successful in integrating my data where I extracted from Twitter API with chart.js. This is a screenshot of my web page. The table was the extracted tweets with their corresponding sentiments. The bar chart however is just static data. I don't know how to convert it into json. enter image description here this is my views.py from django.http.response import JsonResponse from django.shortcuts import render, redirect, HttpResponse from .forms import Sentiment_Typed_Tweet_analyse_form from .sentiment_analysis_code import sentiment_analysis_code from .forms import Sentiment_Imported_Tweet_analyse_form from .tweepy_sentiment import Import_tweet_sentiment from django.contrib.auth.decorators import login_required from django.contrib import messages def sentiment_analysis_import(request): if request.method == 'POST': form = Sentiment_Imported_Tweet_analyse_form(request.POST) tweet_text = Import_tweet_sentiment() analyse = sentiment_analysis_code() if form.is_valid(): handle = form.cleaned_data['sentiment_imported_tweet'] # messages.info(request, 'It might take a while to load the data.') if handle[0]!='#': list_of_tweets = tweet_text.get_hashtag(handle) list_of_tweets_and_sentiments … -
why showing error page is not found while using /<pk>/?
urls.py I tryed allot but can not fond why this happened when I apply or it is always showing the same error from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('nature', views.nature, name ='nature'), path('', views.index, name ='index'), path('footer', views.footer, name ='footer'), path('navebar', views.navebar, name ='navebar'), path('form', views.form, name ='form'), path('venue', views.venue, name ='venue'), path('db/<db_id>/', views.db, name ='db'), views.py from django.shortcuts import render def db(request, db_id): all = Task.objects.get(pk= db_id) return render(request,'MYapp/db.html',{'all': all}) -
Duplicate Django model with nested children
I have a model with nested children and want to duplicate it, I tried some solutions but couldn't solve my problem! here are my models to show the relationships between them: class Form(models.Model): form_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) form_title = models.CharField(max_length=100) class Page(models.Model): page_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) page_title = models.CharField(max_length=100) form = models.ForeignKey(Form, related_name='pages') class Section(models.Model): section_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) section_title = models.CharField(max_length=100) page = models.ForeignKey(Page, related_name='sections') class Question(models.Model): question_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) question_title = models.CharField(max_length=100) section = models.ForeignKey(Section, related_name='questions') class Answer(models.Model): answer_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) answer_value = models.TextField(blank=True) question = models.OneToOneField(Question, related_name="question") I used this solution, I could duplicate the form and pages but couldn't go next for duplicating other children! class DuplicateFormAPI(views.APIView): def get(self, request, form_id): form = Form.objects.filter(form_id=form_id).first() form.form_id = None form.save() duplicated_form_id = FormSerializer(form).data.get('form_id') pages = Page.objects.filter(form_id=form_id).all() for page in pages: page.page_id = None page.form_id = duplicated_form_id page.save() return Response({ "status": status.HTTP_200_OK, "message": "Form duplicated successfully!", "form": FormSerializer(form).data, }) Anyone could help or give me some hints? -
django-filter shows all fields instead of just the ones specified
In my filters.py: class DataFilter(FilterSet): start_date = DateFilter(field_name='date',lookup_expr=('lt'),) end_date = DateFilter(field_name='date',lookup_expr=('gt')) date_range = DateRangeFilter(name='date') class Meta: model = DataModel fields = ['date', ] I have also tried setting fields = [], but filters of all fields are still there. Why is it showing all even I just only specified one (even none)? And how to fix that? Can anyone help explain? Thank you! In my models.py: class DataModel(models.Model): date = models.DateField(default=now) other_field_1 = models.CharField() other_field_2 = models.CharField() other_field_3 = models.CharField() In my views.py: class DataModelListView(LoginRequiredMixin, FilterView): model = DataModel template_name = 'datamodel_list.html' filter_class = DataFilter I am using django 3, django-filter 21. -
Acess dictionary value in template
I have a list view where I define queryset as a list of objects if current user is not a top manager otherwise queryset is a dictionary with key being employee and value being list of objects. So I want to know how to display the key from this dict and then list it's value - a list. I tried to do it like that <ul> {% for k, v in employees_list.items %} <li><a href="{% url 'employees:employees-detail' pk=v.pk %}"> {{ v.title }} {{ v.last_name }} {{ v.first_name }}</a></li> {% endfor %} </ul> It didn't work out. Here's the view class EmployeesListView(LoginRequiredMixin, ListView): model = Employees template_name = 'employees/employees_list.html' context_object_name = 'employees_list' fields = ['last_name', 'first_name', 'title', 'birth_date', 'reports_to'] is_top_manager = False def get_queryset(self): #current_emp = get_current_users_employee(self.request.user) #return super().get_queryset().filter(reports_to=current_emp) current_emp = get_current_users_employee(self.request.user) this_employees_subordinates = Employees.objects.filter(reports_to=current_emp) if str(current_emp.title) != "Top manager": return this_employees_subordinates else: self.is_top_manager = True print("this user is top manager") lower_level_subordinates = {} for subordinate in this_employees_subordinates: lower_level_subordinates[subordinate] = Employees.objects.select_related('title').filter(reports_to=subordinate) print(lower_level_subordinates) return lower_level_subordinates -
Reverse for 'db' with arguments '('',)' not found. 1 pattern(s) tried: ['db/(?P<db_id>[^/]+)/$']
when I am trying to grab items from db.html with the help of id it is showing an error I cant understand where is the problem please help me out venue.html {% extends 'MYapp/index.html' %} {% block content %} <center> <h1> venue.html </h1> <br> <div class="card-header"> Featured </div> <div class="card-body container-fluid"> <h5 class="card-title">Special title treatment</h5> {% for venues in venue_list %} <p class="card-text container-fluid"> <a href="{% url 'db' all.id %}"> {{ venues }} {{ venues.lastname}}</a> {% endfor %} </p> </div> </center> {% endblock %} views.py from django.shortcuts import render from django.http import * from MYapp.models import * from .form import * def index(request): return render(request,'MYapp/index.html') def venue(request): venue_list = Task.objects.all() return render(request,'MYapp/venue.html',{'venue_list': venue_list}) def db(request, db_id): all = Task.objects.get(pk= db_id) return render(request,'MYapp/db.html',{'all': all}) urls.py another error occers hear it is showing page is not found because of this path('db/<db_id>/', views.db, name ='db'), from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('nature', views.nature, name ='nature'), path('', views.index, name ='index'), path('footer', views.footer, name ='footer'), path('navebar', views.navebar, name ='navebar'), path('form', views.form, name ='form'), path('venue', views.venue, name ='venue'), path('db/<db_id>/', views.db, name ='db'), ] -
DJANGO : How to iterate a ListView items to convert in cards
I am coding an app "dash" how a startpoint to many users. "a applications dashboard". I want to convert the list of applications in cards, "portfolio style". the user login in the platform, and in the url .../dash open the dash(django app). To here it's perfect. with the generic view - ListView - we obtain the list of applications will be available in the platform (if exist in the model, the application it's installed and available to the user) urls.py: path('dash/', views.ListView_Dash_Apps.as_view()), views.py: class ListView_Dash_Apps(ListView): template_name = "dash/ListarAplicaciones.html" model = App and in the html template, How to iterate the columns of the object_list??? with this i can iterate the rows, but not the column, i receive the str output declarated in the model. <ul> {% for e in object_list %} <li>{{ e }}</li> {% endfor %} </ul> If i can to read the columns data and include in the html (App, url_app, icon, etc etc..) -
Django and CKEditor as a template
Is it possible to use db variables in ckeditor? for example: My name is : {{ form.name }} My age is : {{ form.age }} and then i can render the ckeditor entry as a template populated by the model. All advice would be appreciated. Thanks. -
django filter on a large list- giving incorrect count or syntax error on ms sql- filtering in chunks is very slow
I am trying to filter records from a model using a list of values: Sample: items= ['a@xyz.com','b@xyz.com','c@abc.com'.......] data= TestModel.objects.filter(email__in=items) items contains more than 2000 entries and the database being used in SQL. To avoid count incorrect error: I tried: data= TestModel.objects.all() chunks = [items[x:x+1000] for x in range(0, len(items), 1000)] for chunk in chunks: chunk_data=Testmodel.objects.filter(email__in=set(chunk)) data= data | chunk_data return data I am not sure if this is the right approach and also the results are very slow. Any suggestions if there is a proper work around to filter data using a large list in django? -
How do I migrate vieys.py file without exceptions?
when Im trying to migrate my my .py file I'm facing an error "^ if request.method == 'POST' SYNTAX ERROR : Invalid character in Identifier error" this is my code def register(request): registered = False if request.method() == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save User Form to Database user = user_form.save() # Hash the password user.set_password(user.password) # Update with Hashed password user.save() # Now we deal with the extra in # Can't commit yet because we still need to manipulate profile = profile_form.save(commit=False) # Set One to One relationship between # UserForm and UserProfileInfoForm profile.user = user # Check if they provided a profile picture if 'profile_pic' in request.FILES: print('found it') # If yes, then grab it from the POST form reply profile.profile_pic = request.FILES['profile_pic'] # Now save model profile.save() # Registration Successful! registered = True else: # One of the forms was invalid if this else gets called. print(user_form.errors,profile_form.errors) else: # Was not an HTTP post so we just render the forms as blank. user_form = UserForm() profile_form = UserProfileInfoForm() # This is the render and context dictionary to feed # back to the … -
Add percent(%) sign in the Django URL
I'm doing API migration part where I have URL with % sign in it. However I want to do the same URL mapping with the Django API URL. I have tried with creating space and also tried creating % sign.I'm getting only 404 URL not matching How could I able to achieve it error msg: The current path, api/Data/CurrentRunningActivity2/10|checkrequest, didn't match any of these. existing .net API URL: http://localhost:1400/api/Data/CurrentRunningActivity2/10%7Ccheckrequest To Django URL: Here I have used space to created percent sign in front of 7Ccheckrequest path('Data/CurrentRunningActivity2/<int:implementor> 7Ccheckrequest', CurrentRunningActivityView2, name='CurrentRunningActivity2'), -
When I search useing SearchRank, if it does not find anything, it returns everything
When I search using SearchRank, if it does not find anything, it returns everything. How can I fix this problem? views : self.search = form.cleaned_data['search'] vector = SearchVector('title', weight='A') + SearchVector('description', weight='C') + SearchVector('category', weight='B') query = SearchQuery(self.search) self.results = post.annotate(rank=SearchRank(vector, query)).order_by('-rank') -
Django How to add loop column in model from another model
I want to add each City name in models A data to models B table Column name. When I add a new City is it possible to add and update the model B table? class ModelA(models.Model): city_name = models.CharField(max_length=50) def __str__(self): return f"{self.city_name}" class ModelB(models.Model): for eachCity in ModelA: code = eachCity.city_name code = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return f"{self.options}" -
How to require an additional charge for the first-time users in stripe subscription?
I am building a Saas project. This system has several pricing plans. The first-time users should pay an additional amount of money. This money is charged only once per account and is not required anymore after the user paid once regardless of the purchased plan. It seems Stripe have no such option. And if I use the normal checkout method and subscription method together, the user should pay twice the first time. This is bad for the user experience. I would be appreciate if you could help me to solve this problem. In addition, I am using Django+React for the project. -
Django - Join between models and only get `url` field of ImageField attribute of one of the joined models
I have this class called User, which has an ImageField attribute, which stores the user's avatar/profile picture. I'm trying to annotate a Post query set so that just the user's avatar url gets returned with the post none of the other data. I've tried 2 different ways to annotate the query, but get errors as you can see below when I ping the views to get posts. How do I attach user avatar url with the return annotated Post query set? models.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) @property def avatar_url(self): return self.avatar.url class Post(models.Model): uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) annotator.py def query_to_full_post_data_serializer(post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar_url') ) return FullPostDataSerializer(query_set_annotated, many=True) annotator_version_2.py def query_to_full_post_data_serializer(post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar__url') ) return FullPostDataSerializer(query_set_annotated, many=True) annotator.py gives the error: django.core.exceptions.FieldError: Cannot resolve keyword 'avatar_url' into field. Choices are: avatar, cheer_post, cheer_reply, created, creator_username, followee_id, follower_id, friendship_creator, friendshiprequest, goal_creator, goal_follow, goal_join, post_creator, reply, updated_at, … -
Is there a Django library that automatically display local currency based on a visitors country IP address
I'm trying to integrate a functionality on an Ecommerce website in Django, Where victors are automatically shown local currency base on their country IP address, Is there any library that i can use to achieve this functionality. what is the best way to write a function view or class base view to accomplish this fit. Is it possible to have the manipulations of the currency on one template ? -
How to combine Celery with asyncio to handle HTTP requests asynchronously?
How to receive async HTTP requests and process the requests asynchronously using celery? Here is what I have tried, is this the right way to combine async with celery so I can receive async HTTP requests and process them asynchronously The url is: urlpatterns = [ path('api/example/', example, name='example'), ] The views.py is async def example(request): res = await process_data(request) json_data = json.loads(res.content) return render(request, "index.html", {"task_id": json_data["task_id"], "task_status": json_data["task_status"]}) async def process_data(request): result = some_CPU_heavy_function.delay("yes") return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_200_OK) @shared_task def some_CPU_heavy_function(some_data): return {"reply": "yes"} And the command from Docker is command: gunicorn server.asgi:application --bind 0.0.0.0:8000 -w 17 -k uvicorn.workers.UvicornWorker -
How to connect MySQL with Django SQLalchemy?
I'm trying to connect Django app with MySQL, My model: **models.py** from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker engine = create_engine('mysql://root:root0000@localhost', echo=True) Base = declarative_base() Session = sessionmaker(bind=engine) Session.configure(bind=engine) session = Session() class School(Base): __tablename__ = 'schools' id = Column(Integer, primary_key=True) title = Column(String) address = Column(String) created = Column(DateTime(timezone=True), server_default=func.now()) My Controller: views.py class SchoolViewSet(ViewSet): query = models.session.query(models.School).all() def list(self, request): return Response(self.query) Getting this error: in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1046, 'No database selected')