Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DEBUG = False / "Server Error (500)" - Django
I have a fully built Django python website and now I'm launching it into production. I'm trying to set DEBUG equal to False for production with limited success. I have been working on this problem on and off for about a week and here is what I've got. settings.py DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) This makes most pages work and I think the pages where it works are the HTML pages that are extended from another page that looks for the CSS files and images in the head tag or at least that is the only correlation I can see. Some pages properly show the contents and when there is an error it shows "Server Error (500)" or something along those lines. For other pages that don't work, they never display the proper contents and just automatically show "Server Error (500)" or something along those lines. When it does always give this error I get an error in my terminal that says raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'style.css' I do have a static CSS file called style.css that contributes to some of … -
got an error while connecting MySQL to Django as backend database
In order to connect MySQL as Backend Language for Django I have made some changes in settings.py and I have given the changed code below # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'PASSWORD':'2684', 'HOST':'127.0.0.1', 'PORT':'3306', 'USER':'root' } } after saving it and while I execute the command python manage.py makemigrations I got an Error mentioned E:\Python\sample_django\root>python manage.py makemigrations C:\Users\2684j\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (1193, "Unknown system variable 'default_storage_engine'") warnings.warn( No changes detected My database Details given below database Name : django MySQL password : 2684 Port : 3306 Host : localhost User : root -
How to apply throttling just to create action in DRF viewsets?
I have a viewset and I want to apply throttling to only create action of that viewset and I don't want it to be applied to update, destroy, retrieve and etc... class UserViewSet(viewsets.ModelViewSet): # should only be applied to the create action throttle_classes = [SomeThrottle] ... -
How to install django with python3.9 on ubuntu aws
I'm having challenges installing django using the command sudo python3.9 -m pip install Django. The error I get running that command is: Traceback (most recent call last): File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/usr/lib/python3/dist-packages/pip/__main__.py", line 19, in <module> sys.exit(pip.main()) File "/usr/lib/python3/dist-packages/pip/__init__.py", line 217, in main return command.main(cmd_args) File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 242, in main with self._build_session( File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 66, in _build_session session = PipSession( File "/usr/lib/python3/dist-packages/pip/download.py", line 321, in __init__ self.headers["User-Agent"] = user_agent() File "/usr/lib/python3/dist-packages/pip/download.py", line 93, in user_agent zip(["name", "version", "id"], platform.linux_distribution()), AttributeError: module 'platform' has no attribute 'linux_distribution' When I created the aws ubuntu server instance I ran python3 -V and the ouput was that python3.5 was running on the machine. I upgraded it to python 3.9. Now when I run python3 -V the output is: Python 3.9.4. After upgrading to python3.9 I created and activated another virtual enviroment. Now when I try to install django using the command sudo python3.9 -m pip install Django I get the above error. If I use sudo python3 -m pip install Django the django is installed with python3.5 because, thereafter when I run sudo python3 manage.py migrate it … -
how do i run this program from git hub properly
I am trying to run this program from Github (https://github.com/dhvanilp/Hybrid-Cryptography) I can't seem to do it right either that or it's is broken please help me confirm this. If it works how do I run it properly. I have followed the instructions provided verbatim and it still would not work. -
Wagtail Images Suddenly Not Rendering on Front End
I have just encountered an odd problem I'm trying to debug but cannot figure out what is wrong. I have a wagtail site with images that were all working. At one point I refreshed the browser, and the images suddenly all disappeared from every page. wagtailimages_tags is there static is all loaded the images are all in the correct media directory as specified and have been uploaded through the CMS if i inspect element, the image is in fact coming through in the code perfectly. But the site itself just does not show the image. I have checked the CSS and nothing has changed there and it is not hiding the image somehow. My last resort - I actually started the project over completely in a new environment and added each application one by one to see if I could solve the issue ... nope. No images on the new install from scratch either! No idea why all the images would suddenly just fail to appear in browser. Just seems super strange to me. Any ideas on debugging appreciated. -
Creating new Objects instead of updating - Django
I am trying to use Update in Django, but it is not being updated, rather a new object of the model is being created in the database. For example, if I try to change product label "Laptop" to "Smartphone", Django creates a new product called "Smartphone" instead of updating "Laptop". This is my code Model: class Products(models.Model): label = models.CharField(max_length=50) description = models.CharField(max_length=250) first_price = models.FloatField(null=True) price = models.FloatField() quantity = models.IntegerField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.label @property def imageURL(self): try: url = self.image.url except: url = '' return url Form: class ProductForm(ModelForm): class Meta: model = Products fields = ['label', 'description', 'first_price', 'price', 'quantity', 'image'] View: @login_required(login_url='login') def editProduct(request, id): product = Products.objects.get(id=id) form = ProductForm(instance=product) if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Product was edited.') return redirect('index') context = { 'form': form } return render(request, 'store/edit-product.html', context) Template: <h3>Edit Product</h3> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.label.label }} {{ form.label }} {{ form.description.label }} {{ form.description }} {{ form.first_price.label }} {{ form.first_price }} {{ form.price.label }} {{ form.price }} {{ form.quantity.label }} {{ form.quantity }} {{ form.image.label }} {{ form.image }} <input type="submit" name="Add product"> {{form.errors}} </form> Thank you … -
Django admin set fk_name = to_field in inline class only allows one image to be uploaded
I am new to Django and I ran into a problem when I tried enable the admin to add multiple images to a user profile at once. I created a Model Profile that allows a user to have one profile, and can have more than one photo in the profile. I want to use user_id to link images to profile and use user_id for filter. However, when I tried to upload more than one photo to a profile, it displays error. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, ) GENDER_CHOICES = ( ('F', 'Female'), ('M', 'Male') ) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, default='F', blank=False, choices=GENDER_CHOICES ) about_me = SizedTextField( size_class=2, null=True, blank=True ) date_created = models.DateTimeField(default=timezone.now) class Photos(models.Model): user = models.ForeignKey( Profile, to_field='user', null=True, blank=True, on_delete=models.SET_NULL ) photo = models.ImageField( upload_to='photos/%Y/%m/%d/', blank=True ) admin.py class PhotosInline(admin.TabularInline): model = Photos fk_name = 'user'#only one photo allowed to be uploaded, I want more than one @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'date_of_birth','gender', 'about_me'] inlines = [PhotosInline,] Why does it only allow one photo to be uploaded? What must I do? -
I keep getting a 'There is no current event loop in thread 'Stream''
I'm trying to redo a project based on a github repo I found a while back. When I try to run the author's code I get the 'There is no current event loop in thread 'Stream''. I've looked online through some stackoverflow questions that had the same issue I'm facing but none of their code seems to be similar to mine. They all have used the Asyncio package while I opted for the Threading package. Here's the code to the python file where the error occurs: import base64 import cv2 import time from threading import Thread import RPi.GPIO as GPIO import collect import visit import os #import save #from pymongo import MongoClient GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(27, GPIO.OUT) class Stream(Thread): def __init__(self): self.flag = [False] self.capture_flag = [False] #self.ws = ws self.clients = [] Thread.__init__(self, name=Stream.__name__) def run(self): self.camera = cv2.VideoCapture(0) prev_input = 1 #mongo_db = MongoClient('localhost',27017) #db = mongo_db.smartbell.visitors while True: # Read camera and get frame rval, frame = self.camera.read() if frame is None: self.camera.release() self.camera = cv2.VideoCapture(0) continue # Send camera stream to web if self.flag[0]: rvel, jpeg = cv2.imencode('.jpg', frame) encode_string = base64.b64encode(jpeg) for client in self.clients: client.write_message(encode_string) # A visitor pushes button but = … -
Select2 in django doesn't show the options
I want to join selections in a form. I have the model "Country" and the model "City". when a user selects a Country only the Cities listed in that country should be listed. The problem is that When I try to do it, in the form I cant see any options, so no country or cities are listed at all. This is my code: forms.py: Blockquote from django import forms from django.forms import ModelForm from .models import Country, City from django_select2.forms import ModelSelect2Widget class AddressForm(forms.Form): country = forms.ModelChoiceField( queryset=Comunidad.objects.all(), label=u"Country", widget=ModelSelect2Widget( dependent_fields={'city': 'city'}, search_fields=['name__icontains'], ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( search_fields=['name__icontains'], max_results=500, ) ) '''''' This is what I have in models.py: class Country (models.Model): name= models.CharField(max_length=20, help_text="Añada Comunidad Autónoma") def __str__(self): return self.name class City(models.Model): name= models.CharField(max_length=20, help_text="Añada provincia") country = models. ForeignKey('Country', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name ''' and, in the template: '''{{form.as_table}}''' What I get is the text: "Country" and "City" followed by a drop down button but it's empty. So I see no Countries and no Cities at all, but database is not empty. I don't know what am I missing. Any help will be welcome. -
How can I convert a Django Project into a Django application inside my own project?
I have found a Django project who's purpose is to send emails to subscribers and it is divided into several applications but I view this project as an application and want to include it in my own project. What are the minimal steps to convert that project into an app ? -
how to verify if input email is already exist in database?
I have an issue with the program am trying to develop. I have a function that will send OTP code to user when they request to login. the OTP code should be sent through email to the registered users. the problem is that my code now accepts every email and it doesn't validate the users from the database. How can I do this? this is my script <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type='text/javascript'> {% block title %} {% endblock %} {% block content %} <h1>OTP Verification Page</h1> <br> <br> <p> </script> <div id="email_div" style="display: block;" > <label for="email">Email</label> <input type="text" name="email" id="email"> <button onclick="ajax_send_otp()">Send OTP</button> </div> <div id="verify_text_div"></div> <div id="otp_div" style="display: none;" > <label for="email">OTP</label> <input type="text" name="otp" id="otp"> <button onclick="verify_otp()">Verify</button> </div> </p> {% endblock %} <script> var otp_from_back=""; function ajax_send_otp(){ document.getElementById("email_div").style.display='none'; email = document.getElementById("email"); $.post("/send_otp", { "email":email.value, "csrfmiddlewaretoken":"{{csrf_token}}" }, function(data, status){ if(status=="success"){ otp_from_back = data; document.getElementById("otp_div").style.display='block'; } } ); } function post(path, params, method = 'post') { const form = document.getElementById('post-form'); form.method = method; form.action = path; for (const key in params) { if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); } } document.body.appendChild(form); form.ajax_send_otp(); } // Submit post on submit var form … -
Django - get id in form
I try to develop a web app with Django and Stripe API. But my problem is i'd like to allow visitor to register/login. Then if the user is connected he can use a form to create a company (one user can get n companys) then when this form is validate there are a redirection to STRIPE API to pay an abonments. So i've theses databases : User (name, adress, ...) Company (company name, employees,...) Transaction(subscription plan, idUser, idCompany) I don't know how to get the CompanyId because when the company form is validate there are a redirection to stripe api then if payment = "ok" redirect to sucess page. I try to use input hidden but its doesn't work because I didn't get the id in the company form because the company didn't create yet. Someone get ideas ? Thanks a lot -
Problems with a Form to Edit a Model in Django - Reverse for 'variable name' not found
I'm currently having an issue to display a form, the following code is a depiction of the problem: views.py class LeadUpdate(UpdateView): model = Leads fields='__all__' template_name_suffix = '_update_form' urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), path('', include('django.contrib.auth.urls')), path('edit/', views.edit, name='edit'), path('add_client/', views.add_client, name='add_client'), path('add_company/', views.add_company,name='add_company'), path('add_lead/', views.add_lead, name='add_lead'), path('add_call/', views.add_call, name='add_call'), path('add_status/', views.add_status, name='status'), path('leads_view/', views.leads_view, name='leads_view'), path('client_view/', views.client_view, name='client_view'), path('deal_view/', views.deal_view, name='deal_view'), path('<int:project_id>/',views.LeadUpdate.as_view(), name='edit_lead') ] The problem I have corresponds to the last URL The dashboard displaying the list and the web app is design such that when the user clicks the number you can edit the form dashboard.html <table class="styled-table"> <thead> <tr> <th>Project ID</th> <th>Agent</th> <th>Company</th> <th>Country</th> <th>Modelling Services</th> <th>Est. Closing Date</th> <th>Est. Revenue</th> <th>Est. # of Licenses</th> <th>Status</th> </tr> </thead> <tbody> {% for lead in leads %} <tr> <td><a href="{% url 'project_id' lead.project_id %}">{{lead.project_id }}</a></td> <td>{{ lead.agent }}</td> <td>{{ lead.company }}</td> <td>{{ lead.country }}</td> <td>{{ lead.modeling_services }}</td> <td>{{ lead.estimated_closing_date }}</td> <td>{{ lead.expected_revenue }}</td> <td>{{ lead.expected_licenses }}</td> <td>{{ lead.status }}</td> </tr> {% endfor %} </tbody> </table> This is the file edit_lead.html {% extends "base.html" %} {% block … -
Check if the last file in os.listdir()
I need to know if the file currently checked in the os.listdir is the last file. I need it in a condition I have. Here is the code: # iterate through all files in directory for filename in os.listdir(edgar_path): # open and read with open(edgar_path + filename, 'r') as file: # rearrange by date (column 3) tsv_file = sorted(list(csv.reader(file, delimiter='|')), key=lambda t: t[3]) # get date today today = datetime.datetime.now() # get start date and end date depending on the first and last row start_date = datetime.datetime.strptime(tsv_file[0][3], "%Y-%m-%d") end_date = datetime.datetime.strptime(tsv_file[len(tsv_file) - 1][3], "%Y-%m-%d") # check print logger.debug(start_date) logger.debug(end_date) # if within date range if start_date <= today <= end_date: logger.debug('pass condition 1') # if not within date range, but # the date today is greater than the end date # and its the last file being checked so it still passes elif today >= end_date: logger.debug('pass condition 2') # add to delete files if both conditions are unmet else: files_to_delete.append(filename) logger.debug('no pass') Any help is appreciated. -
Django How do add reply to rich editor
I create a post and this post's comment in my page. Users can comment on posts and I use rich editor(ckeditor) for this. But I want users to reply on comments too. Because of this, I added "Reply" button. When the user clicks the "reply" button, I want to redirect to ckeditor and add the message to ckeditor. LİKE THİS; Actually, I don't want something that complicated, Just user to know reply to other user it works for me. My models: class UserPosts(models.Model): postTitle = models.CharField(max_length=100, verbose_name="Title") postContent = RichTextUploadingField(null=True, verbose_name="Content") username = models.ForeignKey( User, on_delete=models.CASCADE, blank=True ,null=True, verbose_name="Username") class UserMessages(models.Model): postMessages = RichTextUploadingField(null=True, verbose_name="Message") post = models.ForeignKey( UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) username = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="Username", null=True) My Views: def detail_post(request,_detail): postDetail = UserPosts.objects.get(pk = _detail) messages = UserMessages.objects.all().filter(post_id =postDetail.id) if request.method == "POST": #New Message if request.method == "POST": #New Message form = MessageForm(request.POST,request.FILES) if form.is_valid(): form.instance.username = request.user form.instance.post = postDetail form.save() return redirect("detail",postDetail.id) context= { "detail":postDetail, "messages":messages, "form":form, } return render(request,"DetailPost.html",context) and my HTML: {% if request.user.is_authenticated %} <div class="comment-user "> <form method="POST" class=" "> {% csrf_token %} {{form.media}} <div class="form-group "> {{ form }} </div> <div class=""> <button type="submit" class="btn btn-primary btn-block">Submit</button> </div> … -
What should i use for front-end vue.js/react or django templates?
I know that big projects typically use django REST for back-end and vue.js or react for front-end, so my question is how do I choose what I should do? And why do big projects use two different frameworks? -
i need to create test for my models in django
i need to create some test for one of method of models but i cant do that model in my project: class Member(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def borrowed_books(self, genre): pass def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): title = models.CharField(max_length=50) genre = models.CharField(max_length=50) def __str__(self): return self.title class Borrowed(models.Model): member = models.ForeignKey('Member', on_delete=models.CASCADE) book = models.ForeignKey('Book', on_delete=models.CASCADE) i need create test for borrowed_books borrowed_books get one genre for Input variable and return list of book id this genre i need to Write test for none list variable and return correct lenght But contains incorrect book id class MemberAppTest(TestCase): def setUp(self): ali=Member.objects.create(first_name='xxx', last_name='yyy') Member.objects.create(first_name='zzz', last_name='kkk') Book.objects.create(title='fff' , genre='m') def test_borrowed_books(self): self.assertIsNone(Book.genre) What should I do? -
Pagenation firestore data in python
Hey there i need to Pagenate this code can you guys please help me out i tried the docs but not able to get hold of it. cases = db.collection(u'hospitals').document(request.session['hospital_email']).collection('cases').where( u'status', u'==', "done").where("formstatus", "==", "draft").order_by(u'date').limit(3).get() for i in cases: cases_data[i.id] = i.to_dict() print(cases_data[i.id], " ==>", i.to_dict()) print("") -
Django - how to return a pre_signed s3 (boto3) url to the client for download
I have the following code at my views.py def download(request, pk): obj = get_object_or_404(Files, pk=pk) file = obj.file_path download_url = s3_get_client(endpoint=obj.s3_backend.endpoint, access_key=obj.s3_backend.access_key, secret_key=obj.s3_backend.secret_key, region=obj.s3_backend.region ).generate_presigned_url( ClientMethod='get_object', Params={'Bucket': obj.s3_backend.bucket, 'Key': file}, ExpiresIn=1000 ) return download_url Now I would like to know how I can immediately instruct the clients browser to download the returned download_url. Thanks in advance -
how to download videos in user machine Django
Here is my views.py file from django.shortcuts import render,HttpResponse,redirect import youtube_dl from django.contrib import messages from pytube import * # Create your views here. def home(request): return render(request,'home.html') def download(request): if request.method == 'POST': video_url = request.POST.get('url') if video_url: ydl_opts = {'outtmp1': 'D:/'} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) messages.success(request, 'Video Downloaded.') return redirect('home') else: messages.warning(request, 'Please Enter Video URL') return redirect('home') return redirect('home') How can I download the video file to the user's machine? can anyone help me? -
I have problem when i import Django-Markdownx
i have problem when i import markdownx. i installed Markdownx for Django, and add in url. and i want to in models.py, but it has problem. problem is.. (Import 'markdownx.models' could not be resolved Pylance(reportMissingImports) [3, 6]) And my code Settings.py INSTALLED_APPS = [ 'blog', 'single_pages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'crispy_forms', 'markdownx', ] project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), path('markdownx/', include('markdownx.urls')), path('', include('single_pages.urls')), ] blog/models.py from markdownx.models import MarkdownxField class Post(models.Model): title = models.CharField(max_length=30) hook_text = models.CharField(max_length=100, blank=True) content = MarkdownxField() when i import this line, it has problem -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'WSGIRequest' when a POST request is sent to Django
I'm trying to send a POST request which I have done through Postman and through the command line but I get the same result which is TypeError: int() argument must be a string, a bytes-like object or a number, not 'WSGIRequest' This request is going to my tasks route which then calls the create_task function # backend/tasks/urls.py from django.urls import path from django.views.decorators.csrf import csrf_exempt from . import views urlpatterns = [ path('tasks/', csrf_exempt(views.create_task)) ] This is views.create_task is in backend/task/views.py from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie from celery.result import AsyncResult from rest_framework.parsers import JSONParser from .tasks import create_task @csrf_exempt def run_task(request): if request.method == 'POST': data = JSONParser().parse(request) print("hello") print(data.data) task_type = data.data print(task_type) task = create_task.delay(int(task_type)) return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result } return JsonResponse(result, status=200) Nothing I print is being logged, so I don't know if what I'm doing is being properly parsed, all I get is the error in my title -
camelot-py: ccv2.error: OpenCV(4.5.3) error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
I want to get some data from table in pdf file with library camelot-py in my django project. But when I try to run a simple code, it rise Traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\io.py", line 117, in read_pdf **kwargs File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\handlers.py", line 177, in parse p, suppress_stdout=suppress_stdout, layout_kwargs=layout_kwargs File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\parsers\lattice.py", line 423, in extract_tables self._generate_table_bbox() File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\parsers\lattice.py", line 259, in _generate_table_bbox c=self.threshold_constant, File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\image_processing.py", line 36, in adaptive_threshold gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-c2l3r8zm\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' My code: import camelot pdf_file = 'C:/Users/myuser/Desktop/statement_7022035.pdf' csv_file = 'C:/Users/myuser/Desktop/ex.csv' def export_csv(pdf_file, csv_file): tables = camelot.read_pdf(pdf_file) tables.export(csv_file, f='csv', compress=True) OS: Windows 10 Python version: 3.7.5 All dependencies for Windows have been installed successfully (Ghostscript and ActiveTcl). Camelot-py have been installed with pip (pip install "camelot-py[base]"). My file is text-based PDFs Please, tell me, where I have done mistake. -
how to use (from itertools import chain) to search multiple model
i want to search field of a multiple model in a single search view here is what i tried i know this is not a clean and better way to do that's why i am looking for a clean and better way to do it i read it is possible with (from itertools import chain) but i did not completely understand how to use it in my function based views without passing so many context here is my view def search_item(request): search_item = request.GET.get('search') if search_item: story = Story.objects.filter(Q(title__icontains=search_item)|Q(written_by__icontains=search_item)) news = News.objects.filter(Q(title__icontains=search_item)|Q(written_by__icontains=search_item)) Stock = stock.objects.filter(Q(title__icontains=search_item)|Q(written_by__icontains=search_item)) return render(request, 'search_result.html', {'ttts':ttt,'story':story,'news':news,'stock':Stock,}) thank you