Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels using RedisPubSubChannelLayer fails to receive
I was testing RedisPubSubChannelLayer for a simple send/receive, but the test fails using pytest. (it passes with RedisChannelLayer) Test class class TestRedis(TestCase): # test if RedisChannelLayer communicates async def test_channels_send_receive(self): channel_name = '45jfngoegnolkmlrmbhrfmh' channel_layer = channels.layers.get_channel_layer() payload = {'type': 'hello'} await channel_layer.send(channel_name, payload) print(f"channel_layer.send done") result = await channel_layer.receive(channel_name) print(f"channel_layer.receive done") self.assertEqual(payload, result) Would you help me understand what I'm doing wrong? If I simply change "BACKEND": "channels_redis.pubsub.RedisPubSubChannelLayer" to "BACKEND": "channels_redis.core.RedisChannelLayer" the test passes, but otherwise, only "channel_layer.send done" prints and hangs on receive I'm using Ubuntu 22.04.3 LTS python 3.10.12, redis_version:6.0.16 channels-redis==4.1.0 Django==4.2.4 channels==4.0.0 pytest==7.4.2 pytest-asyncio==0.21.1 pytest-django==4.5.2 -
build API for support pagination and non-paginate on django rest framework
As I work on Django-rest-framework. I want the API to support dynamic pagination. For example, if user need pagination they can use an endpoint /api_url?offset=0&limit=10(should return with the format that can let the user know the current page and have the next page or not) and if they don't want pagination they just request without params /api_url. I need it to work with django_filters so it won't make many requests to SQL. I expect to get solition or sample code to about this problem. -
Check_password doesn't work in my Django login system
I am trying create login system when user signup it register successfully users data in database when user signin, the check_password method not work it wil give the else statement meassage Like 'password mismatch'. Can anyone help me to find the answer thankyou in advance I am also used built-in authenticate funtion to authenticate the use but it is also not work from django.http import HttpResponse from django.contrib import messages from django.shortcuts import render from.forms import loginform from.models import Logindata import re import mysql.connector from django.contrib.auth.hashers import make_password,check_password def signin(request): if request.method=='POST': username=request.POST.get('Username') password=request.POST.get('Password') try: user=Logindata.objects.get(Username__contains=username) except Logindata.DoesNotExist: return HttpResponse(f" login failed") if user.check_password(password) : return HttpResponse('login successful') else: return HttpResponse("password mismatch") return render(request,'Signin.html') def signup(request): if request.method=='POST': user=loginform(request.POST) if user.is_valid(): username=user.cleaned_data['User'] password=user.cleaned_data['Password'] Repassword=user.cleaned_data['ConfirmPassword'] mydb=mysql.connector.connect(host='localhost',user='root', password='',database='loginststem') cursordb=mydb.cursor() sql='select*from loginapp_logindata where BINARY Username=%s' cursordb.execute(sql,[(username)]) Result=cursordb.fetchone() if Result: messages.error(request,"Username already exists") return render(request,'Signup.html',{'form':user}) if len(password)==8: if re.search('[A-Z]',password): if re.search('[a-z]',password): if re.search('[0-1]',password): if password==Repassword: Logindata.objects.create(Username=username, Password=make_password(password)) messages.success(request,'your are Register succesfully') return render(request,'Signin.html',{'form':user}) else: messages.error(request,'Pasword Must be Same') return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one Numeric value") return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one lowercase value") return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one uppercase value") return render(request,'Signin.html',{'form':user}) else: messages.error(request," password must be 8 characters") return render(request,'Signin.html',{'form':user}) else: user=loginform() return render(request,"Signup.html",{'form':user}) … -
pylint_django "Instance of 'ForeignKey' has no ... member"
I'm working on a project in python with django and recently I decided to modify the way the models were stored in one of the apps. With the help of django documentation, I deleted the models.py file and created a models folder in which I put all my models in files and created a _init_.py file in which I import all my models. This solution works but now pylint no longer seems to understand ForeignKeys. this is my app tree: apps myapp models _init_.py mymodel.py mymodel2.py if i run pylint i can see some E1101. let's take an example: i have a model subnet in subnet.py: class Subnet(models.Model): def __str__(self): return self.nom + "(" + self.cidr + ")" net = models.ForeignKey("Network", on_delete=models.CASCADE, related_name="subnets") def get_parent_cidr(self): return self.net.cidr this model have a reference to the network models in network.py: class Network(models.Model): def __str__(self): return self.company.name + " - " + self.nom + " - " + str(self.cidr) cidr = models.CharField(max_length=18) this network object have a cidr field, all seems to be fine but when i run pylint with the pylint_django plugin, this one send me an error: project/apps/myapp/models/subnet.py:74:15: E1101: Instance of 'ForeignKey' has no 'cidr' member (no-member) What did I do … -
in github actions, how to give the django process permission to create a directory?
for every user image, i create a directory and store the image there.This works as intended on my machine in automated tests and manual use but when i push to the Github, the Github actions raise bellow error which indicates it can not create the required directory to run the tests. PermissionError: [Errno 13] Permission denied: '/src/media/profile_image' -
join some table twice in Django ORM
I have two models class Customer(AbstractBaseModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_column='uuid') name = models.CharField(max_length=55) class CustomerAddress(AbstractBaseModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_column='uuid') customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, related_name='addresses', db_column='customer_uuid') country_code = models.CharField(max_length=3) type = models.CharField(max_length=8, choices=[('shipping', 'shipping'), ('billing', 'billing')]) User can filter customers using two fields: billing_country and shipping_country, they can fill either one or both fields. If user fills both fields, I have to join to CustomerAddress table twice. I do this in raw SQL like this: SELECT * FROM customer c LEFT OUTER JOIN address shipping_address ON shipping_address.customer_uuid = c.uuid AND shipping_address.type = 'shipping' LEFT OUTER JOIN address billing_address ON billing_address.customer_uuid = c.uuid AND billing_address.type = 'billing' and append WHERE clauses if user uses filters like this: # billing_country and shipping_country are sanitized at this point filters = [] if billing_country: filters.append(f"billing_country_code = '{billing_country}'") if shipping_country: filters.append(f"shipping_country_code = '{shipping_country}'") where_part = 'WHERE ' + ' AND '.join(filters) How can I do this using Django ORM? -
Best practices for masking sensitive data on django
In a django project, I am sending requests to third party services and keeping a log of these requests, but I want to censor some sensitive data (password, token, etc.) when saving to the database. I wrote a Handler, which works correctly, but I could not do the masking part. I tried with logging.Filter, but it was not the right approach. When I wanted to try logging.Formatter, I could not save to the database because the returned record was a string, not an object. What is the best way to mask this kind of data? Is it to write a masking function in the handler or some other method? I cannot use third party package because it is a company project -
How to fix Django "ModuleNotFoundError: No module named 'application'" on AWS ElasticBeanstalk?
I faced this issue as well. In my case I was getting a 502 nginx error after deploying to AWS EB using eb deploy and my environment had a red flag. My AWS EB was using Amazon Linux. my verion of django is 4.1.3, python version is 3.9 (also tried with 3.11). option_settings: aws:elasticbeanstalk:container:python: WSGIPath: gnt.wsgi:application project dir. -root-folder -apps -requirements.txt -.ebextensions -django.config -gnt -wsgi.py -settings.py -
Not getting browsable interface at http://127.0.0.1:8000/api
Not getting browsable interface at http://127.0.0.1:8000/api But getting on http://127.0.0.1:8000/api/login and on http://127.0.0.1:8000/api/register first i am also not getting on api/register and api/login then i changed as_view to this as_view() i forget to put () auth_app.urls from django.urls import path from .views import RegistrationAPIView,LoginAPIView,LogoutAPIView urlpatterns=[ path('register/',RegistrationAPIView.as_view(),name='register'), path('login/',LoginAPIView.as_view(),name='login'), path('logout/',LogoutAPIView.as_view(),name='logout'), ] auth_project.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/',include('auth_app.urls')) ] i have included rest_framework in installed apps -
PostgreSQL database structure help (multiple database, multiple schema)
Im developing a web application. I have Django for my backend and using PostgreSQL for my database. I am not sure if this is the best approach or not but: I want to create a database for each company and in that database schema for each project within that company. recommendations? I want to create a database for each company and in that database schema for each project within that company. -
Avoid code duplication between django Q expression and as python code
I have a very complex property on a model ALLOWED_STATES = {1,2,3} class X(models.Model): a = models.BooleanField() b = models.ForeignKey('Y', on_delete=model.CASCADE) c = models.IntegerField() d = models.IntegerField() @property def can_delete(self) # this goes on for 6 and clause return self.a and self.b.c and self.c in ALLOWED_STATES and self.d != 5 and .. I also need this property in an annotate() call and filter() #in one endpoint qs = X.objects.filter(...).annoate(can_delete=ExpressionWrapper(Q(a=True, b__c=True, c__in=ALLOWED_STATES,...) & ~Q(d=5), output_field=models.BooleanField()) I wonder if there is a way to unify these forms of this same property into one, without calling can_delete in python after I've fetched the rows. These two forms have become a bit of a maintainability issue as PM keeps on changing the definition of can_delete. -
Pytest error in tests for Single choice question in Django
This is going to be Pytest for single choice question. It cannot be completed due to two reasons - the first one is that the test cannot choose any option from available language_name fields: views.py class AddSingleChoiceQuestionView(View): template_name = "single_choice_form.html" def get(self, request): form = SingleChoiceQuestionForm() return render(request, self.template_name, {"form": form}) def post(self, request): if request.user.is_staff: form = SingleChoiceQuestionForm(request.POST) print(request.POST) print(form.is_valid()) print(form.errors) if form.is_valid(): question = form.save() # Ermitteln Sie die ausgewählte Option aus den Checkboxen selected_option = int(request.POST.get("correct_option")) for i in range(1, 6): option_text = request.POST.get(f"option_{i}") is_correct = i == selected_option # Überprüfen Sie, ob diese Option die ausgewählte ist question.singlechoiceoption_set.create(option_text=option_text, is_correct=is_correct) # return HttpResponseRedirect("success_page") hier doesn't work return redirect("success_page") return render(request, self.template_name, {"form": form}) else: return redirect("index") Conftest.py import pytest from django.contrib.auth.models import User @pytest.fixture def staff_user(db): user = User.objects.create_user(username='staffuser', password='staffpassword', is_staff=True) return user @pytest.fixture def regular_user(db): user = User.objects.create_user(username='testuser', password='testpassword') return user test_views.py for single chocie import pytest from django.test import Client from django.urls import reverse from ..models import MultiQuesModel, Answer, SingleChoiceQuestion from django.contrib.auth.models import User from ..views import AddMultiQuestionView from ..forms import AddMultipleForm, SingleChoiceQuestionForm @pytest.mark.django_db class TestAddSingleChoiceQuestion: @pytest.mark.singlechoice def test_add_single_choice_question(self, client, staff_user): client.login(username='staffuser', password='staffpassword') url = reverse("singleform") # Ersetzen Sie "singlechoice_form" durch den tatsächlichen Namen Ihrer … -
Can not make a user model for both superuser and regular users. Django/Mysql
There is an auth_users table in the database which is built in. If I login any superuser then that superusers information is stored in the auth_user table. There is also another table named authorization_userprofile (authorization is the app name) which stores all the regular users information. This is my model.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class UserProfileManager(BaseUserManager): def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number field must be set') user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) # Hash the password user.save(using=self._db) return user def create_superuser(self, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(phone_number, password, **extra_fields) class UserProfile(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField(max_length=15, unique=True) first_name = models.CharField(max_length=255, default='') # Added first name field last_name = models.CharField(max_length=255, default='') # Added last name field dob = models.DateField(null=True, blank=True) # Added Date of Birth field email = models.EmailField(max_length=255, default='') # Added email field address = models.TextField(default='') # Added address field is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # other fields if any ... objects = UserProfileManager() USERNAME_FIELD = 'phone_number' # Unique related name to avoid clashes with auth.User model groups = models.ManyToManyField('auth.Group', related_name='user_profiles', blank=True) user_permissions = models.ManyToManyField('auth.Permission', related_name='user_profiles', blank=True) # other fields if any ... This is in … -
populate a select with data from the database
I need to fill in a select with data from the bank. I have a description field and a category field, I need django to fill the select with the categories when opening the registration form. I recently started using django and have been facing this difficulty. Does anyone have a light at the end of the tunnel? cadproduto.html <label for="exampleFormControlInput1">Categoria:</label> <select class="form-control select" id="exampleFormControlSelect1"> {% for categoria in ListaDeCategorias %} <option value="{{categoria.id}}">{{categoria.descricaocategoria}}</option> {% endfor %} </select> forms.py from django import forms from .models import CadastroProduto class ProdutoForm(forms.ModelForm): class Meta: model = CadastroProduto fields = ('descricaoresumida', 'precoprincipal', 'enviabalanca') views.py @login_required def ListagemCategorias(request): ListaDeCategorias = models.CadastroCategoria.objects.all() return render(request, 'listagemcategorias.html', {'ListaDeCategorias': ListaDeCategorias}) -
Can I use forked repo in server side? [closed]
Let me ask one that will be easy for you. I've mind in one github repo and I want to deploy it after creating my server. But, it is renewed continuously. Is it possible? I've just forked and I can't know what I have to do next. -
jQuery and Django disable dates in the database on the datepicker
I am building a booking system using Django. I am trying to incorporate a datepicker from jQuery, to disable dates that have been fully booked in the datepicker. I am currently using a snippet of code from stack overflow that disables certain dates, I would like to push an array from my view into this. I can't get it working with the dummy dates so any help is much appreciated. var dates = ['14-10-2023', '15-10-2023', '16-10-2023']; $('.datepicker').datepicker ({ beforeShowDay: function (date) { var string = jQuery.datepicker.formatDate('dd-mm-yy', date); return [dates.indexOf(string) == -1]; } }); class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('booking_date', 'booking_time', 'number_attending') widgets = { 'booking_date': DateInput(attrs={'type': 'date', 'class': 'datepicker'}), } I will alter the check_availability to return an array of dates once i know how to add this to the javascript. def check_availability(date, time): all_bookings = Booking.objects.all() unavailable = Booking.objects.filter( booking_date=date, booking_time=time) available = True total_attendees = unavailable.aggregate(Sum('number_attending'))[ 'number_attending__sum'] for booking in all_bookings: if unavailable.exists() and total_attendees > 20: available = False else: available = True return available def limit_no_attendees(date, time, attending): attendees_limit = False unavailable = Booking.objects.filter( booking_date=date, booking_time=time) total_attendees = unavailable.aggregate(Sum('number_attending'))[ 'number_attending__sum'] if total_attendees is None: total_attendees = 0 if total_attendees + attending < … -
Is it possible to use template tags inside model field for displaying static images?
I have a huge report with some 50+ pages and there are several images and tables inside them. Is there any way I can put static tag inside textField which would be rendered in template, or I have to hardcode path inside model and use report.chapter_one|safe inside tempates? report model looks like chapter_one = models.TextField() chapter_two = models.TextField() chapter_three = models.TextField() ..etc And there are some tables and images that go inside those chapters. So what's the best way to display them because in templates I call chapters like report.chapter_one and it displays a wall of text where I can't put image from inside template -
I need help on algorithm for image recognition in python [closed]
I need a code for python that can detect number plates and compare it with the one on database Have no idea on where to start. The number plates supposed to be read through a camera. I need the code which can compare the plate with the one on database to identity the owner if is owing. -
Astrology prediction website using django [closed]
Need all complete source code.please help me.I tried a lot but not coming. I am trying it from many days but I am unable to build it.so can anyone help me in doing this. Hope anyone one help me to do this. I am waiting for it to complete. -
Python Logger does not write to file, still generates logs
have been struggling with this. I had created a logger for a class instance that gets created every 30 seconds or so. To prevent duplicate logging, I added a hasHandlers check, but now the results do not get logged to the file. I can see the logs being generated in PM2 though, so some portion of the logging is working. class ExampleClass: def __init__(self): self.example_logger = logging.getLogger(__name__) handler = TimedRotatingFileHandler('logs/example.log', when='D', interval=1, backupCount=0, encoding=None, delay=False, utc=False) if not self.example_logger.hasHandlers(): self.example_logger.addHandler(handler) self.example_logger.setLevel(logging.DEBUG) For the use-case, a new instance of this class needs to be created every 30 seconds. It is created via a django command. I would like to avoid any logging duplication as that has been an issue in the past. The path to the log file exists, and if the file is not present, it is created. Yet not written to. -
Problems to populate dropdown list with options from one of my tables (which already in Models.py)
I'm a newbie and I'm stuck while trying to populate a dropdown list with the records in one on my tables (mysql), my idea is to get this data from Marcasmodelos, and use it as to be posted with another field to my table "Modelos". But whenever rendering, nothing happens, it only shows the default option. Here are my codes: models.py class Marcasmodelos(models.Model): marca = models.CharField(db_column='Marca', primary_key=True, max_length=20) # Field name made lowercase. class Meta: managed = False db_table = 'marcasmodelos' class Modelos(models.Model): modelo = models.CharField(db_column='Modelo', primary_key=True, max_length=45) # Field name made lowercase. marca = models.CharField(db_column='Marca', max_length=45) # Field name made lowercase. class Meta: managed = False db_table = 'modelos' forms.py class MarcasForms(forms.ModelForm): class Meta: marca=Marcasmodelos fields= '__all__' class ModeloForm(forms.Form): marca = forms.ModelChoiceField(queryset=Marcasmodelos.objects.all().values(), widget=forms.Select(attrs={'class': 'custom-select'})) modelo = forms.CharField(max_length=100) formModelos.html (my form) <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="container"> <div class="row"> <div class="form-group"> <div class="mb-3"> <label for="marca">Marca:</label> <select name="marca" class="form-control custom-select" id="marca"> <option value="">Selecciona una marca</option> {% for marca in marcas %} <option value="{{ marca.id }}">{{ marca }}</option> {% endfor %} </select> </div> </div> <div class="col-fluid"> <div class="mb-3"> <label for="modelo" class="form-label">Modelo</label> <input type="{{ campo.field.widget.input_type }}" class="form-control" id="modelo" name="modelo" placeholder="Modelo del Producto"> {% if campo.errors %} <div class="invalid-feedback">{{ campo.errors }}</div> {% … -
How to use two database one for development and other production in the same application django
I have two databases one for development and other for the production, i set two dbs in my settings, but how can i alternate between the two dbs. Now i use method using in all objects, but i dont know if it`sthe best form. settings.py DATABASES = { 'default': { 'ENGINE': os.getenv('DB_PRODUCTION_ENGINE', 'change-me'), 'NAME': os.getenv('POSTGRES_PRODUCTION_DB', 'change-me'), 'USER': os.getenv('POSTGRES_PRODUCTION_DB_USER', 'change-me'), 'PASSWORD': os.getenv('POSTGRES_PRODUCTION_DB_PASSWORD', 'change-me'), 'HOST': os.getenv('POSTGRES_PRODUCTION_HOST', 'change-me'), 'PORT': os.getenv('POSTGRES_PRODUCTION_PORT', 'change-me'), }, 'development': { 'ENGINE': os.getenv('DB_DEVELOPMENT_ENGINE', 'change-me'), 'NAME': os.getenv('POSTGRES_DEVELOPMENT_DB', 'change-me'), 'USER': os.getenv('POSTGRES_DEVELOPMENT_DB_USER', 'change-me'), 'PASSWORD': os.getenv('POSTGRES_DEVELOPMENT_DB_PASSWORD', 'change-me'), 'HOST': os.getenv('POSTGRES_DEVELOPMENT_HOST', 'change-me'), 'PORT': os.getenv('POSTGRES_DEVELOPMENT_PORT', 'change-me'), } } example queryset def get_database_name(request): environment = request.session.get('environment', 'default') return environment using = get_database_name(request) model = Model.objects.using(using) -
Not Showing Browsable Api interface in djanog rest framework
not showing browsable api interface in django rest_framework http://127.0.0.1:8000/api here is my code auth_app/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager,PermissionsMixin class CustomUserManager(BaseUserManager): def create_user(self,email,password=None,**extra_fields): if not email: raise ValueError('The Email Field must be set') email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,password=None,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self.create_user(email,password,**extra_fields) class CustomUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] def __str__(self): return self.email auth_app/serializers.py from rest_framework import serializers from .models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id','email','first_name','last_name','is_active','is_staff') auth_app/views.py from rest_framework import generics,permissions,status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .serializers import CustomUserSerializer class RegistrationAPIView(APIView): def post(self,request): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) return Response( { "refresh": str(refresh), "access": str(refresh.access_token), }, status=status.HTTP_201_CREATED, ) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) class LoginAPIView(APIView): def post(self,request): email = request.data.get("email") password = request.data.get("password") user = authenticate(request, email=email,password=password) if user: login(request,user) refresh = RefreshToken.for_user(user) return Response( { "refresh":str(refresh), "access": str(refresh.access_token), }, status=status.HTTP_200_OK ) return Response({"error":"Invalid Credentials"},status=status.HTTP_401_UNAUTHORIZED) @method_decorator(login_required,name="dispatch") class LogoutAPIView(APIView): def post(self,request): logout(request) return … -
Wagtail SSL issue running locally with ip instead localhost
Is there anyone who is familiar with disabling SSL redirection in a Python Django/Wagtail project? We're currently experiencing an issue on our local setup where the site isn't functioning properly with an IP address, unless it's using "localhost" and its specific IP address. If you have a solution or any insights into this matter, kindly send me a direct message. Your assistance would be greatly appreciated. Thanks. Tried with the SSL disable configuration but still not worked -
Why is file download not working in my Django view?
The view function in my Django application is designed to transcribe a file and generate a subtitle file in .srt format. It then identifies the transcript file and is expected to automatically download it. However, currently, the automatic download does not occur. The file was submitted on a different page that uses the transcribeSubmit view, while the initiate_transcription view is responsible for handling and returning the file. Here is my views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) #transcribe_file(uploaded_file) #return redirect(reverse('proofreadFile')) return render(request, 'transcribe/transcribe-complete.html', {"form": form}) else: else: form = UploadFileForm() return render(request, 'transcribe/transcribe.html', {"form": form}) @csrf_protect def initiate_transcription(request): if request.method == 'POST': # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcribe_file(path_string) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, '.srt') transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name) file_location = transcript_path with open(file_location, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"' return response else: #complete return render(request, 'transcribe/transcribe-complete.html', {"form": form}) def …