Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS'
I have a JSON value that comes directly from a DB that has this label GERP++_RS This is part of a big dictionary and I need to display the correspondent value on a HTML page, but Django gives me this error Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS' What would be best strategy to retrieve the value from this key? Would I need to process it before it gets to the template? Thanks in advance -
how to run django in pycharm in https
I need to run a python Django project with Pycharm IDE locally in HTTPS so that other services can talk with my service without any errors. I don't manage to run it locally in HTTPS -
Passing and using the request object in django forms
I'm trying to user the request object to create a dynamic dropdown list in my form using the following code: view: form = TransactionForm(request.user) form: class TransactionForm(forms.Form, request.user): # Payment methods get_mm_details = MMDetails.objects.filter(username=request.user) get_card_details = CardDetails.objects.filter(username=request.user) payment_meth = [] # form fields trans_amount = forms.IntegerField(label="Amount", min_value=0) payment_method = forms.CharField( label='Payment method', widget=forms.Select( choices=payment_meth ) ) is there a way of using the request object in a form? -
Django --- how to get pdf model upfront in a html download button?
I would like to create a HTML button where it loads the pdf file from the database. Do you know how to create the button to upload the latest pdf file from the model? Below is my code so far from the model: class PdfLoad(models.Model): file = models.FileField(upload_to='Portfolios/') Code for admin.py: admin.site.register(PdfLoad) Code HTML code: <!-- Download link --> <section class="about section" id="CV"> <h2 class="section-title">Curriculum Vitae</h2> <div class="d-flex justify-content-center"> <a href ="{{pdf.file}}"><button type="submit" class="cv__button" onclick="blank">CV</button></a> </div> </section> do I have to do something for the setting.py file ?? -
Filter Dataset Based on Account Log In
I'm trying to filter the dataset shown in my table based on the user that logged in within the previous page. My app is set up in a way that it's a simple log-in screen where you put a username and password, and then there's a single dataset feeding two screens: 1 = Week, 2 = Picks. On the first screen, you select which week you'd like to select picks for, and once you click into a week you can change your picks. When I've built apps in different solutions, my idea was to store username or week as a variable and then filter the dataset to just records pertaining to that criteria, but I'm not sure how to do that in Django. Thoughts? I have the following code: views.py class PickList(LoginRequiredMixin, CoreListView): model = Pick def user_picks(request): Pick.objects.filter(submitter={{ request.user.get_full_name|default:request.user }}) return render(request, 'app/pick_list.html', {'Pick': Pick}) app urls.py urlpatterns = [ path('', home, name='home'), path('picks/', PickList.as_view(), name='pick-list'), path('pick/<int:pk>/', PickDetail.as_view(), name='pick-detail'), path('picks/<str:submitter>', user_picks(), name='pick-list'), path('weeks/', WeekList.as_view(), name='week-list'), path('weeks/<int:pk>/', WeekDetail.as_view(), name='week-detail'), ] account urls.py urlpatterns = [ path('login/', views.LoginView.as_view(template_name='account/signin.html', authentication_form=AuthenticationForm, extra_context={ 'title': 'Login', 'extra_title': 'Please sign in', }), name='login'), path('logout/', views.LogoutView.as_view(next_page='account:login'), name='logout'), ] models.py class Pick(models.Model): submitter = models.CharField(max_length=50, verbose_name='Submitter', null=True, blank=True) … -
Custom User return empty get_all_permissions()
I'm just trying start work with Permissions to learn how thats work. In shell i have empty set() result. I see this question, is the same of that, but i can't find what is missing im my code: I creared Custom User from AbstractBaseUser, so my model is like: settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = [ 'users.backends.CustomModelBackend', ] models.py class UserManager(BaseUserManager): def create_user(self, email, username, phone, password = None): ... def create_superuser(self, email, username, phone, password = None): ... class User(AbstractBaseUser, PermissionsMixin): ... objects = UserManager() ... def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True backends.py class CustomModelBackend(backends.ModelBackend): def user_can_authenticate(self, user): return True In shell i try something like: >>> from users.models import User >>> user_test = User.objects.get(email="user@example.com") >>> user_test.get_all_permissions() set() That user is superuser. What is needed to check that permissions? -
Filter for several items of the same field Django
I have a view like this: class ProductViewSet(viewsets.ModelViewSet): ... filter_class = ProductFilter and ProductFilter: class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['brand'] the problem is that when I send a GET /products/?brand=Adidas+Nike, I get an error [ "Select a valid choice. Nike Adidas is not one of the available choices." ] How can I fix it that it will filter for several items of the same field. -
django filter a prefetch_related queryset
I am trying to use prefetch_related with a model with foreign key because I then need to query the database within a loop. models.py class SelfEvaluatedStatement(models.Model): evaluation_statement = models.ForeignKey(EvaluationStatement, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default=0) views.py queryset = SelfEvaluatedStatement.objects.prefetch_related( 'evaluation_statement__sku__topic__subject', 'evaluation_statement__sku__level' ).filter( evaluation_statement__sku__topic__subject=subject, evaluation_statement__sku__level=level ) for student_user in student_users: red_count = queryset.filter(user=student_user, rating=1).count() However, this hits the database with a new query each time I iterate through the loop. Is it possible to filter a queryset which has been prefetched, or am I thinking about this incorrectly? -
Getting and Resuming from Process ID in Python 3
I am developing a testapp in django for internal computing usage. I am using Octave (open source version of Matlab). The idea is to give the user a web interface, where user will type commands, and the commands will go to backend, get executed in octave, and return the results. And the key is to remember the values of all variables that the user has set previously without any recourse to database as octave does it automatically. The problem I am facing is that once I return from backend, I loose the parameter values. In essence, I create a shell process in django view using import subprocess; subprocess.run('a=2'). I capture the output and send it back to UI. And lets say user sends another command subprocess.run('a = a + 2'). But this time when I try to execute in backend, I am going to get error, because the value of parameter a is lost!! To make matters worse multiple users can access this app at the same time with their own set of data and operations. Now my question how can I get process ID of shell created using python, and resume later on using the same process ID and … -
Ajax url with parameter. The current path didn’t match any of these
I'm new in django. I try to delete element from database by ajax call. My ajax call send url with parameter which is pk of element to delete. Url looks fine but browser raise error that url pattern doesn't match to any of urlpatterns in my url.py. I have done similar project before and everything workerd good so I'm confused why it does't work now. Any Idea? urls.py: urlpatterns = [ path('', views.home,name='home'), path('mojerec',views.mojeRec,name='mojerec'), path('dodajrec',views.dodajRec,name='dodajrec'), path('receptura/(<int:receptura_id>)',views.receptura,name='receptura'), path('formJson/<str:skl>/', views.formJson, name='formJson'), path('receptura/formJson/<str:skl>/', views.formJson, name='formJson'), path('receptura/dodajskl/<str:sklId>/', views.dodajsklJson, name='dodajsklJson'), path('receptura/aktualizujTabela/<str:sklId>/', views.aktualizujTabela, name='aktualizujTabela'), path('receptuta/delSkl/<int:id>/', views.delSkl, name='delSkl'), ] views.py def delSkl (request,id): deletedElement=Skladnik.objects.filter(pk=id) response=serializers.serialize("python", deletedElement) deletedElement.delete() print('response', response) sys.stdout.flush() return JsonResponse({'response':response}) myjs.js function usuwanieSkladnika (pk){ $.ajax({ type: 'GET', url: `delSkl/${ pk }/`, success : function(response){console.log('sukces ajaxa z del'); cardBox.innerHTML='' tabelaDocelowa.innerHTML=''; updateTable() },//koniec sukcesa error : function (error){console.log('brak sukcesu ajaxa z del')}, }) } log: Page not found (404) Request Method: GET Request URL: http://localhost:8000/receptura/delSkl/13/ Using the URLconf defined in recipe.urls, Django tried these URL patterns, in this order: admin/ [name='home'] mojerec [name='mojerec'] dodajrec [name='dodajrec'] receptura/(<int:receptura_id>) [name='receptura'] formJson/<str:skl>/ [name='formJson'] receptura/formJson/<str:skl>/ [name='formJson'] receptura/dodajskl/<str:sklId>/ [name='dodajsklJson'] receptura/aktualizujTabela/<str:sklId>/ [name='aktualizujTabela'] receptuta/delSkl/<int:id>/ [name='delSkl'] users/ The current path, receptura/delSkl/13/, didn’t match any of these. -
Django - i have add onclick function into html and whenever i click into different button then it will render the same data. how to fix that?
<div class="home-food-row"> {% if allmenu %} {% for menu in allmenu %} <div class="home-food-menu-col"> <div class="filterDiv breakfast"> <div class="img-price-tag"> <div class="price-tag" id="price">{{menu.price}} only</div> <img class="home-page-food-img" src="{{menu.food_img.url}}" alt="Food" width="100%"/> </div> <h1 id="foodName_1">{{menu.food_name}}</h1> <p>{{menu.food_description}}</p> <button id="order" onclick="myFunction()">Place Order</button> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p>No Food</p> </div> {% endif %} </div> /////////////////////////// JS Code //////////////////////////// function myFunction() { var price = document.getElementById("price"); var food = document.getElementById("foodName_1"); console.log(food); console.log(price); } enter image description here enter image description here -
how to get attribute from other model in your django template
SO I have these two models, One is Members other is PaymentDetail. What I want is all the members from Member model in my template which I can get from Members.object.all() but also I want the payment_status of all those members in my template next to them. I dont know how to do it as payment_status is not in the Member model. class Members(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status') mem_note = models.TextField(null=True, blank=True) class PaymentDetails(models.Model): mem = models.ForeignKey(Members,on_delete=models.CASCADE, related_name="payment_details",verbose_name='Memeber Phone no') com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') payment_month = models.DateField(default=datetime.now()) payment_amount_debit = models.IntegerField(null=True,blank=True) payment_amount_credit = models.IntegerField(null=True,blank=True) payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1") payment_proof = models.ImageField(upload_to='images/') payment_note = models.TextField(null=True,blank=True) I searched alot and Found out there is somehting called related name and setname, but I am kinda new so I am not getting the desired results by using them too. -
Using data from the select tag to make queries based on the given id
I'm trying to make queries or to filter data based on the given id from the select tag that I have in the html. In the index.html I have the following: <div class="row"> <label for="patientId">Choose a patient:</label> <select name="patient" id="patient"> {% for item in patientId %} <option value="{{item}}"> {{item}} </option> {% endfor %} </select> In this select I have all the ids from the database, in the same page, I also have a chart that should display data based only on this id from the select tag. For this, I have the data declared in a script tag: var ctx = document.getElementById("weeklyChart"); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: {{ hourArray|safe}}, datasets: [{ label: "Value", lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", borderColor: "rgba(78, 115, 223, 1)", pointRadius: 3, pointBackgroundColor: "rgba(78, 115, 223, 1)", pointBorderColor: "rgba(78, 115, 223, 1)", pointHoverRadius: 3, pointHoverBackgroundColor: "rgba(78, 115, 223, 1)", pointHoverBorderColor: "rgba(78, 115, 223, 1)", pointHitRadius: 10, pointBorderWidth: 2, data: {{ glucoseArray|safe}}, }], }, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", titleMarginBottom: 10, titleFontColor: '#6e707e', titleFontSize: 14, borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, intersect: false, mode: 'index', caretPadding: 10, callbacks: { label: function(tooltipItem, chart) { var datasetLabel … -
Drag and Drop sorting with django and ajax
I want to add drag and drop functionality to the players field. I want to know what are the conditions and requirements for this kind of scenario. What are the steps should I follow? For now, players are stored as we select them (so first selected goes first). I also want to save the order after drag and drop, any suggestions or question improvements will be a great support. Models.py class Group(TimeStampModel, PermissionsMixin): name = models.CharField(_("Group name"), blank=False, max_length=127, unique=False) phase = models.ForeignKey("Phase", related_name="groups", on_delete=models.CASCADE, blank=False, null=True) class Meta: ordering = ["name"] Forms.py: I'm using modelMultipleChoiceField for now. class GroupCreateForm(ModelForm): players = ModelMultipleChoiceField(queryset=None, help_text=_("Please hold down 'Control', to select more than one player")) def save(self, commit=True): group = super(GroupCreateForm, self).save(False) group.phase = self.instance.phase group.created_by = get_request().user if commit: group.save() if self.instance: for player_id in self.cleaned_data['players']: player = Player.objects.get(pk=player_id) ranking = GroupRanking(order=0, player=player, group=group) ranking.save() # Trigger a compute on saving group.phase.ruleset.computeScores() return group class Meta: model = Group fields = ("name",) views.py class GroupCreateView(AccessControlMixin, CreateView): model = Group form_class = GroupCreateForm template_name_suffix = '_create' def has_access(self, user): return self.can(" ", self.phase.tournament) def get_success_url(self): return "%s" % reverse("tournaments:detail", kwargs={"pk": self.kwargs['pk']}) def dispatch(self, request, *args, **kwargs): self.phase = get_object_or_404(Phase, pk=kwargs['rpk']) return super(GroupCreateView, … -
Pagination causes duplicate elements in Django
I've the following ListView: class SentencesListView(ListView): model = Sentence paginate_by = 10 def get_queryset(self): return Sentence.objects.all().order_by('-proficiency') When the user interacts with the webpage, proficiency of all Sentences on the displayed page increases. As a result, when get_queryset will be called again (when user visits the next page), he'll see the same sentences as he did on the previous page. How can I prevent this? I've tried the following which didn't work: class SentencesListView(ListView): model = Sentence paginate_by = 10 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cached_query_set = None def get_queryset(self): if not self.request.GET.get('page') or not self.cached_query_set: self.cached_query_set = Sentence.objects.all().order_by('-proficiency') return self.cached_query_set self.cached_query_set is never not None when the test is performed inside get_queryset. Hence, the query set is always computed anew when moving to the next page. Is there a way to prevent users from experiencing duplicates? Or, is there a way to prevent get_queryset from being called when moving to the next page? -
Django The QuerySet value for an exact lookup must be limited to one result using slicing Error
I have this problem when I want to show all of the post that related to category. I couldn't find the solution in other similar questions. Thank you. Error: The QuerySet value for an exact lookup must be limited to one result using slicing. Model: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse("post", kwargs={'slug': self.slug}) View : class PostListView(ListView): """ Return all of the posts """ model = Post ordering = '-created' context_object_name = 'posts' template_name ='blog/post_list.html' def get_queryset(self): qs = Post.objects.all() if self.kwargs.get('slug'): category_slug = self.kwargs.get('slug') qs = Post.objects.filter(category = Category.objects.filter(slug = category_slug)) return qs URL: path('', PostListView.as_view(), name='posts'), # all of the posts path('category/<slug:slug>/', PostListView.as_view(), name='categoryposts'), Template: <div class="row"> {% for post in posts %} <div class="col-md-4"> <div class="card" style="width: 25rem; height: 34rem;"> <a href="{% url 'post' post.slug %}"> <img class="post-thumbnail card-img-top" src="{{post.thumbnail.url}}" alt="{{post.title}}" style="width: 24.9rem; height: 18rem;"> </a> <div class="card-body"> <h5 class="card-title"><a href="{% url 'post' post.slug %}">{{post.title}}</a></h5> <p class="post-updated">Last update at {{post.updated|date:"Y/M/d"}}</p> <p>Post by <a href="">{{post.author}}</a></p> {% if post.description %} <p class="card-text">{{post.description|slice:"80"}}...</p> {% else %} <p class="card-text">{{post.body|slice:"80"}}...</p> {% endif %} <a href="{% url 'post' post.slug %}" … -
django: get() returned more than one Freelancers -- it returned 3
i am trying to assign a freelancer to a particular gig but it shows get() returned more than one Freelancers -- it returned 3!. I have tried getting the logged in freelancer to is trying to create the git like this freelancer = get_object_or_404(Freelancers, user=user) and before i save the form i assign the value like this new_form.creator = freelancer . views.py @login_required def create_gig(request): user = request.user freelancer = get_object_or_404(Freelancers, user=user) if request.method == "POST": form = CreateGig(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.creator = freelancer new_form.slug = slugify(new_form.title) new_form.save() messages.success(request, f'Gig Created Successfully, Would be Live Soon') return redirect('freelance:listings') else: form = CreateGig() context = { 'form': form } return render(request, 'freelance/create.html', context) models.py class Gigs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gig_user') creator = models.ForeignKey(Freelancers, on_delete=models.CASCADE, related_name='gig_creator') title = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Enter what you will do", default=" I will ") -
Django ManyToMany model: unable to access one relation from the other
My models.py: class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField( "Book", related_name="books", blank=True ) class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(Author) In Django admin I first created an instance of Author, without assigning him any Book: Then I created a new Book and assigned Leo Tolstoy as theAuthor: In Django shell, I am able to access the Book's Author: >>> Book.objects.filter(title="War and Peace").first().author.first() <Author: Leo Tolstoy> But I'm unable to access the Author's Books: >>> Author.objects.filter(name="Leo Tolstoy").first().books.all() <QuerySet []> The book isn't assigned in the Admin view either: I would like to access the Author's Books as well as for the Books to show in the Author's Admin view. -
How can I send localstorage data from JavaScript ajax call and print return data from views in Django template
I have stored some data on localStorage( Itemnames and ItemIds), now I want to send itemid's to django views from ajax. I have basics knowledge of django and learning Javascript. I tried to figureit out by myself but its been more than 4 days I could not succeed, any help will be highly appreciated. My Javascript: $(document).ready(function() { var compare = localStorage.getItem("comparisionItems"); var compareObj = JSON.parse(compare); var data_url = window.location.href; console.log(compare) console.log(compareObj) $.ajax({ url: './compare', type: "POST", data: {'compare_id': compareObj }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, dataType: "json", success: function (data) { console.log(data) }, error: function () { alert("Please login"); } }); }); My views: def compare(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax and request.method == "POST": compare_id= request.POST.getlist('compare_id[itemIds]') """compare_id=request.POST.getlist('itemIds[]') """ """compare_id = request.POST.get('compare_id')""" product = get_object_or_404(Products, id=compare_id) context={ 'product':product} """ return render (request, './ecommerce/compare.html', context)""" return render (request, './compare.html', context) else: context = None return render(request,'./compare.html', context) How can I get the products which have id's pass by ajax? And is there any different ways to pass those products to the template or I can do it just like the regular Django context process? -
Group By with Django, with distinct() in one especific field
My goal is get all charge in one particular segment, distinct by user, and group by origin_province and destination_province, so: From this query: charges = charges_mean.filter(numbers_pallets = num).order_by().values('charger').distinct() I would like to group by 'origin_province' and 'destination_province', fields in Charges table, but it only response 'charger' value, obviously, and I do not know how do it. I tried something like this, but it doesn't work without Potgress Database: Mymodel.objects.filter(...).annotate(distinct_name=Concat('tcode', 'created_on', output_field=TextField())).order_by('distinct_name').distinct('distinct_name') I get it from this post: Django distinct group by query on two fields -
I am stuck when accessing the DetailView template in Django
urls.py urlpatterns = [ path('',CourseList.as_view(),name='course_list'), path('create/',CourseCreate.as_view(),name='course_create'), path('<int:cid>/',CourseView.as_view(),name='course_view'), ] views.py COURSE_PERM_GUEST = 0 COURSE_PERM_STUDENT = 1 COURSE_PERM_TEACHER = 2 COURSE_PERM_MEMBER = 3 class CourseAccessMixin(AccessMixin): permission = None extra_context = {} def dispatch(self,request,*args,**kwargs): if not request.user.is_authenticated: return super().handle_no_permission() self.course = get_object_or_404(Course,id=kwargs['cid']) user_perm = COURSE_PERM_GUEST if self.course.teacher == request.user: user_perm = COURSE_PERM_TEACHER elif self.course.enroll_set.filter(student=request.user).exists(): user_perm = COURSE_PERM_STUDENT if not request.user.is_superuser and self.permission is not None: is_accessible = False if self.permission == COURSE_PERM_GUEST and \ user_perm == COURSE_PERM_GUEST: is_accessible = True elif (self.permission & user_perm) != 0: is_accessible = True if not is_accessible: return super().handle_no_permission() self.extra_context.update({'course':self.course}) return super().dispatch(request,*args,**kwargs) class CourseView(CourseAccessMixin,DetailView): extra_context = {'title':'檢視課程'} model = Course pk_url_kwarg = 'cid' models.py class Course(models.Model): name = models.CharField('課程名稱',max_length=50) enroll_password = models.CharField('選課密碼',max_length=50) teacher = models.ForeignKey(User,models.CASCADE) def __str__(self): return '{}#{} ({})'.format( self.id, self.name, self.teacher.first_name) course_list.html {% extends "base.html" %} {% load user_tags %} {% block content %} {% if user|is_teacher %} <div class="mb-2"> <a href="{% url 'course_create' %}" class="btn btn-sm btn-primary">建立課程</a> </div> {% endif %} <div id="course_list"> {% for course in course_list %} <div class="list-group"> <div class="list-group-item d-flex"> {% if user.is_authenticated %} <a href="{% url 'course_view' course.id %}">{{ course.name }}</a> {% else %} {{ course.name }} {% endif %} <small class="ml-auto">{{ course.teacher.first_name }} 老師</small> </div> </div> {% endfor %} … -
Django views best practice : explicit or implicit context?
I'm wondering if there is a 'best' solution between explicit context definition and implicit use of locals() parameter in view rendering. The original way of doing is to 'declare' each variable to be used in the context of a view, thanks to a dictionary, but Django proposes some shortcuts and also offers the ability to take into account all variables defined in a view to be part of the context. Are there any differences between both options (context variable defined in a dict vs 'locals()'), and is one of them 'better' (and why?)? Btw (subsidiary question): I'm quite new to Django and I never used return HttpResponse(...) but always return render(...), am I wrong? -
Django launch windows app from website Django?
in an application, I want to open the zoom application on the user's computer from my website, how can I do this? -
Which method of 'Django Serializer' do I need to customize?
The frontend sends the json in an array. I received the value with difficulty as shown in ex) below. ex) applier_phone = data.get('phone')[0] applier_name = data.get('name')[0] applier_birth = data.get('birth')[0] applier_gender = data.get('gender')[0] But I want to get the value using Serializer. In this case, which method of Serializer do I need to customize? -
Django pdf file not finishing its downloading in browser
views.py def showName(request): if request.method == 'POST': uploaded_file = request.FILES['user_initial_pdf'] if uploaded_file is not None: import PyPDF2 import os from io import BytesIO from django.conf import settings #Merging 2 pdf files pdfObject1 = PyPDF2.PdfFileReader(uploaded_file) pdfWriter1 = PyPDF2.PdfFileWriter() for pageNum in range(pdfObject1.numPages): pageObj = pdfObject1.getPage(pageNum) pdfWriter1.addPage(pageObj) for pageNum in range(pdfObject1.numPages): pageObj = pdfObject1.getPage(pageNum) pdfWriter1.addPage(pageObj) pdfOutputFile = BytesIO() pdfWriter1.write(pdfOutputFile) #using FileSystem storage to store the merged pdf in merdia directory fs = FileSystemStorage() fs.save(uploaded_file.name,pdfOutputFile) #getting the file path file_path = settings.MEDIA_ROOT +'/'+ uploaded_file.name #creating wrapper of file object of the required pdf to be sent as downloadable file to client side wrapper = FileWrapper(open(file_path,"r",encoding="utf8")) response = HttpResponse(wrapper, content_type = 'application/pdf') response['Content-Length'] = os.path.getsize( file_path ) response['Content-Disposition'] = 'attachment; filename="sample.pdf"' return response else: return HttpResponse("File has not been uploaded or is empty!") return HttpResponse("No Post method") Above is the function in views.py which takes in a single pdf and basically merge with itself and send it back to the user. Error/Issue: For some reason my pdf file seems to be stuck at near completion and never finishes Note: I have just started learning django and I am not using any models as of such since I havent started yet so please forgive me …