Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customizing JWT token claims in Django
I'm trying to customize my JWT token and what ever I do I got an error like this : ImportError: cannot import name 'MyTokenObtainPairView' from 'base.api.serializers' (D:\Anaraki\api\bakend\base\api\serializers.py) here is my serializers.py file: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer my urls.py file: from django.urls import path from . import views from rest_framework_simplejwt.views import (TokenRefreshView, TokenObtainPairView) from .serializers import MyTokenObtainPairView # to customize the token we use this one insted . urlpatterns = [ path('',views.getRoutes), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] I did everything's that doc said but I still got this ... error, please help me. -
In Django, which has faster and better performance beween ".filter(a).filter(b)" and "Q objects" and "or/and queries" and "keyword queries"
Simply put, what is the order of performance and speed among the following similar looking queries in the Django ORM? .filter(a).filter(b) instances = Model.objects.filter(a=A).filter(b=B) Q objects instances = Model.objects.filter(Q(a=A) & Q(b=B)) or/and queries instances = Model.objects.filter(a=A) & Model.objects.filter(b=B) keyword queries instnaces = Model.objects.filter(a=A, b=B) Thank you, and please leave any comments below. AND please don't copy and paste chatgpt or any other ai services. -
How to implement SignOut request NextAuth with Django REST API?
I am trying to create frontend on next js for my Django REST API. I use Next Auth for frontend auth and token auth for backend api. For login I used api for example www.mysite.com/login and I got token and user data, so for logout I used api endpoint example www.mysite.com/logout it is needed to pass token in headers. So how to implement logout? import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" import api from "../baseaxios" const SIGN_IN_HANDLERS = { "credentials": async (user, account, profile, email, credentials) => { return true; }, }; const SIGN_IN_PROVIDERS = Object.keys(SIGN_IN_HANDLERS); const handler = NextAuth({ providers: [ CredentialsProvider({ name: 'Credentials', credentials: { username: { label: "Email", type: "email", placeholder: "Email" }, password: { label: "Password", type: "password" } }, async authorize(credentials, req) { const res = await api.post("/login", { body: JSON.stringify(credentials), headers: { "Content-Type": "application/json" } }) const user = await res.json() if (res.ok && user) { return user } return null } }) ], pages: { signIn: '/login', }, callbacks: { async signIn({user, account, profile, email, credentials}) { if (!SIGN_IN_PROVIDERS.includes(account.provider)) return false; return SIGN_IN_HANDLERS[account.provider]( user, account, profile, email, credentials ); }, async jwt({user, token, account}) { // If `user` and `account` are set … -
django, problem with the - contact - keyword
I am new to django and trying to create a contact page. Here is my urls.py in the app folder: urlpatterns = [ path("contacts", contact_view), ] and my views.py contact_view(request): return HttpResponse('<h1>Contact Page</h1>') Everything works fine when trying: http://127.0.0.1:8000/contacts I've noticed when I change contacts to contact as the following: urlpatterns = [ path("contact", contact_view), ] and then try http://127.0.0.1:8000/contact, it gives: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/contact/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: 1. admin/ 2. 3. about 4. contact The current path, contact/, didn’t match any of these. I've tried restarting the server and the VSCode. Not working! Appreciate any help on this. Windows 11, VSCode, django 4.2.4 -
IntegrityError FOREIGN KEY constraint failed [In django project ]
enter image description here While adding user data in DB through a form I created I got this error integrity error at \add_emp and it says foreign key constraint failed I tried deleting dbsqlite3 files, migrations files, and pychache files but that did not work please tell me where I am wrong it's my first time getting this error. from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) -
Behave Django Testing - Behave testing only uses dev database instead of test database
How to properly set up behave-django so that it can use a test database loaded with data using factories? Please have a look to the code I have written. environment.py environment.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SampleDemo.settings') django.setup() from behave import fixture, use_fixture from django.test.runner import DiscoverRunner from django.test.testcases import TransactionTestCase, TestCase from src.core.models import User class BaseTestCase(TransactionTestCase): @classmethod def setUpClass(cls): User.objects.create_superuser(username='setuadmin', password='admin', email='setuadmin@admin.com') super(BaseTestCase, cls).setUpClass() @classmethod def tearDownClass(cls): User.objects.filter().delete() super(BaseTestCase, cls).tearDownClass() @fixture def django_test_case(context): context.test_case = BaseTestCase context.test_case.setUpClass() yield context.test_case.tearDownClass() del context.test_case def before_all(context): django.setup() context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() yield context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() def before_scenario(context, scenario): use_fixture(django_test_case, context) feature file Feature: Polish Grading CRUD Test CRUD methods of Polish-Grading Module REST API testing framework Background: Given I set REST API server url Scenario: User login with valid credentials Given I provide user authentication credentials And I make an http post call to "/user/login/" api Then I must get a response with status code 200 and a jSon object with token Scenario: fetch grading details Given I provide the params to fetch polish-grading details When I set the HEADER param request content type as "application/json". And I send HTTP GET request as "/polish/fetch-grading/" Then I receive the Valid … -
Django Post Office - How can I add a foreign key in the Email model that references the Client model?
I'm utilizing the django-post-office library in my Django project. I aim to link the library's existing Email model to my Client model, ensuring that while a single client can have multiple emails, each email can only be linked to one client. Is this feasible? Interestingly, ChatGPT provided a solution, but it mentioned parameters (create_models, model_class) that don't exist in the library therefore the code below doesn’t work. However, I'm curious if ChatGPT might have been hinting at an approach I am not aware. Suggestions how to solve it ? from post_office.models import Email as PostOfficeEmail class ClientEmail(PostOfficeEmail): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='emails') from post_office import mail def send_client_email(client, subject, message): mail.send( recipients=[client.email], sender='your_sender_email@example.com', subject=subject, message=message, create_models=True, # This will create an Email model instance model_class=ClientEmail, # Use our extended model ) # Associate the email with the client email = ClientEmail.objects.last() email.client = client email.save() -
Django: calling .only() on my model causing infinite loop?
I am using .only to fetch the required fields from my model, it seems like my __init__ method causing a inifinite loop when calling only on this model, and this is my model: class PodcastEpisode(models.Model): audio_metadata = models.JSONField(null=True) featured_artists = models.ManyToManyField(to=User, related_name='featured_artists') podcast_series = models.ForeignKey(to=PodcastSeries, on_delete=models.CASCADE, null=False) published = models.BooleanField(default=False) published_at = models.DateTimeField(blank=True, null=True) _original_audios = None # To store current data _published = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self._original_audios = self.audio_metadata # self._published = self.published When I commented these lines self._original_audios = self.audio_metadata and self._published = self.published, it doesn't cause inifinite loop. I am not sure how this is happening even if I have included audio_metadata in my .only() fields. This is my query PodcastEpisode.objects\ .filter(id__in=id_list).prefetch_related(*prefetches).only(*['id' 'audio_metadata']) Please suggest me how do I use .only() and where should I place these _original_audios and _published variables. -
How to hide django default filters from others except admin user?
I have below User graphql API endpoint in my application. Query class Query(UserQuery, graphene.ObjectType): all_users = DjangoFilterConnectionField( UserType, filterset_class=UserFilter) Type class UserType(DjangoObjectType): class Meta: model = User fields = "__all__" interfaces = (graphene.relay.Node,) Filter class UserFilter(FilterSet): user_name_search = CharFilter( method='user_name_filter', label='User Name Search' ) class Meta: model = User fields = [ 'user_name_search', 'user_id', 'first_name', 'last_name', 'email', 'gender', 'height', 'rating', 'phone', 'city', 'state', 'country', 'active', 'deleted', ] def user_name_filter(self, queryset, name, value): return User.objects.filter( Q(first_name__icontains=value) | Q(last_name__icontains=value) ) On API side it shows below filtes by default, I need to hide the filters like first, last, before, after, offset because I don't want to expose all my data to everyone on the internet. So basically if is_superuser is true then only those filters should work. Please guide how to handle this scenario. -
Django uploads Gif as JPG despite a function to add it as video
I'm trying to upload a .gif to my django 3.2 api. I have already ran troubleshoots through Postman and came to the conclusion that my flutter app sends it as a .gif and it gets returned as a .jpg. The problem is on the backend. Here is my relevant code from add media function which checks for file_meme subtype and converts the incoming .gif to a video(There is a separate block for checking if its video and add the video) : def add_media(): if file_mime_subtype == 'gif': if is_in_memory_file: file = write_in_memory_file_to_disk(file) temp_dir = tempfile.gettempdir() converted_gif_file_name = os.path.join(temp_dir, str(uuid.uuid4()) + '.mp4') ff = ffmpy.FFmpeg( inputs={file.temporary_file_path() if hasattr(file, 'temporary_file_path') else file.name: None}, outputs={converted_gif_file_name: None}) ff.run() converted_gif_file = open(converted_gif_file_name, 'rb') temp_files_to_close.append(converted_gif_file) file = File(file=converted_gif_file) file_mime_type = 'video' has_other_media = self.media.exists() self.save() I'm not sure where the problem is. From my limited understanding, it is taking only the first frame of the .gif and uploading it as an image. -
How to upload multiple images or files in a single input field using Django forms?
Could you please provide more context or specific details about the issue you're facing with Django forms? This will help me understand your problem better and provide you with a more accurate solution. I attempted to implement the MultiFileInput widget from the django-multiupload package within my Django form. I expected the widget to allow users to upload multiple images or files through a single input field. However, I faced challenges integrating this widget within my existing form structure. While the widget appeared on the page, I couldn't figure out how to handle the uploaded files and save them to the database. The documentation for the package lacked detailed examples for this specific use case. n short, I tried using the MultiFileInput widget but struggled with its integration and file handling. Any guidance or code snippets to achieve this functionality would be greatly appreciated -
Multiple User Foreign Keys to Same Model?
I'm attempting to create a simple web application (first django personal project) for my friends and I to log our casual sporting bets against eachother. Currently I have the model like this using django's auth User model: class Bet(models.Model): bettor1 = models.ForeignKey(User, related_name='bets', on_delete=models.CASCADE) bettor2 = models.CharField(max_length=256) bet_description = models.TextField() bet_amount = models.PositiveIntegerField() win_amount = models.PositiveIntegerField() create_date = models.DateTimeField(auto_now=True) Currently bettor1 is correctly linked to the user that is logged into the application, but I would like to make it so that bettor 2 is also a foreign key (i think?) connecting to another user's account that exists on the application. (So bettor 1 can choose the opponent he is wagering against from a dropdown menu of the other users with existing accounts). How can I do this? Tried setting another foreign key to user but got errors. Not sure how this is done. -
Non existing value for foreign key in django
I would like know if I can make django accept values for foreign key that doesn't exist in the column referenced. The problem in the business logic is that a model can point to the phone number of a user that doesn't exist yet -
cannot import name in a file?
Hello I am trying to run my django application but its saying: cannot import name 'd' from 'niu' (C:\Users\amber\Umaido\niu_init_.py) which is strange. I have created d in my code file: [ and importet it than into views.py ( The problem now is that it usually works on the Terminal but my Command prompt Terminal is telling me that its an error. I have tried to change form code import d to from . import d but it does not work either -
How to reload the app on Django after changed files?
I have been studying Django lately. The novice tutorials are good, but from a student perspective, there are some steps which are black boxes. One of them is file monitoring: every time I need to update the application, my heart beats faster, I stop the ongoing process and run python manage.py runserver. In real world, I have worked with solutions using Django, but was never clever enough to know how the github pull requests would update the actual hosted app. Would you please help me understand this knowledge gap? Remark: On NodeJS, we use the library nodemon to monitor changes on files. -
Why am I not receiving any data from my forms when using a dropdown with django
Hi guys I'm trying to create a form with a dropdown and other fields, I'm trying to get the data from the form but for some reason I'm not getting anything This the template tha I'm using {% extends "main_page_layout.dj.html" %} {% block content %} <form id="comunicate" method="post">{% csrf_token %} <select name="company"> {% for company in companies %} <option value={{company.id}}>{{ company.name }}</option> {% endfor %} </select> <button id="comunicate" type="submit">Submit</button> </form> {% endblock %} I'm using this piece of code to try to get the data from the form but it's not working This is the form that I'm using in django class PruebaForm(forms.Form): company = company = forms.ModelChoiceField( queryset=CompanyInfo.objects.all(), widget=forms.Select(attrs={"hx-get": "/load_users/", "hx-target": "#id_user"}), ) user = forms.ModelChoiceField( queryset=UserLicense.objects.all(), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['user'].queryset = UserLicense.objects.none() if "company" in self.data: company_id = self.data.get('company') self.fields["user"].queryset = UserLicense.objects.filter(company_id=company_id) If someone can explain why I'm not getting anything it would be helful since I'm new with this -
Slice capacity in go
I recently studying go in w3schools and I can't able to understand capacity of slice in go? How the cap() of myslice1 is 12.Slice in go I expect that the cap() of myslice1 is 8 because I append the two numbers on previously created slice.But the cap() myslice1 before append is 6. And after appended the cap()of myslice is 12. -
I can't link CSS file to HTML file in Django project
HTML file is working well. But it's not linking with CSS, what I make in CSS simply does not work. HTML PAGE <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TheWebPub</title> <link rel="stylesheet" href="stylepage.css"> </head> <body> {% if name %} <h1 class='title'>Hello {{name}}. </h1> {% else %} <h1>Hello world.</h1> {% endif %} <p>Thank you for being here in my website, it's my first one. I'm creating this website with django/python.</p> </body> </html> everything seems to be ok. it's my views.py file in my django project from django.shortcuts import render from django.http import request # Create your views here. def say_hello(request): return render(request, 'index.html', {'name':'Adryan'}) -
In Edit-Form I must enter a tab to make fields return with values but they return "None" where I didn't enter them tabs in django forms
I have a problem with my forms (I fixed it) by an idea I’ll mention here, But I think I miss something or Django Forms have a another good solution for it. I have one page with(many tabs and as a result many forms and many inputs also). All forms must save by one save button under one form <form class="add-product-form"></form> And <form class="edit-product-form"></form> The next image illustrate what I mean. My Problem : In add-product-form everything is OK(Saving process has been done perfectly till now) but in edit-product-form I noticed that (Any inputs present in a tab I don’t enter, every input in this tab return "None" and the update process of edit-product-form leads to make the original data that I have saved in add-product-form return to None or to default - As clean_field(self) method stated) Here is some of code of my forms.py file class ProductForm(forms.ModelForm): name = forms.CharField( required=False, widget=forms.TextInput( attrs={ # "class": "form-control", "placeholder": "Write the product English name here ...", } ), ) name_ar = forms.CharField( required=False, widget=forms.TextInput( attrs={ # "class": "form-control", "placeholder": "Write the product Arabic name here ...", } ), ) class Meta: model = Product fields = ( 'name', 'name_ar', 'branch', 'pos_station', … -
Django model's string representation creates duplicates queries
Working on Airport API Service task. Can not solve N+1 problem for Flights: moldels.py: class Flight(models.Model): route = models.ForeignKey(Route, related_name="flights", on_delete=models.CASCADE) airplane = models.ForeignKey(Airplane, related_name="flights", on_delete=models.CASCADE) crew = models.ManyToManyField(Crew, related_name="flights") departure_time = models.DateTimeField() arrival_time = models.DateTimeField() class Meta: ordering = ["departure_time"] def __str__(self): return f"{self.route} ({self.departure_time})" serializers.py: class FlightListSerializer(FlightSerializer): route = serializers.StringRelatedField(many=False, read_only=True) airplane_name = serializers.CharField(source="airplane.name", read_only=True) tickets_available = serializers.IntegerField(read_only=True) class Meta: model = Flight fields = ( "id", "route", "airplane_name", "departure_time", "arrival_time", "tickets_available", ) views.py: class FlightViewSet(viewsets.ModelViewSet): queryset = Flight.objects.all() serializer_class = FlightSerializer permission_classes = (IsAdminOrIsAuthenticatedReadOnly,) def get_queryset(self): queryset = self.queryset if self.action == "list": queryset = ( queryset .select_related("airplane", "route__destination", "route__source") .annotate( tickets_available=( F("airplane__rows") * F("airplane__seats_in_row")) - Count("tickets") ) ) return queryset return queryset def get_serializer_class(self): if self.action == "list": return FlightListSerializer # if self.action == "retrieve": # return TripDetailSerializer return FlightSerializer Problem: I checking endpoint with debug_toolbar and it shows 7 duplicates. Before it was much more, but I fixed some by add selected_related method and decrease it from 25 to 17. I noticed, that this problem comes from "route" field. This is Route model: class Route(models.Model): source = models.ForeignKey( Airport, on_delete=models.CASCADE, related_name="sources" ) destination = models.ForeignKey( Airport, on_delete=models.CASCADE, related_name="destinations" ) distance = models.IntegerField() class Meta: unique_together … -
Django symmetrical tabularinline m2m
Just starting in Python/Django framework so sorry if this is dumb... but i cant find any solution. model.py class Apk(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, unique=True, verbose_name='XXXX') class ListProductConnections(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Apk, on_delete=models.CASCADE) related_products = models.ManyToManyField(Apk, related_name='related_product', verbose_name='Є компонентом',) My admin.py class ListProductConnectionsInline(admin.TabularInline): model = ListProductConnections filter_horizontal = ('related_products',) extra = 0 max_num = 1 verbose_name = 'XXX' verbose_name_plural = 'XXX' class ListProductConnectionsForm(forms.ModelForm): class Meta: model = ListProductConnections fields = '__all__' related_products = forms.ModelMultipleChoiceField( queryset=Opk.objects.all(), widget=FilteredSelectMultiple('YYY', is_stacked=False), required=False, ) def __init__(self, *args, **kwargs ): super().__init__(*args, **kwargs) current_product_id = ListProductConnectionsReversInline.global_variable if current_product_id is not None: related_products_data = ListProductConnections.related_products.through.objects.filter( opk_id=current_product_id ).values_list('listproductconnections_id', flat=True) related_products_data_new = ListProductConnections.objects.filter(id__in=related_products_data).values_list('product_id', flat=True) initial_product_ids = list(related_products_data_new) self.initial['related_products'] = initial_product_ids class ListProductConnectionsReversInline(admin.TabularInline): model = ListProductConnections form = ListProductConnectionsForm extra = 0 max_num = 1 verbose_name = 'YYY' verbose_name_plural = 'YYY' global_variable = None def get_formset(self, request, obj, **kwargs): formset = super(ListProductConnectionsReversInline, self).get_formset(request, obj, **kwargs) try: self.__class__.global_variable = obj.id except: pass return formset @admin.register(Opk) class OpkAdmin(ImportExportModelAdmin): form = FactoryForm .... inlines = [ListProductConnectionsInline, ListProductConnectionsReversInline] I have a Product, and I want to do the following: In the ListProductConnectionsInline, select which Products use the Product we are currently editing. This is working perfectly now. In the ListProductConnectionsReversInline, select … -
A testcase for a guest user trying to edit another user's post
I'm working on a Web site (in Django) which is a very simple social network with authentication (i.e. if you want to edit a post you should login into the Web site, although you can see all the posts even if you aren't logged into the site). I´m preparing a set of testcases for my Web site and I would like to include one for a guest user cannot edit another user's post (e.g. a user who is not logged in into the Web site is not able to edit any post). How can I get it? Below my code: urls.py (app) from django.urls import path from . import views #app_name = "network" urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newPost", views.newPost, name="newPost"), path("profile/<int:user_id>", views.profile, name="profile"), path("unfollow", views.unfollow, name="unfollow"), path("follow", views.follow, name="follow"), path("following", views.following, name="following"), path("edit/<int:post_id>", views.edit, name="edit"), path("remove_like/<int:post_id>", views.remove_like, name="remove_like"), path("add_like/<int:post_id>", views.add_like, name="add_like"), ] urls.py (project) from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("network.urls")), ] views.py def index(request): allPosts = Post.objects.all().order_by("id").reverse() # Pagination paginator = Paginator(allPosts, 10) page_number = request.GET.get('page') posts_of_the_page = paginator.get_page(page_number) # Likes allLikes = Like.objects.all() whoYouLiked = [] try: for … -
Redirect To Root Not Happening In Custom User Login View function
I am newbie to python and Django. I tried every tool (chatgpt, Youtube, blogs) but I was unable to find the solution. Problem Statement: When I fill the sign-up form, after submission, I am directed to login page. Here when I enetr correct credentials, instead of redirecting me to "home" view function, the login page remain appearing/stayed on the screen.I asked Chatgpt, according to it, redirection is not happening properly. Please help when I typed correct credentials in login form and hit the submit button following error appears in the terminal [27/Aug/2023 05:22:34] "POST /login/ HTTP/1.1" 200 1078] Models.py from django.db import models from django.contrib.auth.models import AbstractUser,Group, Permission class CustomUser(AbstractUser): email = models.EmailField("email address", unique=True) 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, null=True, verbose_name='username') groups = models.ManyToManyField( Group, verbose_name='groups', blank=True, help_text='The groups this user belongs to.', related_name='custom_users', # Add a unique related_name ) user_permissions = models.ManyToManyField( Permission, verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name='custom_users', ) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['username'] Forms.py from django import forms from .models import CustomUser class SignUpForm(forms.ModelForm): class Meta: model = CustomUser fields = ("username", 'password', "email",'first_name', 'last_name',) … -
Server error(500) after deployment to railway in django
I was working on A Django project and it worked perfectly fine on the local server, especially when it came to form handling like user signup, login even admin login. But after I deployed it to Railway, first i got the error of csrf token, so it could not load any forms, which i solved with CSRF_TRUSTED_ORIGINS = ['https://domain_name.com'] which worked and now the forms load up but when after I fill in the details, the admin login, user sign up and login pages, and I hit the save but it throws back and error "SERVER ERROR(500)" I am really confused on what to do... someone please point me in the right direction please -
problem with logic in django code. read data from redis and database
I have this django code and it take data from redis by inscode and return. if redis is down it should jump out of try,expect block and read data from database (postgresql). class GetOrderBook(APIView): def get(self, request, format=None): # get parameters inscode = None if 'i' in request.GET: inscode = request.GET['i'] if inscode != None: try: #raise ('disabling redis!') r_handle = redis.Redis( host=r_handles['orderbook_host'], port=r_handles['orderbook_port'], socket_timeout=REDIS_TIMEOUT, charset='utf-8', decode_responses=True) data = r_handle.get(inscode) if data != None: return Response(json.loads(data), status=status.HTTP_200_OK) else: print('GetOrderBook: data not found in cache') except BaseException as err: print(err) orderbook = OrderBook.objects.filter( symbol__inscode=inscode).order_by('rownum') if len(orderbook) > 0: data = OrderBookSer(orderbook, many=True).data data_formatted = {'buynum': [0]*5, 'buyvol': [0]*5, 'buyprice': [ 0]*5, 'sellnum': [0]*5, 'sellvol': [0]*5, 'sellprice': [0]*5} for row in data: rownum = row['rownum'] - 1 data_formatted['buynum'][rownum] = row['buynum'] data_formatted['buyvol'][rownum] = row['buyvol'] data_formatted['buyprice'][rownum] = row['buyprice'] data_formatted['sellnum'][rownum] = row['sellnum'] data_formatted['sellvol'][rownum] = row['sellvol'] data_formatted['sellprice'][rownum] = row['sellprice'] return Response(data_formatted, status=status.HTTP_200_OK) else: return Response({'Bad Request': 'invalid input'}, status=status.HTTP_404_NOT_FOUND) return Response({'Bad Request': 'incomplete input data'}, status=status.HTTP_400_BAD_REQUEST) but problem is that it not reading from database also I write this test for it to return 200 if you read data. but when redis is down it dont read data and return 404 to me . def test_redis_function(self, …