Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Random password generation when admin creates employees in admin site
I have inherited three users from the User model, namely the Admin, Employee, and Relative. models.py config = RawConfigParser() config.read('config.cfg') class UserManager( BaseUserManager): def _create_user(self, PAN_ID, password=None, **extra_fields): """ Creates and saves a User with the given email, date of birth and password. """ if not PAN_ID: raise ValueError('Users must have a PAN_ID') extra_fields['email'] = self.normalize_email(extra_fields["email"]) user = self.model(PAN_ID=PAN_ID, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, PAN_ID, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(PAN_ID, password, **extra_fields) def create_superuser(self, PAN_ID, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(PAN_ID, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): PAN_ID = models.CharField(max_length=100, unique=True) password = models.CharField(_('password'), max_length=128, null=False, blank=True) email = models.EmailField(max_length=100, unique=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) name = models.CharField( max_length=60, blank=True) address = models.CharField(max_length=70, null=True, blank=True) holding = models.CharField(max_length=100, null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=True, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) objects = UserManager() USERNAME_FIELD = "PAN_ID" EMAIL_FIELD = "email" REQUIRED_FIELDS = ['email', … -
How to disable default Django Template/Skin
is there a way to disable Django View for users? I want to get all the data per API as Json, not from View. I tried to delete Template in Django Setting, it was okay... But after that, I couldn't access to Admin Panel. To be more clear, I mean these Templates: Thanks -
NOT NULL constraint failed: auth_user.password
Django inbuild authentication using time I'm faced this error ! ! NOT NULL constraint failed: auth_user.password Views.py from django.shortcuts import render from django.views.generic import TemplateView, FormView from .forms import UserRegistrationForm from django.contrib.auth.models import User class RegisterView(FormView): template_name = "registration/register.html" form_class = UserRegistrationForm success_url = '/' def form_valid(slef, form): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = User.objects.create(username=username, email=email, password=password) user.save() return super().form_valid(form) Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm, forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')``` -
How to exclude an item in Django loop?
Hopefully just a quick question. I am having some difficulty wrapping my mind around to using Django loop function. I have a simple page which is fetch some data from db. Everything seems fine although loop function melting my mind. Simply my loop: {% if books %} {% for reader in books %} {{ reader.title }} {{ reader.booknumber|default_if_none:"" }} {% endfor %} {% else %} My result like: Elena 141 Elena M.Mary 1035 P.Paul 141 P.Paul T.Mark 741 T.Mark T.Mark My Expect result like: Elena 141 M.Mary 1035 P.Paul 141 T.Mark 741 Thats because some of booknumber cell is emtpy in my db. I just wonder how do i put them out of loop? I'm using defult_if_none func for hide "None" but didnt find a way for hiding\excluding title (if doesnt have booknumber). I really appreciate if someone could help me out. Thank you in advance. -
Writing Customized functions in django views
how can I return error from a python function and display it in Django temaplate. I have a code base that is similar to the following structure: In Views.py: def calculate(num1, num2): result = int(num1) + int(num2) return result def home(request): if request.method == POST: user_input_1 = request.POST.get('user_input_1 ') user_input_2 = request.POST.get('user_input_2 ') calculator = calculate(user_input_1 , user_input_2 ) context = { 'calculator' : calculator } return render(request, 'home.html', context) return render(request, 'home.html') So in the case were the user enters a letter instead of a digit, I want to display an error in the django template telling the user about the error. Right now when error occurs the code crashes. I know that I can write a try and except to handle the error but I don't know how to display the exact error message on the HTML template. Any Ideas on how to go about this please? -
How to set token expiration time according to user type in django-graphql-jwt?
Let's say we have two type of users, bot users and normal users: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) is_bot_user = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = CustomUserManager() We would want to set longer expiration time to bot user when it logs in. In settings.py we must define JWT_EXPIRATION_DELTA GRAPHENE = { 'SCHEMA': 'app.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', 'debugging.middleware.DebugMiddleware' ], } GRAPHQL_JWT = { 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': timedelta(minutes=10), } How this expiration delta can be varied according to the Users is_bot_user field? Or is there some other way to create different type of tokens for different Users -
why the image doesn't save on my code and just saved by admin page?
I need to know why the images don't save in the path. I checked from the path and both of static root and media root seems to work good but the image doesn't save, here is the code where you can see what's happening: notice: the image works fine and has installed by admin page but doesn't save or work by my code. models.py class Product(models.Model): ... image = models.ImageField(upload_to='img/', blank=True) def save(self, *args, **kwargs): if not self.image: self.image = 'empty.jpg' super().save(*args, **kwargs) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/img/' MEDIA_ROOT = os.path.join(BASE_DIR, 'img') urls.py that exists in the project generally urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py @login_required(login_url=reverse_lazy('accounts:login')) def createProduct(request, slug=None): user = User.objects.get(slug=slug) if user.user_admin: form = CreateProduct(None) if request.method == 'POST': form = CreateProduct(request.POST, request.FILES or None) if form.is_valid(): Product.objects.create( user=request.user, name=form.cleaned_data['name'], price=form.cleaned_data['price'], digital=form.cleaned_data['digital'], image=form.cleaned_data['image'] ) return redirect('store:store') return render(request, 'store/create_product.html', {'forms': form}) else: raise ValueError('You have no perm to make something here') -
how to display Time according to user location
in my website a user saves datetime in model and i need to display this time in my template according to other user's local time for instance if a user in Mexico creates a new tour it should be saved in model in Mexico time but for a user in America i want it to be displayed in US time this is my setting.py : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True and this is my code in views.py : utc = pytz.utc date_field = form.cleaned_data['date'] time_field = form.cleaned_data['time'] meeting.date_time = utc.localize(datetime.combine(date_field,time_field)) meeting.save() and this is my template : <p class="">{{meeting.date}} {{meeting.date_time|localtime|date:'h:i A'}}</p> but it is not working! Thanks in advance! -
ImportError: cannot import name 'get_safe_settings' from 'django.views.debug' when upgrading django2 to 3.1.5
I am trying to upgrade from Django2.2.6 to Django 3.1.5. I have already upgraded few installed packages, but I do not know which one causes the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 69, in inner_run self.check(display_num_errors=True) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/apps.py", line 18, in check_middleware from debug_toolbar.middleware import DebugToolbarMiddleware File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/middleware.py", line 12, in <module> from debug_toolbar.toolbar import DebugToolbar File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 141, in <module> urlpatterns = DebugToolbar.get_urls() File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 134, in get_urls for panel_class in cls.get_panel_classes(): File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 115, in get_panel_classes panel_classes = [ File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 116, in <listcomp> import_string(panel_path) for panel_path in dt_settings.get_panels() File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/panels/settings.py", line 5, in <module> from django.views.debug import get_safe_settings ImportError: cannot import name 'get_safe_settings' from 'django.views.debug' (/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/views/debug.py) -
Python Django SQLite Database is Locked
I am using Python Django and trying to save some data in Admin panel but it throws an error Please help to solve thisThanks -
How to manage mobile and web authentication with Django Rest and react/react native?
We are in the process of setting up a project that requires mobile and web app authentication and were wondering if there are any best practices for implementation. For the backend we are currently using django rest framework with a knox token authentication and for the web frontend react.js. For the future, there will be a mobile app in react native. We want to set up the authentication now so that it supports the react native mobile app in the future. However, I have seen that Knox authentication does not work for mobile apps straight forward as it uses csrf token. So I'm wondering if there are any best-practices for mobile app and web authentication that specifically feature good documentation, multi-device login and smooth extensibility of login options (fb, google etc) for the current setup drf and react.js/react native. I'm grateful for any guiding hints. -
Django in qpython
Hi I program in Android Python But I have a problem, thank you for your help I installed Django completely and created the Manage.py folder, now I have a problem with runserver python manage.py runserver There is an error for the word Python here! What should I do? -
PostgreSQL HStore() field
I use multiple PostgreSQL HStore fields in my django model. Keys of HStore fields are big int numbers that are related to some other fields in application and are therefore random, not predefined. Values are decimal numbers. Like so: "10intNumber" => "DecNumber". All hstore fields have the same 10IntNumber keys in them, even if DecNumber is 0. The model also include a foreign key to user, and a status. Status is 1: only the hstore_field_1 is evaluated and summed. Status is 0: both hstore_field_1 and hstore_field_2 are evaluated and summed. I use a SQL Query like this, to sum all the DecNumber in values for predefined 10intNumber, where d.number is the 10IntNumber from before and is retrieved from another queryset.: query = f""" SELECT SUM(hstore_1::numeric) AS hstore_1_field, SUM(hstore_2::numeric) as hstore_2_field, FROM ( SELECT UNNEST(hstore_field_1-> ARRAY {[str(d.number) for d in queryset]}) AS hstore_1, UNNEST(CASE WHEN status = '0' THEN hstore_field_2-> ARRAY {[str(d.number) for d in queryset]} ELSE ARRAY ['0'] END) AS hstore_2, FROM public.app_model WHERE hstore_field_1?| ARRAY {[str(d.number) for d in queryset]} ) AS b; """ I also use a SQL query to group sums by related user_id and user__othemodel_id. But my knowledge of SQL comes short afterwards. I would like … -
tag inside bootstrap_button tag in django-bootstrap4
I have a question regarding the bootstrap_button template tag of django-bootstrap4 (https://django-bootstrap4.readthedocs.io/en/latest/templatetags.html#bootstrap-button) , could it be possible to include a tag from my tags in the href, something like this : {% bootstrap_button "Supprimer" button_type="link" href="../../delete/{{article.id}} " button_class="btn-danger" %} but {{article.id}} is not interpreted and it gives me a link to http://127.0.0.1:8000/delete/{{article.id}} I also tried : {% bootstrap_button "Supprimer" button_type="link" href="{% url 'delete' article.id %}" button_class="btn-danger" %} it returns TemplateSyntaxError at /edit/127/ Could not parse the remainder: '"{%' from '"{%' Request Method: GET Request URL: http://127.0.0.1:8000/edit/127/ Django Version: 3.0.5 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '"{%' from '"{%' but none of thos syntax is not working... Could you help me to make it work ? Man thanks -
Error while accessing CSS file Type scan linked CSS file
My code is not bad i think i have checked different websites and i have done what they did but for some reason my html code doesnt accept the css code in django {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> I have tried everything and honestly it is fustrating -
DJANGO PWA Install to home screen not working
I am trying to follow the instructions on this site (https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen) with my DJANGO app to make a PWA "Install to home screen' button. I have SSL installed on the site, and it seems to me that the service worker is installed properly, I got the "Service Worker Registered" message back. However when I click the button I nothing happens, the + sign does not appear in the URL bar as it should. I have no idea what is causing the error, as there is no clear sign of anything not working properly. My index.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>A2HS demo</title> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <script src="{% static 'js/index.js' %}" defer></script> <link rel="manifest" href="{% static 'manifest.json' %}"> </head> <body> <button class="add-button">Add to home screen</button> </body> </html> My manifest.json: { "short_name": "Test site", "name": "Test site", "theme_color": "#062440", "background_color": "#F7F8F9", "display": "fullscreen", "icons": [ { "src": "assets/logo.png", "type": "image/png", "sizes": "192x192" } ], "start_url": "/index.html" } My index.js // Register service worker to control making site work offline if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/static/js/service-worker.js') .then(() => { console.log('Service Worker Registered'); }); } // Code to handle install prompt on desktop let deferredPrompt; … -
In Django what does the request argument in a method do?
I have seen a few codes where sometimes the authenticate method have the request argument while other times it does not, e.g. see the below codes: Code 1: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # code for automatic login after singing up username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return redirect('/') Code 2: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) According to the official docs: request is an HttpRequest and maybe None if it wasn’t provided to authenticate() (which passes it on to the backend). What does this request argument actually do and when should I consider passing it in the authenticate or login method? Is there any specific reason for which request argument is present or absent in the above codes? -
how to solve static file error in my django app
Request Method: GET Request URL: http://127.0.0.1:8000/static/mytxt.txt 'mytxt.txt' could not be found -
Unable to follow django-quickbooks Documentation
I am working on Django web application and i want to push data in Quickbook Desktop. So i was following https://github.com/weltlink/django-quickbooks/ this link and in the third step where you have to create qwc file with manage.py command is not working. So, Is there any better way to integrate django and quickbook desktop? Or Is there any better Documentation? -
How do you access a ForeignKey's other attribute in Django?
I've been looking for a way to retrieve a model's attribute via ForeignKey(related_name). I'm going to paste the code below. Django version is 3.1, while Python version is 3.7. accounts.models.py class Company(models.Model): name = models.CharField(max_length=60) industry = models.CharField(max_length=20, choices = INDUSTRY_CHOICES, default="agriculture") partner.models.py class Partnership(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partnership_creator_set") partner = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partner_set") So when a Company partners with another Company, 2 instances of Partnerships are created. How do i get get the number of existing partners for a specific company? I'm able to get a Company instance then use the related name to get the existing partnerships. If I try something like Company.partnership_creator_set.all(), I'm able to get the list of partnerships. What I want is to look for the current partners which is in the "partner" attribute in the Partnership model. -
Django creating radar chart with Json
I created a system with Django. I need some charts for my project and I am using chart.js library. I get data from an API address, I can get the data correctly with Json and display it in a table, but I can not display it in the radar chart. I think I cannot write Javascript code correctly because Radar chart does not show anything. views.py def Radar(request): response = requests.get('https://api.f-rayscoring.com/company/ADESE/radar') data = response.json() return render(request, 'radar.html', {'data': data}) radar.html <div class="content"> <div class="page-inner"> <h4 class="page-title">Radar Chart</h4> <div class="row"> <div class="col-md-6"> <div class="card"> <div class="card-header"> <div class="card-title">Radar Chart</div> </div> <div class="card-body"> <div class="chart-container"> <canvas id="radarChart"></canvas> </div> </div> </div> </div> </div> </div> </div> {% endblock content %} {% block javascripts %} <script src="/static/assets/js/setting-demo2.js"></script> <script> radarChart = document.getElementById('radarChart').getContext('2d') {% for dt in data %} var myRadarChart= new Chart(radarChart, { type: 'radar', data: { labels: [{{ dt.title }}], datasets: [{ data: [{{ dt.value }}], borderColor: '#1d7af3', backgroundColor : 'rgba(29, 122, 243, 0.25)', pointBackgroundColor: "#1d7af3", pointHoverRadius: 4, pointRadius: 3, label: 'Team 1' }, { data: [], borderColor: '#716aca', backgroundColor: 'rgba(113, 106, 202, 0.25)', pointBackgroundColor: "#716aca", pointHoverRadius: 4, pointRadius: 3, label: 'Team 2' }, ] }, options : { responsive: true, maintainAspectRatio: false, legend : … -
django-admin cannot create project due to - bad interpreter
% pip install django Collecting django Using cached Django-3.1.5-py3-none-any.whl (7.8 MB) Requirement already satisfied: pytz in ./virtualenvproj/lib/python3.8/site-packages (from django) (2020.5) Requirement already satisfied: asgiref<4,>=3.2.10 in ./virtualenvproj/lib/python3.8/site-packages (from django) (3.3.1) Requirement already satisfied: sqlparse>=0.2.2 in ./virtualenvproj/lib/python3.8/site-packages (from django) (0.4.1) Installing collected packages: django Successfully installed django-3.1.5 % pip freeze asgiref==3.3.1 Django==3.1.5 pytz==2020.5 sqlparse==0.4.1 % python -V Python 3.8.0 % django-admin startproject myproject zsh: /usr/local/bin/django-admin: bad interpreter: /usr/local/opt/python@2/bin/python2.7: no such file or directory After Big Sur Mac OS update, quite a lot of thing being messed up python and djangp. -
Django Queryset instead of for loops and if statements in views.py
I've got the following models: class Post(models.Model): description = models.TextField() post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_on = models.DateField(auto_now_add=True, verbose_name=_("created on")) liked_users = models.ManyToManyField(User, blank=True, related_name='liked_post') disliked_users = models.ManyToManyField(User, blank=True, related_name='disliked_post') class Image(models.Model): post = models.ForeignKey(Post, null=True, default=None, on_delete=models.CASCADE, related_name='parent_post') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) images = models.ImageField(upload_to = 'images/') class Tag(models.Model): name = models.CharField(max_length=100) weight = models.IntegerField(default=0) post = models.ForeignKey(Post, null=True, default=None, on_delete=models.CASCADE,related_name='post') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) and in accounts class User(AbstractUser): user_id = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) liked_posts = models.ManyToManyField('post.Post', blank=True, related_name='user_liked') disliked_posts = models.ManyToManyField('post.Post', blank=True, related_name='user_disliked') liked_tags = models.ManyToManyField('post.Tag' , blank=True, related_name='user_liked') disliked_tags = models.ManyToManyField('post.Tag', blank=True, related_name='user_disliked') Here is my get_queryset method in views.py def get_queryset_post(self, user): liked_tags = user.liked_tags.all() disliked_tags = user.disliked_tags.all() posts = Post.objects.all() sorted_posts = [] liked_posts = [] disliked_posts = [] normal_posts = [] for post in posts: is_break = False is_added = False post_tags = Tag.objects.filter(post=post) for tag in post_tags: if is_break: break for liked_tag in liked_tags: if tag.name == liked_tag.name: liked_posts.append(post) is_break = True is_added = True break else: for disliked_tag in disliked_tags: if tag.name == disliked_tag.name: disliked_posts.append(post) is_added = True is_break = True break if is_added == False: normal_posts.append(post) continue for i in … -
HTTPConnectionPool: Max retries exceeded Caused by NewConnectionError: Failed to establish a new connection: [Errno 13] Permission denied
Hi I'm trying to get REST request from a certain URL and if I input the url directly in the browser it works ok and output is as show in the image below If I also try to query the url via native python, it works fine too. The problem is when i put the request in view.py in my django project I get a connection error as the the title of this question. import requests def my_method(request): response = requests.get('http://10.150.20.103:8000/se/se-seid') special_events_dashboard_events = response.json() for event in special_events_dashboard_events['events']: context['special_events'].append(event) return render(request, 'updates/updates_network.html', context) When I check the page in the browser, I get this error. The REST API url is of different IP Address from my django application. Is this a setting problem in my django application? How to work around this? I have been searching in the internet but I cant seem to find an answer to this. -
download file from s3 uisng django
I am able to read the uploaded file but not able to download it Here is my code from storages.backends.s3boto import S3BotoStorage from boto.s3.connection import S3Connection from boto.s3.key import Key import boto3 from boto3.session import Session import StringIO def download(request, opp_id, document_id): c = setup_context(request) client = request.user.client document = get_object_or_404(RecordDocument, record_id=opp_id, pk=document_id) bucket_name = 'mybucket' key = document.document.name ( when print key u'record/3/AASQIO4L67EU_test.csv') s3_client = boto3.client('s3') s3_response_object = s3_client.get_object(Bucket=bucket_name,Key=key) s3_response_object['Body'].read() s3 = boto3.resource('s3') string_io = StringIO.StringIO() s3.Object(bucket_name, key).download_fileobj(string_io) return redirect(reverse('record_view', kwargs={"pk": opp_id})) Here by file is getting read but not able to download the file