Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
project's Interpreter version is 3.5 still get the SyntaxError: Non-ASCII character Error
When I execute the migrations: python manage.py makemigrations I get the bellow error: SyntaxError: Non-ASCII character '\xe4' in file /Users/abx/Desktop/website/website/settings.py on line 40, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details But my Django project's Interpreter version is 3.5.2 in my PyCharm. -
Django LoginView send success message
I have one LoginView Class. Here: class LoginFormView(LoginView): template_name = 'auth/login.html' success_url = '/profile' messages.success('<p class="success_login">You were successfully login</p>') And here: def log_out(request): logout(request) messages.success(request, '<p>You were successfully logout</p>') return redirect('/') Through my function i can send success message as messages.success but when.. Log in message success requires *request *message i can not request. What to do? Any ideas? Error is : messages.success('<p class="success_login">You were successfully logout</p>') TypeError: success() missing 1 required positional argument: 'message' Thank you in advance -
How to propagate parent attributes in Django models?
Is there a way to propagate child attributes in parent class without having to access it by its related name? Please consider the following example: class BaseA(models.Model): pass class BaseB(models.Model): a = models.ForeignKey('BaseA') class A(BaseA): base = models.OneToOneField('BaseA', related_name='related') field = models.IntegerField(default=0) def some_method(self): pass class B(BaseB): base = models.OneToOneField('BaseB') # code in view model_b = B() model_b.a.some_method() I cannot access the some_method method because model_b.a returns a BaseA() instance instead of A(), if I want to access this method I have to: model_b.a.related.some_method() # or model_b.a.related.field Is there a way to propagate the properties and methods from the base class so I won't have to access using the related name? -
Custom location for custom Django commands
In my Django project I have multiple apps and would like to add custom Command which is general (populate_db) to all apps. However, Django seems to be registering custom commands only from the INSTALLED_APPS locations (i.e. you must place management folder within a folder of an app). Is there a way to place management folder in project_folder. Here is the desired dir structure: . ├── __init__.py ├── app_1 | ├── admin.py | └── ... ├── app_2 | ├── admin.py | └── ... ├── project_folder | ├── settings.py | └── management | ├── __init__.py | └── commands | ├── __init__.py | └── populate_db.py └── manage.py -
How to save a repositionned image (new position after dragging) with django?
I have a cover profile image in my web application and I want to reposition the image like facebook style cover page reposition. I have found a usefull example (you can find it in this link using Jquery and PHP) Dragging the image is done correctly but the problem when I save the picture after repositioning it , it's not saved as I want. This is my code : HTML <form action="{% url 'save_profile_cover' %}" role="form" method="post" enctype="multipart/form-data"> <div class="cover overlay cover-image-full height-300-lg cover-resize-wrapper" style="margin-top:-15px;height: 300px;"> <img src="{{ request.user.get_cover_picture }}" alt="cover" id="image" style="position: relative"/> <div class="drag-div" align="center" id="button_block" style="display: none">Drag to reposition</div> <div class="overlay overlay-full"> <div class="v-top btn-group" style="margin-top:15px;" id="plus_button"> <button type="button" class="btn btn-cover dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-pencil"></i> </button> {% csrf_token %} <div hidden> {{ form.profile_cover }} </div> <ul class="dropdown-menu pull-left" id="cover_options"> <li><a href='#' onclick="repositionCover();">Reposition...</a></li> <li><a href="#" id="upfile" onclick="repositionCover();">Upload Photo...</a></li> </ul> </div> </div> <div class="v-center overlay" style="display: none" id="buttons_block"> <button class="btn btn-success pull-left" type="submit" id="save_button" style="margin-right: 10px ;margin-top: 10px"><i class="fa fa-save"></i> Save </button> <a href="{% url 'upcoming_events_list' %}" type="button" class="btn btn-default pull-left" id="cancel_button" style="margin-top: 10px" ><i class="fa fa-remove"></i> Cancel </a></div> </div> </form> <script src="{% static "profile/js/change_cover.js" %}"></script> <script> $("input[name='profilecover']").addClass("cover-position"); function repositionCover() { $('.cover-wrapper').hide(); $('.screen-width').val($('.overlay-full').width()); console.log($('input.cover-position').length) $('.cover-image-full img') .css('cursor', … -
how to use forloop.counter in in another django template?
I want to print all the Questions and their respective answers. I have passed the list of all the Questions and a list of all the answers of all the questions. I am doing something like this in my html {% for question in questions %} <div class="row"><h5>Q.{{forloop.counter}} </h5>&nbsp; {{question.0}}</div> {% for answer in answers.0.getanswers %} <blockquote> <div class="row"><h6>A.{{answer}} </h5> {{answer}}</div> <footer> </footer> </blockquote> {% endfor %} <form method="POST" class="form-group"> {% csrf_token %} answer: <input type="text" name="answer_text" class="form-control" placeholder="Write"> <br> <input type="hidden" name="rating1" value="2"> <input type="hidden" name="question_id" value="{{question.1}}"> <input type="submit" class="btn btn-primary" value="answer" class="form-control"> </form> <br> {% endfor %} and in my views.py ihave something like this class Question_answer(): question_id=-1 answers = [] def getanswers(self): return self.answers def detail(request,ID): #something cursor.execute("""Select * from Question where product_id='""" + str(ID) + "';") questions = cursor.fetchall() ids = [] for question in questions: ids.append(question[1]) answers = [] for i in ids: cursor.execute("Select * from Answer where question_id='" + str(i) + "';") temp = list(cursor.fetchall()) b = Question_answer() b.question_id = i b.answers = temp answers.append(b) return render(request, 'html',{'questions': questions, 'answers': answers}) But it seems like answers.forloop.counter is not giving me answers.0,answers.1... but when i replace answers.forloop.counter0.getanswers with answers.0.getanswers, it does print all the answers … -
User not recognised in django-rest-framework-social-oauth2.
When registering my application I enter my superuser name in user field but it throws error stating invalid. -
Show a paginated ListView and an UpdateView on the same template page
I am trying to create a Django page where one part of a model can be updated and another part is shown in a table. The model looks like this: class Cost(models.Model): name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=50, decimal_places=2) description = models.CharField(max_length=200) I previously had it working by just having an UpdateView for the form and the table included in the form template. Now though, as I want to include pagination on the table, I need to use two views on the same page. The page I have designed should look something like this in the end: I am not worried about the styling at the moment my main focus at the moment is getting the form and the table on the same page. In its current state the only thing that I don't have is the pagination for the table: Template: {% extends 'pages/dashboard.html' %} {% load i18n humanize crispy_forms_tags %} {% block content %} <div> <h1 class="text-center">Cost: {{ cost.name }}</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Edit cost data / feed: {{ cost.name }}</h3> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary pull-right ml-1" type="submit">{% trans "Update" %}</button> <a class="btn btn-secondary pull-right" href="{{ … -
Django 1.6 to 1.11 Admin.py migration
I am trying to port an old Django 1.6 admin.py code into Django 1.11 and for whatever reason, it is not working on 1.11. I am sending you the code below so some of you might give me some points on areas of the old code that will probably not work on Django 1.11. Thanks in advance for any hint. ---- admin.py ----- from django.contrib import admin from webpad.models import Layout, Element, LayoutElement, Session, Click, DataGroup, DataElement, ReportTemplate, ReportBlock, Stream, Participant, Observer, Additional from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django import forms class FilteredUserAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user obj.save() def queryset(self, request): qs = super(FilteredUserAdmin, self).queryset(request) return qs.filter(user=request.user) class ElementAdmin(FilteredUserAdmin): fieldsets = [ (None, {'fields': ['name','group','connotation','color','add_to_video']}), ] class AdditionalInline(admin.StackedInline): model = Additional can_delete = False class UserAdmin(UserAdmin): inlines = (AdditionalInline, ) class ParticipantInline(admin.TabularInline): model = Participant extra = 0 class StreamAdmin(FilteredUserAdmin): fieldsets = [ (None, {'fields': ['stream_name','active']}), ] inlines = [ParticipantInline] class LayoutElementInlineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(LayoutElementInlineForm, self).__init__(*args, **kwargs) self.fields['element'].queryset = Element.objects.filter(user=self.request.user) class LayoutElementInline(admin.StackedInline): model = LayoutElement extra = 0 form = LayoutElementInlineForm def queryset(self, request): self.form.request = request class LayoutAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LayoutAdminForm, self).__init__(*args, … -
Use PyCharm create a website project, but do not find the db.sqlite3 file
I use PyCharm create a website project, but do not find the db.sqlite3 file. The database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Django : Signals with a extend User model
I am in Django 1.11 and my question is quite simple : I read these posts : Extending the User model with custom fields in Django https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html and I am not sure a StudentCollaborator user will be created/updated when a user exists (there is already users in the database so I cannot simply redo stuff ). My current code looks like this : # Create your models here. class StudentCollaborator(models.Model): # https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model user = models.OneToOneField(User, on_delete=models.CASCADE) """" code postal : pour l'instant que integer""" code_postal = models.IntegerField(null=True, blank=False) """" flag pour dire si l'user a activé le système pour lui """ collaborative_tool = models.BooleanField(default=False) """ Les settings par défaut pour ce user """ settings = models.ForeignKey(CollaborativeSettings) def change_settings(self, new_settings): self.settings = new_settings self.save() """ https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone """ """ Signaux: faire en sorte qu'un objet StudentCollaborator existe si on a un modele """ @receiver(post_save, sender=User) def create_student_collaborator_profile(sender, instance, created, **kwargs): if created: """ On crée effectivement notre profile """ StudentCollaborator.objects.create( user=instance, collaborative_tool=False, settings=CollaborativeSettings.objects.create() # Initialisé avec les settings par défaut ) Can you help me ? Thanks -
settings. DATABASES is improperly configured. Please supply the NAME value
by django /// made cookiecutter python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_co mmand_line utility.execute() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\commands\makemigrations.py", line 109, in handle loader.check_consistent_history(connection) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\migrations\loader.py", line 276, in check_consistent_hi story applied = recorder.applied_migrations() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations self.ensure_schema() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor self.ensure_connection() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 170, in connect conn_params = self.get_connection_params() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\postgresql\base.py", line 158, in get_connecti on_params "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. settings by base.py DATABASES = { 'default': env.db('DATABASE_URL', default='postgres://nomadgram'), } DATABASES['default']['ATOMIC_REQUESTS'] = True I'm not sure why it matters. Please help me. Or will this not happen at all? Am I just too confused/tired at this point? enter image description here <- my database in pgadmin -
Django and REST API serializer of various derived classes
I am solving an equivalent problem to the following. I need to serialize django models which have following criteria: Base (abstract) class from django model containing a "type" field where I can store type of goods (i.e. fruit, clothes...) Derived classes for different type of goods (fruit has weight, clothes have color) I would like to serialize (into JSON) the list of any goods for REST API framework. I do not know how to make it the best to use framework capabilities of serialized object validation etc. -
OpenCV video livestream over HTTP
I'm recently started working on image processing using OpenCV library with python wrapper. Now I want to broadcast original frame and processed frame on server. I need help to decide compatible technologies to implement my goal. After several hours of searching I guess to use: NGINX as server engine UWSGI + DJANGO as backend framework HLS as protocol to send video over HTTP Video.js on client side to play live stream Please, can you give me advise or suggest me anything else? -
Access many2many field values before saving to database in clean method django
I have the below model and I am trying to raise a validation error in clean method based on the values of many2many field RULE_SET_CHOICES = ( ('G', 'GLOBAL'), ('C', 'LOCAL') ) class Books(models.Model): type = models.CharField(max_length=2, choices=RULE_SET_CHOICES, null=False, default='C') author = models.ManyToManyField(Author, related_name="books", blank=True, null=True) def clean(self): if self.type = 'G': // Check if type is Global and if we tried to associate / add authors then raise a validation error if self.author : raise ValidationError("When type is global, you should not associate authors") But when I tried to access self.author I am facing below error *** ValueError: "<Books: Hello World- G>" needs to have a value for field "author " before this many-to-many relationship can be used So is there any way to access many-2-many relationship field values before saving into database? as I need to raise a validation error based on its values as above -
Django: File Uploading vs File Creating (upload not working)
I have two forms: one where you create a new object (then it creates a new empty file for it), and one where you create an object with an existing file (it uploads the file). The creation form works just fine, it takes the name of the new created object and creates a file with the same name and uploads it in the static folder. However, the second form, it tells you that it got the file object and everything, but the file is not found anywhere. I tried to change directories and modify code and everything and it doesn't seem to work at all and I do not know where is the issue, here are my codes: views.py: def create(request): print request.POST filename = request.POST['name'] f = File(open(filename, "w+")) structure = Structure(name=request.POST['name'], file=f) structure.save() return redirect('/structures') def upload(request): print request.POST structure = Structure(name=request.POST['name'], file=request.POST['file']) structure.save() return redirect('/structures') models.py: class Structure(models.Model): name = models.CharField(max_length=120) file = models.FileField(upload_to='structures') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name html template: [...] <!--CREATE--> <div class="col-md-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Créer une nouvelle structure</h3> </div> <div class="panel-body"> <form class="form-horizontal" action="/create", method="post"> {% csrf_token %} <fieldset> <div class="form-group"> … -
Unable to convert dictionary object to JSON object
I want to convert my dictionary object as a JSON as i need to send it in ReactJS file. My code is below: def get(self, request, pk, format = None): queryset = SocialAccount.objects.filter(provider='twitter').get(id=pk) user_id= queryset.uid name = queryset.extra_data['name'] username = queryset.extra_data['screen_name'] data = {'user_id':user_id,'name':name,'username':username} data = json.dumps(data) print(type(json.loads(data))) return Response(json.loads(data)) In this view, I got " class 'dict' " in "print(type(json.loads(data)))" line instead of JSON object. If i am going wrong, please guide me. What i need to do? Thanks. -
how to upload multiple images with resizing with jquery to django backend server
I am using Jquery file upload and compressing code for images with this i can select multiple images but it only compressing and uploading the last image selected so how can i upload multiple images with compression? What modifications are needed plzz suggest. Html code: <input id="fileupload" type="file" name="file" multiple> Jquery code: function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(function () { 'use strict'; var csrftoken = $.cookie('csrftoken'); var url = '/dashboard/{{name}}/{{name_product_type.type_product|urlencode}}/{{abc}}/'; $('#postbtn').on('click', function () { var $this = $(this), data = $this.data(); $this .off('click') .text('Abort') .on('click', function () { $this.remove(); data.abort(); }); data.submit().always(function () { $this.remove(); }); }); $('#fileupload').fileupload({ url: url, crossDomain: false, beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, dataType: 'json', uploadMultiple: true, // allow multiple upload autoProcessQueue: false, // prevent dropzone from uploading automatically maxFiles: 5, autoUpload: false, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, maxFileSize: 5000000, // 5 MB // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true }).on('fileuploadadd', function (e, data) { data.context = $('<div/>').appendTo('#files'); $.each(data.files, function (index, file) { var node = $('<p/>') .append($('<span/>').text(file.name)); if (!index) { node .append('<br>') // .append($('#postbtn').clone(true).data(data)); … -
Manually validate django-simple-captcha
I'm using django-simple-captcha in a project. I want show a captcha to the user in a mobile application and get the response and manually validate the response. The documentation only mentions validation by creating a form. How can I manually validate the response? -
Django "prepopulated_fields" did not work
I am trying to prepopulate the SlugField but it's not happening. I use python 3.6.1 and Django 1.11. Here is my code. models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Черновик'), ('published', 'Опубликовано'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', default=1,) body = RichTextUploadingField(blank=True, default='', config_name='awesome_ckeditor') publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() def __str__(self): return self.title class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) And this is admin.py class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {"slug": ("title",)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ['-publish', 'status'] admin.site.register(Post, PostAdmin) Site is hosted on heroku. Maybe I can auto generate slug field in another way? -
Tree Structure (Foreign Keys to itself) and templates
I have a tree structure for Categories. Categories with a Foreign key that is referring to itself. class Category(MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField() Because I don't know the depth of the categories tree(can't use for) I need to use a recursive function: def cat_for_parents(self, cat_obj): ... if cat_obj.parent_id: p = cat_obj.parent ... self.cat_for_parents(p) But how I implement the function in the template to get something like this(to theoretically infinite recursive loop): <ul> <li>CategoryA <ul> <li>SubCategA1 <ul> <li> Subcateg Subcateg B1 <ul> <li> Subcateg SubCateg C1> <li> Subcateg SubCateg C2> <ul> <li> Subcateg Subcateg B2> ............. -
How to access folder name in djangocms-filer plugin in which user is uploading files?
I want to store media file in folder whose name should be exactly same as folder name created in admin panel 'http://localhost:8000/en/admin/filer/folder/' How can we get folder name from djangocms-filer plugin and pass it to UPLOAD_TO so that file get uploaded at specific location '/media/project_name/Folder_name/file' FILER_STORAGES = { 'public': { 'main': { 'ENGINE': 'filer.storage.PublicFileSystemStorage', 'OPTIONS': { 'location': os.path.join(DATA_DIR, 'media'), 'base_url': '/media/filer/', }, 'UPLOAD_TO': 'filer.utils.generate_filename.randomized', 'UPLOAD_TO_PREFIX': 'project_name', }, 'thumbnails': { 'ENGINE': 'filer.storage.PublicFileSystemStorage', 'OPTIONS': { 'location': '/path/to/media/filer_thumbnails', 'base_url': '/media/filer_thumbnails1/', }, }, }, 'private': { 'main': { 'ENGINE': 'filer.storage.PrivateFileSystemStorage', 'OPTIONS': { 'location': '/path/to/smedia/filer', 'base_url': '/smedia/filer/', }, 'UPLOAD_TO': 'filer.utils.generate_filename.randomized', 'UPLOAD_TO_PREFIX': 'filer_public', }, 'thumbnails': { 'ENGINE': 'filer.storage.PrivateFileSystemStorage', 'OPTIONS': { 'location': '/path/to/smedia/filer_thumbnails', 'base_url': '/smedia/filer_thumbnails/', }, }, }, } -
MultiValueDictKeyError at /app/index "'access_key'"
I got an error,MultiValueDictKeyError at /app/index "'access_key'" .I wrote in views.py from django.shortcuts import render from .forms import UserIDForm from .models import User import json from django.http.response import JsonResponse from django.http import HttpResponseNotFound def index(request): inp_id = request.POST['access_key'] arr = [[100,2],[300,3],[500,4],[800,5],[200,6]] inp_id = int(inp_id) find = False for i in range(int(len(s)/2)): if inp_id == arr[i][0]: find = True if find: id_json = {"id": 100} else: return HttpResponseNotFound() return JsonResponse(id_json, safe=False) in index.html <html lang="en"> <head> <meta charset="UTF-8"> <title>Input</title> </head> <body> <p>Hello</p> </body> </html> in urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^index$', views.index, name='index'), url(r'^response$', views.response, name='response'), ] Now I use POSTMAN. My ideal system is when I post Key is access_key& Value is 100 to http://localhost:8000/app/index in POSTMAN,{"id": 100} is returned.What is matter in my code?Is it unicode error?How should I fix this? -
celery write specific log file for specific task
How to write specific log file for specific task in django celery,i have write overall celery log in single log file how to do that one from redington.celery import app from celery import shared_task @app.task(bind=True, name='load_ibm_machine_images') def load_ibm_machine_images(self): """ Task to perform To load soft-layer machine images """ from cloudapp.management.commands.update_softlayer_machine_types import Command soft_layer_command_object = Command() soft_layer_command_object.handle() return True Thanks in advance!!! -
Subprococess calling a python script in Django running a server through Apache in Linux - Raspbian.
I am working on a home automation project, and I want to run certain python codes when going to certain URLs of my Django Webpage. The subprocess.call() line from my Django Views.py works perfectly on my Django development server: from django.http import HttpResponse import subprocess def home(): subprocess.call(['python','path_to_python_file/python_file.py']) html = "<html><h1>Hello World</h1></html>" return HttpResponse(html) But the python script (or whatsoever command line) is not called on my Raspberry with Apache. According to many previous questions I've read, this could either be a SELinux issue or an premission issue. But I have given persmission to all users, groups, andd others to my python file: sudo chmod a=rwx python_file.py And still the python file is not executed. Using subprocess.Popeninstead of subprocess.call does not work, and neither does setting shell = True. Anyone has any idea of what I am missing here? Otherwise I'll try to switch over to CGI and drop subprocessing for running scripts :-)