Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
signal only works in main thread: scrappy
I am making an api which return the JsonResponse as my text from the scrapy. When i run the scripts individually it runs perfectly. But when i try to integrate the scrapy script with python django i am not getting the output. What i want is only return the response to the request(which in my case is POSTMAN POST request. Here is the code which i am trying from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt import scrapy from scrapy.crawler import CrawlerProcess @csrf_exempt def some_view(request, username): process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'LOG_ENABLED': 'false' }) process_test = process.crawl(QuotesSpider) process.start() return JsonResponse({'return': process_test}) class QuotesSpider(scrapy.Spider): name = "quotes" def start_requests(self): urls = [ 'http://quotes.toscrape.com/random', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): return response.css('.text::text').extract_first() I am very new to python and django stuff.Any kind of help would be much appreciated. -
catagory/subcatagory/product detail i want to make model data and display the data in template
Please give anyone solution of this problem.i want to make model data and display in template. Category1 ...Subcategory1 ......Video1 ......Video2 ...Subcategory2 ......Video3 ......Video4 Category2 ...Subcategory3 ......Video5 ......Video6 ...Subcategory4 ......Video7 ......Video8 -
categories and details url slugs
I am trying to understand a basic example of adding both categories and detail slugs from 2 related classes. Whereas the /categories alone works, I can't make the /categories/detail working. Here are my files: #Models: class Categories(models.Model): name = models.CharField(max_length=50,unique=True) cat_slug = models.SlugField(max_length=100,unique=True) def __str__(self): return self.name class Details(models.Model): title = models.CharField(max_length=100) det_slug= models.SlugField(max_length=100,unique=True) categorie = models.ForeignKey('Categories', on_delete=models.CASCADE, related_name="Categories") def __str__(self): return self.title #Views: class ListCategorie(DetailView): model = Categories slug_field = 'cat_slug' context_object_name = "listcategories" template_name = "show/categories.html" class DetailCategorie(DetailView): model = Details slug_field = 'det_slug' context_object_name = "categorydetail" template_name = "show/detail.html" #Urls: path('<cat_slug>', views.ListCategorie.as_view(), name='listcategories'), path('<cat_slug>/<det_slug>', views.DetailCategorie.as_view(), name='categorydetail'), -
exception "unhashable type: 'list'" while following Mozilla django tutorial
I'm working through Mozilla's excellent Django tutorial at https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django, and have introduced a bug I can't find. The tutorial sets up a simple library catalog system. In a previous section the tutorial setup a book detail view, where I could view all instances of a book with a given id by going to: http://192.168.0.28:8000/catalog/book/ This was working fine, but I've somehow managed to trash it. When trying to get to http://192.168.0.28:8000/catalog/book/4 I now get: TypeError at /catalog/book/4 unhashable type: 'list' Request Method: GET Request URL: http://192.168.0.28:8000/catalog/book/4 Django Version: 2.1.1 Exception Type: TypeError Exception Value: unhashable type: 'list' Exception Location: /home/mike/anaconda3/envs/miketestenv/lib/python3.6/site-packages/django/db/models/sql/compiler.py in get_order_by, line 287 Python Executable: /home/mike/anaconda3/envs/miketestenv/bin/python Python Version: 3.6.6 Python Path: ['/home/mike/Projects/locallibrary', '/home/mike/anaconda3/envs/miketestenv/lib/python36.zip', '/home/mike/anaconda3/envs/miketestenv/lib/python3.6', '/home/mike/anaconda3/envs/miketestenv/lib/python3.6/lib-dynload', '/home/mike/anaconda3/envs/miketestenv/lib/python3.6/site-packages'] Server time: Tue, 16 Oct 2018 11:20:39 +0100 Error during template rendering In template /home/mike/Projects/locallibrary/catalog/templates/base_generic.html, error at line 0 unhashable type: 'list' 1 2 3 4 {% block title %}Local Library{% endblock %} 5 6 7 8 9 {% load static %} 10 Book id number 4 is a valid book id. The same error happens for all book ids. The relevant section in urls.py is : path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), From views.py: class BookDetailView(generic.DetailView): model = Book The base_generic.html template is fine, and … -
Why does my Django formwizard code get run even when IF condition is not met?
I'm working with formwizard to create a multi-step form. I am overriding get_form_instance to prepopulate my forms with model data. I have clearly stated an IF conditional: if 'pk' in self.kwargs: This should evaluate as false when I call the wizard view. I do NOT pass in pk as kwargs when calling the wizard view. I use a url like this: path('create/resume/', views.ResumeWizard.as_view(views.FORMS), name='create-resume') My wizard view code looks like this: class ResumeWizard(LoginRequiredMixin, SessionWizardView): login_url = '/login/' def get_form_initial(self, step): if 'pk' in self.kwargs: return {} return self.initial_dict.get(step, {}) def get_form_instance(self, step): if 'pk' in self.kwargs: pk = self.kwargs['pk'] resume = Resume.objects.get(id=pk) if step == 'resumes': return resume elif step == 'work_experience': return resume.workexperience_set.all() elif step == 'certifications': return resume.certification_set.all() elif step == 'education': return resume.education_set.all() elif step == 'skills': return resume.skill_set.all() elif step == 'languages': return resume.language_set.all() else: return None When I run the code, when I create a new form wizard, my steps are populated with model instances from my database. Whats going on here? Shouldn't get_form_instance return None because I don't pass in PK in kwargs? Any help will be much appreciated. -
Django 'NoneType' object has no attribute 'has_header' when subclass LoginView
Straight to the point, I'm new on python, and I want to try a custom login on django. More specifically I want to process some form data before login. I went out to this: class mylogin(auth_views.LoginView): def form_valid(self, form): print("datas :D!", form.cleaned_data['password']) super().form_valid(form) All the other things should remain the ones of the LoginView. So, in my urls.py I have: path('login/', views.mylogin.as_view(template_name='public/login.html'), name='login'), And the result, when i try to log in is: AttributeError: 'NoneType' object has no attribute 'has_header' This has more to do with some kind of response object. Precisely: django\lib\site-packages\django\utils\cache.py in patch_response_headers, line 243 Django is on version 2.1.2. Thanks for all the fish! -
Why isnt Django not loading built-in static files?
I have a Django instance set up on an Apache server running through uWSGI hunky dory. Everything looks perfect on my local machine when I use python manage.py runserver. Unfortunately, the minute I uploaded the files to my pre-prepared production server, it refused to load all of Django's built-in static files, returning a 404 and I have no idea why... The url that is being queried is listed as www.mysite.com/static/admin/css/fonts.css and is similar for the admin backend(css/base.css,css/dashboard.cssandcss/responsive.css). At first I thought it might be something wrong with the packages so I force-reinstalled Django but no go. Still not loading... Here is my uWSGI config .ini: [uwsgi] chdir = /path/to/top/level/mysite module = mysite.wsgi:application env = DJANGO_SETTINGS_MODULE=mysite.settings master = true pidfile = /path/to/project.pid socket = 127.0.0.1:49152 ; Dont use UNIX sockets as it confuses the proxy and alters the request : URL's. Current Apache version cant handle it. ; socket=/var/run/swerth_django.sock processes = 5 harakiri = 20 post-buffering = 1 max-requests = 5000 vacuum = true home = /path/to/top/level/Virtualenv/directory daemonize = /path/to/uWSGI.log env = LANG=en_US.UTF-8 enable-threads = true And I have included Static root and url as follows (comments were for my own understanding): #The URL of which the static files in STATIC_ROOT … -
Django Graphene node interface with arguments returns all fields
The following graphene query of mine where I pass parameters to my query returns all the results, even when my front end gives correct parameters it gives all results. Even with data where no result should return it still returns all results. I have a graphene type: class TimeStampType(DjangoObjectType): rowid=graphene.Int() class Meta: model = TimeStamp interfaces = (Node, ) filter_fields = { 'year': ['exact'], 'week': ['exact'], 'weekDay': ['exact'], 'shift': ['exact'], 'time': ['exact'], 'shortDate': ['exact'], } def resolve_rowid(self, context, **kwargs): return self.id with query: node_timestamp = DjangoFilterConnectionField(TimeStampType) My query looks like the following: query nodeTimeStamp($year:Float, $week:Float, $weekDay:Float){ nodeTimestamp(year:$year, week:$week, weekDay:$weekDay) { edges{ node{ id rowid } } } } -
Django Carousel with pictures choosen by admin in front-end from a list
I would like to set in my django web application a Bootstrap or Javascript carousel a bit particular. Up to now and as I see, carousel pictures are defined inside the backend code by developer. I would like to make a carousel where pictures are defined by admin from a template with a choice list of publications. Each publication has a cover page. So admin user could check one or multiple publication and the carousel placed in an other template loads previous selected pictures. I have different questions from this idea : How I can save admin choice in order to use checked picture in the carousel ? (Maybe through database but how ?) How I can pass variables check from a class view to another one ? (I have to set global variables ?) Do you have any idea if something like that already exists ? Thank you so much by advance for any idea ! -
machine learning algorithms web application using django
We have just started doing a project in django, but we couldn't understand how to import the python files(algorithms). Can anyone of you explain how to implement a machine learning algorithm with some piece of code..(views,urls,..) -
Send form data in Django using Ajax
I have ajax call inside external js file as follows: $(document).ready(function () { // Contact form let contact_button = $("#contact-button"); contact_button.on('click', function (e) { e.preventDefault(); let contact_name = $("#contact-name"); let contact_email = $("#contact-email"); let contact_message = $("#contact-message"); let csrftoken = getCookie('csrftoken'); $.ajax({ type: "POST", url: '/main/contact-us/', data: { email: contact_email.val(), name: contact_name.val(), message: contact_message.val() }, success: function (result) { hideSpinner(); resetForm(); contact_form_success() }, beforeSend: function (xhr, settings) { showSpinner(); if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, error: function (data) { hideSpinner(); let errors = null; if (typeof data.responseJSON !== "undefined") { errors = data.responseJSON; } contact_form_error(errors) } }) }); }); And in my view is as follows: def contact_us(request): if request.method == 'POST': contact_us_form = ContactUsForm(request.POST) if contact_us_form.is_valid(): name = contact_us_form.cleaned_data['name'] email = contact_us_form.cleaned_data['email'] message = contact_us_form.cleaned_data['message'] try: subject = '[WEB] A customer sent you a message' body = render_to_string('contact_email.html', {'name': name, 'email': email, 'message': message}) from_email = 'web@bemiddelingscenter.com' to_emails = MAIN_MAIL msg = EmailMultiAlternatives(subject, body, from_email, to_emails) msg.content_subtype = "html" # Main content is now text/html msg.mixed_subtype = 'related' msg.send() return HttpResponse(status=200) except: return HttpResponse(status=404) else: data = { "email_error_exists": len(contact_us_form['email'].errors) > 0, "name_error_exists": len(contact_us_form['name'].errors) > 0, "message_error_exists": len(contact_us_form['message'].errors) > 0, } return JsonResponse(data, status=404) And in … -
Django : Display uploaded image with media
I would like to display in my template the uploaded picture for each object. I'm getting an issue because there is an error with media path when I click over picture url. I have in my model : class Publication(models.Model): ... cover = models.ImageField(upload_to='media/', verbose_name=_('cover page')) Then, I have in my settings part : MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR + '/myapp/' Now, in my template file, I display the picture like this : {% if item.cover %} <td> <a href="{{item.cover.url}}" target="_blank"> <img class="glyphicon glyphicon-home" src="{{item.cover.url}}" alt="{{item.cover}}"> </a> </td> {% else %} <td></td> {% endif %} The template page url is : http://localhost:8000/crud/publication/list/ And when I click on my picture link, I get : http://localhost:8000/crud/publication/list/media/media/couverture_qZQKLED.jpg It's false and I should get : http://localhost:8000/media/couverture_qZQKLED.jpg Then, I would like ti replace visible elements just by a glyphicon. Could you help me ? In my urls.py file, I have : if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to set up initial value in Django form for ForeignKey field?
I have problem with setting up initial value for ForeignKey field. I have a CreateView form and I am accessing it from book detail view which has url : path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), I want to have initial value of this book for example /book/4 in my form already when i enter CreateView views.py class BookInstanceCreate(PermissionRequiredMixin, CreateView): model = BookInstance fields = '__all__' permission_required = 'catalog.can_mark_returned' initial = {'book': BookInstance.book.id} def get_success_url(self): return reverse('book-detail', kwargs={'pk': self.object.book.pk}) I was trying to access a book with : initial = {'book': BookInstance.book.id} but i got error: initial = {'book': BookInstance.book.id} AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'id' Here are my models.py: class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in the file. summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') # ManyToManyField used because genre can contain many books. Books can cover many genres. # Genre class has … -
Django ORM search in text by keywords with Subquery
I have two models in django. Article model that have field title, and Keyword model with field title. I need to make query to DB and filter only those articles whose title contains any keyword from Keyword model. I try to search with Subquery, but it's doesn't work. If I try to filter id's with in it's work: from django.db.models import Subquery Article.objects.filter(id__in=Subquery(Keyword.objects.values('id'))) But if I try to filter with icontains it's dosn't work: Article.objects.filter(title__icontains=Subquery(Keyword.objects.values('title'))) Last query returns empty queryset How fix it? -
Implement forgot password functionality using Djoser
I am new to Django framework and now have a trouble with forgot password functionality. I have read the documentation about that functionality but have some not clear. I need someone who can show me the steps on both frontend and backend in more detail. reset() { var self = this; axios .post(this.$apiUrl + "password/reset/", { email: self.email }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } -
call scrapy function in django upon API-Post request
I want to make an api to crawl my webpage. from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt import scrapy from scrapy.crawler import CrawlerProcess @csrf_exempt class QuotesSpider(scrapy.Spider): name = "quotes" def start_requests(self): urls = [ 'http://quotes.toscrape.com/random', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): return JsonResponse({'request parameters': response.css('.text::text').extract_first()}) def some_view(request, username): process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'LOG_ENABLED': 'false' }) process.crawl(QuotesSpider) process.start() Api call is coming from some_view function. If i seperate the api part and scrapy part both works well as a seperate but i want to integrate so can i get the results in POSTMAN request. Upon requesting it is giving me the error of csrf. however without scrappy part it works well. P.S: i am very new to this stuff and still in the learning phase of django and its structure. -
Django postgres migrate models column discount.category_name_id does not exist
Hi i'm trying to combine Django backend and postgresql database together. Here is my database tables: My models.py in Django from django.db import models # Create your models here. class Categories(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField(null=True, unique=True) class Meta: db_table = 'categories' def __str__(self): return self.name class Website(models.Model): id = models.IntegerField(primary_key=True) site = models.TextField(null=True, unique=True) class Meta: db_table= 'website' def __str__(self): return self.site class Discount(models.Model): id = models.IntegerField(primary_key=True) product_name = models.TextField() product_price = models.TextField() product_old_price = models.TextField() product_link = models.TextField() category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name') product_site = models.ForeignKey(Website, on_delete=models.CASCADE, null=True, to_field='site') product_image = models.TextField() class Meta: db_table = 'discount' def __str__(self): return self.product_name I managed to link Django and postgresql together following tutorials but when i try to migrate the database for the first time it come with this error : column discount.category_name_id does not exist LINE 1: ..."."product_old_price", "discount"."product_link", "discount"... ^ HINT: Perhaps you meant to reference the column "discount.category_name". i though i linked my foreign key from discount.category_name to categories.name with to_field='name' in the ForeignKeyField but somehow it used the discount.category_name_id ? i don't know where the category_name_id is, it's not in my tables Any help would be appreciate! -
Django database to html
I’m having a little troubles . I’m trying to show an object from my database to my html webpage I have it set up as: Def index(request): quotes = Quote.objects.all()[:1] *** I imported the model, and also I’m using one because I only want that current one] render(request, homepage/index.html, {“quote”: quote}) . I then use the for loop in my index template but it will not show up, I use {%block content%} {% for data in quote%} <h2>{{data.body}}</h2> {%endfor%} {%endblock%} but I can use {{quote}} by itself and get the object in the database. To show Any help getting the actual body text? I get no errors. Nothing shows. in my models.py ;I have body with text field. I have class Quote(models.Model): body = models.TextField() def __str__(): return self.body I just want to display the quote I have in my data base. When I go to localhost:8000/admin. I can insert the quote. I go to phpmyadmin, I see the quote. I even see it when I call the object. I just can’t display it inside html . Help please! **p.s I typed this question on my cellular device ** -
How to mock/intercept external API calls during unit testing?
I need to write a unit test case for my Django server, where I have the structure like following code snippet. This is just a pseudo-code because I just want to get the idea about the approach. # views.py class UserView(ViewSet): def get_info_from_multiple_sources(self, request): # assume url for this action is /users/:id/info user_id = get_parameters(request) info = info_service.get_info(user_id) return Response(info) # user_info_service.py class UserInfoService: def get_info(user_id): user_fb_info = fb_service.get_user_info(user_id) user_twitter_info = twitter_service.get_user_info(user_id) merged_info = merge_info(user_fb_info, user_twitter_info) return merged_info # fb_service.py class FbService: def _manipulate_data(response): user_info = None # do some processing here, to convert data from fb format to # project format. Assign formatted response to user_info variable. return user_info def get_user_info(user_id): # lets say this imaginary urls gives user info somehow magically. response = requests.request('http://fb.com/users/{0}'.format(user_id)) return self._manipulate_data(response) # twitter_Service.py class TwitterService: def _manipulate_data(response): user_info = None # do some processing here, to convert data from twitter format to # project format. Assign formatted response to user_info variable. return user_info def get_user_info(user_id): response = requests.request('http://twitter.com/users/{0}'.format(user_id)) return self._manipulate_data(response) # test_user_info_endpoint.py class TestUserInfoViewEndpoint(APITestCase): def test_user_info(self): # how to write a unit test function where # I will be mocking only requests.request call. i.e outgoing call to external APIs I am using unittests … -
Django Models - SQL Equivalent multiple tables join in DJANGO
How to join 3 or more tables in django (ORM ) and fetch the results? Have created 3 models: 1.student 2.marks 3.details class Student: s_id = models.IntegerField(primary_key=True) s_name = models.CharField(max_length=100) class Marks: school_id = models.IntegerField(primary_key=True) s_id = models.ForeignKey(Student, on_delete=models.CASCADE) score = models.IntegerField() status = models.CharField(max_length=30) class Details: address_city = models.CharField(max_length=30) emailid = models.EmailField() school_id = models.ForeignKey(Marks,on_delete=models.CASCADE) accomplishments = models.TextField() I need to join these 3 tables and fetch student name,score,status,address_city,email_id,accomplishments. In SQL we can write like this: select s_name, score, status, address_city, email_id, accomplishments from student s inner join marks m on s.s_id = m.s_id inner join details d on d.school_id = m.school_id; Please let me know how to achieve same thing using DJANGO codes. -
How to connect remote SQL server with Django 2
I was trying to connect my Django 2 project with a remote SQL server my connection string is 'default': { 'ENGINE': 'sql_server.pyodbc', # 'ENGINE': 'django_pyodbc', 'NAME': 'hrm5', 'USER': 'sa', 'PASSWORD': '12345', 'HOST': 'Remote Ip', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 11 for SQL Server', 'isolation_level': 'READ UNCOMMITTED', }, } I install pyodbc & django-mssql But still getting this error django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Also, I'm using Linux Mint-19 OS and SQL server -v is 12 -
Django : Add dynamical formset with button
I'm looking for handle Django formsets. I would like to display the first form in my formset and be able to add multiple forms when I click over the adding button. Up to now, I display my formset with extra=4 but I would like to set extra=1 and add extra when I click on new form button. In my template I have : {% block main %} <h2>{{title}}</h2> <div class="row publication-create"> <form method="post" action="" enctype="multipart/form-data" novalidate class="col-md-8 col-md-offset-2"> {% csrf_token %} <fieldset> <legend class="title"><span class="name">{% trans 'Publication form' %}</span></legend> {{ form|crispy }} </fieldset> <fieldset> <legend class="title"><span class="name">{% trans 'Document form' %}</span></legend> <button class="btn btn-default" type="button" data-toggle="collapse" data-target="#collapseDocument" aria-expanded="false" aria-controls="collapseDocument"> {% trans 'Add document(s)' %} </button> <div class="collapse" id="collapseDocument"> <div class="card card-body"> {{ document_form|crispy }} </div> </div> </fieldset> <br> <input type="submit" class="btn btn-default" value="{% trans 'Save' %}" /> <a href="{{request.META.HTTP_REFERER}}" class="btn btn-default">{% trans 'Cancel' %}</a> </form> </div> {% endblock main %} In my forms.py file I have : DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1) And my view looks like this : class PublicationCreateView(EdqmCreateView): """ Create publication with document form through formset """ model = Publication template_name = 'publication_form.html' def get_context_data(self, **kwargs): context = super(PublicationCreateView, self).get_context_data(**kwargs) context['document_form'] = DocumentFormSet(self.request.POST or None, self.request.FILES … -
Django Arrayfield in form
I am trying to render postgres Arrayfield values using SelectMultiple widget like this In models.py: SLOT_CHOICES = (('A','Slot A'),('B','Slot B'),('C','Slot C'),('D','Slot D'),('E','Slot E'),('F','Slot F'),('G','Slot G'),('H','Slot H'),('P','Slot P'),('Q','Slot Q'),('R','Slot R'),('S','Slot S'),('T','Slot T'),) core_slots = ArrayField(models.CharField(max_length=1,choices=SLOT_CHOICES),blank=True,null=True) In forms.py: self.fields['core_slots'].widget = forms.SelectMultiple(attrs={ 'placeholder': 'Choose slots', 'class': 'multi-select-input', },choices=self.Meta.model.SLOT_CHOICES) If I select a single option and submit and then try to get the filled form using 'instance' then it works fine and shows the previously selected option as 'selected'. But if I select more than one option, then on submitting all selected values get correctly inserted into database, but if I try to get the filled form using 'instance' then it doesn't show any option as selected. This problem doesn't happen for ManyToManyField. In models.py: past_courses = models.ManyToManyField(Course,blank=True) In forms.py: self.fields['past_courses'].queryset = Course.objects.filter(~Q(dept=self.instance.dept)).order_by('name') self.fields['past_courses'].widget.attrs.update({ 'placeholder': 'Choose past courses', 'class': 'multi-select-input', }) This one works fine. Only ArrayField rendered using SelectMultiple widget has problem. I want to display submitted options in template, is there any way to fix this or is there any alternate way to display selected options in template. -
Cannot Write InMemoryUploadedFile to Local File in Thread - Python
My Program is in Django. I get the uploaded files from js request.FILES: my_docs = {} for doc_title in request.FILES: doc_name = request.FILES[doc_title].name doc = request.FILES[doc_title] my_docs[doc_name] = doc and pass them to a service object which has a 'save_docs' method: class MyService(): def __init__(my_docs): self.my_docs = my_docs ... def save_docs(self): for my_doc in self.my_docs: with open(os.path.join(self.localfile_path,my_doc),'wb+') as destination: for chunk in self.my_docs[my_doc].chunks(): destination.write(chunk) #destination.close() def process(self): ... self.save_docs() ... ... and create a thread then call it: my_service = MyService(my_docs) platform_thread = threading.Thread(target=my_service.process) platform_thread.start() However there is error: self._target(*self._args, **self._kwargs) File "/Users/xxxx/eclipse-workspace/My/my.py", line 97, in process self.save_docs() File "/Users/xxxx/eclipse-workspace/My/my.py", line 39, in save_docs for chunk in self.my_docs[my_doc].chunks(): File "/Users/xxxx/Library/Python/3.7/lib/python/site-packages/django/core/files/uploadedfile.py", line 91, in chunks self.file.seek(0) ValueError: I/O operation on closed file. The problem is when I run the program without creating a thread, it works. Why within a thread it does not? I have to use threading because I need to run several different such services at the same time. -
how to implement machine learning algorithms in django
I have already started and tried a machine learning project using python django framework. But i didn't understand where to save the python files which contains machine learning algorithms. Can anyone suggest me some solution?