Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webpack in react: Bundid for production
I am learning webpack and i am using it for react, my backend is django In my webpack, development server is working fine, only problem with building bundle for development. this is my webpack.common.js file: const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './client/index.js' }, plugins: [ // new CleanWebpackPlugin(['dist/*']) for < v2 versions of CleanWebpackPlugin new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: "./client/index.html", }) ], output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; and this is my webpack.prod.js file: const merge = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'production', }); and this my webpack.dev.js fiel const merge = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'development', devtool: 'inline-source-map', devServer: { contentBase: './dist' } }); And this is my package.js file { "name": "development", "version": "1.0.0", "description": "", "main": "client/index.js", "scripts": { "start": "webpack-dev-server --open --config webpack.dev.js", "build": "webpack --config webpack.prod.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.5.5", "@babel/plugin-proposal-class-properties": "^7.5.5", "@babel/preset-env": "^7.5.5", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.6", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1", "clean-webpack-plugin": "^0.1.17", "css-loader": … -
How to make the DRF ( Django-REST-Framework) Token persist so that it does not get lost after each page refresh?
NOTE- I am not using Python, Django, Templates for the front end. Just Pure HTML+jQuery+AJAX I have successfully implemented getting a User Based Token from the API Backend, Set it in Header File for the subsequen requests and work on the data provided by the API. But the problem is that whenever I refresh the page, the Authentication token is not there in the Header and I have to provide credentials again to access the API. Every time I refresh the page, the token is removed. How can I stop this? This is my code for setting the Header using jQuery+AJAX. $('#login').click(function () { //Send a POST Request to the URL for Token specified for User $.ajax({ type: 'POST', data: { username: $('#username').val(), password: $('#password').val() }, url: 'http://127.0.0.1:8000/rest-api/api-token-auth/', success: function (res) { console.log(res.token) //Initialize the Ajax for the first time $.ajaxSetup({ //Set the headers so that these will be in every HTTP Request headers: { "Authorization": 'Token ' + res.token } }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Error: " + errorThrown); } }); }); -
Why truncatechars won't works properly?
{{ noticia.imagem_chamada }} returns "abc.jpg" {{ noticia.image_chamada|trucantechars:4 }} returns nothing! Why? -
Why doesn't unittest.mock.ANY work correctly with Django objects?
I have written a test in Django, and I'm using unittest.mock.ANY to ignore certain values in a dictionary. Here is the test: from django.test import TestCase from django.contrib.auth import get_user_model import unittest.mock as mock class Example(TestCase): def test_example(self): user = get_user_model().objects.create_user(username='example') result = {'user': user, 'number': 42} self.assertEqual( result, {'user': mock.ANY, 'number': 42} ) If I run this test, I expect it to pass. Instead, I get this failure: ====================================================================== FAIL: test_example (example.tests.Example) ---------------------------------------------------------------------- Traceback (most recent call last): File "example/tests.py", line 18, in test_example 'number': 42, AssertionError: {'user': <User: example>, 'number': 42} != {'user': <ANY>, 'number': 42} - {'number': 42, 'user': <User: example>} ? ^^^^^^^^^^^^^ + {'number': 42, 'user': <ANY>} ? ^^^ Why doesn't ANY work in this case? It seems to work with strings and numbers. -
How to add custom JS to the Froala Django framework
I am using the Django implementation of Froala (https://github.com/froala/django-froala-editor/tree/master/froala_editor). This means Froala is implemented via the Django framework using views.py, models.py and forms.py rather than initialisation as an inline Javascript. In this implementation I am able to pass options to Froala via forms.py. E.g: class PageForm(forms.ModelForm): content = forms.CharField(widget=FroalaEditor(options={ 'dragInline': False, 'toolbarButtons': [['bold', 'italic', 'subscript', 'superscript'], ['indent', 'outdent', 'formatOL', 'formatUL']], })) However, if I want to implement custom events to the editor, such as this https://www.froala.com/wysiwyg-editor/examples/drop-content example of drop content, how can I do this via Django?. Usually I would add the following code, but the editor is already initialised via Django templates so it's not clear how I would proceed. <script> var dragCallback = function (e) { e.dataTransfer.setData('Text', this.id); }; // For Firefox to work. document.querySelector('#drag-smile').addEventListener('dragstart', dragCallback); document.querySelector('#drag-text').addEventListener('dragstart', dragCallback); new FroalaEditor('div#froala-editor', { events: { initialized: function () { var editor = this; editor.events.on('drop', function (dropEvent) { // Focus at the current posisiton. editor.markers.insertAtPoint(dropEvent.originalEvent); var $marker = editor.$el.find('.fr-marker'); $marker.replaceWith(FroalaEditor.MARKERS); editor.selection.restore(); // Save into undo stack the current position. if (!editor.undo.canDo()) editor.undo.saveStep(); // Insert HTML. if (dropEvent.originalEvent.dataTransfer.getData('Text') == 'drag-smile') { editor.html.insert('<span class="fr-emoticon fr-emoticon-img" style="background: url(https://cdnjs.cloudflare.com/ajax/libs/emojione/2.0.1/assets/svg/1f600.svg)">&nbsp;</span>'); } else { editor.html.insert('Hello!'); } // Save into undo stack the changes. editor.undo.saveStep(); // Stop event … -
Django database: no such table
Before we start, I read almost every post on Stackoverflow with problem like in the title, but no solution has helped me ... I have models like this: CATEGORY_CHOICES = ( ('Django', 'Django'), ('Python', 'Python'), ('C++', 'C++'), ('Graphics', 'Graphics'), ('Text Editor', 'TextEditor'), ('Spreadsheet', 'Spreadsheet'), ('DataBase', 'DataBase'), ('Web Design', 'WebDesign'), ) class PostImage(models.Model): name = models.CharField(max_length=100, choices=CATEGORY_CHOICES) image = models.ImageField(default='default_post.jpg', upload_to='post_pics') def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50, unique=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) numbers_of_entries = models.IntegerField(default=0) image = models.ForeignKey(PostImage, on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('comment-detail', kwargs={'pk': self.pk}) def __str__(self): return self.text The problem is that when I try to create a database I get an error: django.db.utils.OperationalError: no such table: blog_postimage Can someone explain to me what could be going on and how to solve this problem? Before you ask, I used the following commands: python manage.py makemigrations python manage.py migrate I work on Django 2.2.4 -
How to hide form and show successful message on button click
I have a Django template. The template contains a table with multiple rows with each row having two columns. One column consists of videos and the other consists of a feedback form with a submit button. I wish to write a feedback and then submit it. If the feedback gets saved into the database I would like to hide the form and replace it with a successful notification. My html looks as follows: <form method="POST"> {% csrf_token %} <div class="form-group purple-border shadow-textarea" id="divFeedback"> <input type="hidden" id="spotId{{ forloop.counter }}" name="spotId{{ forloop.counter }}", value="{{ spot.id }}"> <label for="feedbackTextarea{{ forloop.counter }}">Rückmeldung</label> <textarea class="form-control z-depth-1" name="feedback{{ forloop.counter }}" rows="5" placeholder="Ihre Rückmeldung!"> </textarea> </div> <input class="btn btn-primary btn-success" type="submit" value="Abschicken" name="submit{{ forloop.counter }}"> </form> The corresponding view would be: if request.method == 'POST': if request.POST.get('submit1'): # hide the divFeedback and show 'client/success.html' return render(request, 'client/success.html') else: return render(request, 'client/spotpreview_2.html', { 'tvspots': tvspots, 'token': token }) I have already tried many answers but due to my low level understanding of HTML, I cannot do anything. Would anyone be able to help me out with this issue? -
Why my Django-Rest-Framework post method do not have the fields?
In the Django-Rest-Framework API, I can not use post for testing, I don't know why there is no the post fields. My View: class WHMCSPhysicalServerIPMIManagementAPIView(APIView): serializer_class = WHMCSPhysicalServerIPMIManageSerializer permission_classes = [IsAdminUser] def post(self, request): """ :param request: action: physical_server_name: :return: """ try: physical_server_name = request.query_params.get('physical_server_name') action = request.query_params.get('action') if not physical_server_name or not action: return Response(data="invalid request data", status=HTTP_400_BAD_REQUEST) physical_server = PhysicalServer.objects.get(name=physical_server_name) msg = ipmi_management_handler({'action': action, 'physical_server_id': physical_server.id}) return Response(data=msg, status=HTTP_200_OK) except Exception as e: return_data = "fail" if e.args == () else e.args[0] return Response(data=return_data, status=HTTP_200_OK) My serializers: class WHMCSPhysicalServerIPMIManageSerializer(Serializer): physical_server_name = serializers.IntegerField(write_only=True) action = serializers.CharField(write_only=True) whmcs_user_id = serializers.IntegerField(write_only=True) My url: urlpatterns = [ url(r'^whmcs/physicalserver/ipmi_management/$', WHMCSPhysicalServerIPMIManagementAPIView.as_view(), name='whmcs-physicalserver-ipmi_management'), ] -
Adding JS function with django? Javascript functions only works from console?
I have an app made with Django as backend so i have a base.html where I inherit from ( things like the sidebars and navbars and stuff ) Whenever I try to add a JS function in a certain page it doesn't work so I add it to the index but now I have a function that only works when I run it in the console of the browser. $("#q12").click(function() { $("#q11").show(); }); and I tried $(document).ready(function() { $('#q12').click(function() { $('#q11').show(); }); }); I know that jquery is loaded as this works from the console but what's I'm missing here? -
Large File in /tmp folder with "request_body-" in title
This might be a very basic question but I have around 30GB disk space in my server running django code and every now and then my server have full disk space because of a file in /tmp directory having "request_body-" in title like this "20190823-015137-asdsadsadsadasdsa-request_body-Tpoyyyyyyy110". I checked and apache sub process is creating this file but I could not figure out how this file is getting created and what could be the reason. strace shows that apache sub process is stuck in read 5 (Pipe FIFO) -
How to work with the legacy database and integrate the django models with them?
I'am working on one of the legacy database, ran inspectdb command and got the respective models from the command. The models which are generated from django does not show-up any foreign key for the models. The db which I'am using is sqlite3. I have copied the models which was generated from inspectdb command and I tried modifying the models as per the tables in sqlite3 db. I have tried giving the 'REFERENCES' as foreign key but in migrations does not show any foreign key. I'am confused whether this REFERENCES is foreign key are not. Please help me out in identifying foreign key for the given tables and alter the models accordingly. The 4 tables which I have in sqlite3 db are test, suite_status, test_status and suites. 1.For suite_status table:- id INTEGER PRIMARY KEY, status TEXT NOT NULL, failed INTEGER NOT NULL, elapsed INTEGER NOT NULL, test_run_id INTEGER NOT NULL REFERENCES test_runs, suite_id INTEGER NOT NULL REFERENCES suites, passed INTEGER NOT NULL, CONSTRAINT unique_suite_status UNIQUE (test_run_id, suite_id For test table:- id INTEGER PRIMARY KEY, doc TEXT, xml_id TEXT NOT NULL, suite_id INTEGER NOT NULL REFERENCES suites, name TEXT NOT NULL, timeout TEXT, CONSTRAINT unique_tests UNIQUE (suite_id, name) For suites table:- id … -
Run a function the same time that django runs
I want to make a function in django that deletes accounts that dosen't have enough points.This function is call every 24 hours.Where I can write this function ? -
Django model method being called twice on production, but not on staging or local dev server
My stack: Ubuntu 18 Postgres 10 Gunicorn NGINX Django 2.1 I have a Django model method that sends an email to users if a form is submitted in a view. After deploying an update lastnight that didn't touch any of the code in the app described below, as of this morning when that form is submitted the method that sends the email is being called twice, leading to two duplicate emails being sent each time. I've started logging the tracebacks of the calls that lead to this method being called using stack_info=True and they are identical for both calls of this method (i.e. it's the method is not being called by rogue code in different places each time) a couple of hundred milliseconds apart. The logged calls are both like: File "/home/[path]/views.py", line 292, in my_view foo': _foo}) File "/home/[path]/views.py", line 231, in _process_view_helper_func thing.send_email() File "/home/[path]/models.py", line 351, in send_email stack_info=True, The confusing thing is that when I submit the form locally (Django dev server) and on my staging server (same stack and configuration as production server) the method is only called once and no duplicate emails are sent. What could be causing my Production server to be calling … -
Defined optional form field not being so optional
I looked over this topic Django: Optional model form field but didn't help solve my problem. I need the field timeout to be optional, meaning when user leaves it blank it will default to 10 This is what I've got so far: models: class MyModel(models.Model): timeout = models.IntegerField(default=10) ... ... modelform: class MyModelForm(forms.ModelForm): timeout = forms.IntegerField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Timeout (optional)'}), required=False, label='') ... ... class Meta: ... ... view: class CreateTestSuite(FormView): template_name = 'create_test_suite.html' form_class = MyModelForm success_url = '/list' context_object_name = 'user_id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_id'] = self.request.user.id return context def form_valid(self, form): form.save() # this is where form submission throws an error return HttpResponseRedirect(self.success_url) The traceback says NOT NULL constraint failed: timeout So where else do I need to specify that the form field is optional and defaults to 10 in the database if left blank ? -
Error 403: Forbidden You don't have permission to access / on this server with apache, mod-wsgi and django
I am new in django and apache. I want to publish my django website by apache and mod-wsgi. when I start httpd.exe, I recieve 403 forbidden error in my browser. my apache config is here LoadFile "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django/python36.dll" LoadModule wsgi_module "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIPythonHome "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django" Alias /static/ /D:/user/JarfaSys/static/ <Directory D:/user/JarfaSys/static/> AllowOverride none Require all granted </Directory> WSGIScriptAlias / /D:/user/JarfaSys/JarfaSys/wsgi.py WSGIPythonPath /D:/user/JarfaSys/ WSGIPassAuthorization On <VirtualHost 127.0.0.1:443> DocumentRoot D:/user/JarfaSys Alias /favicon.ico D:/user/JarfaSys/JarfaSys/favicon.ico Alias / /D:/user/JarfaSys/JarfaSys/wsgi.py ServerName 127.0.0.1 SSLEngine on SSLCertificateKeyFile C:/Users/zharf/TibiFiles/host.key SSLCertificateFile C:/Users/zharf/TibiFiles/host.cert SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown <Directory D:/user/JarfaSys/JarfaSys/> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> WSGIScriptAlias / /D:/user/JarfaSys/JarfaSys/wsgi.py WSGIPythonPath /D:/user/JarfaSys/ WSGIPassAuthorization On <Directory D:/user/JarfaSys/JarfaSys/> <Files wsgi.py> Require all granted </Files> </Directory> wsgi.py is : import os import sys path = "D:/Ghanbari/JarfaSys/JarfaSys" if path not in sys.path: sys.path.append(path) os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "JarfaSys.settings") #print os.getenv("DJANGO_SETTINGS_MODULE") #print os.getenv("PYTHON_EGG_CACHE") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() error log file is here [Fri Aug 23 16:29:26.827875 2019] [core:error] [pid 10784:tid 1092] (20024)The given path is misformatted or contained invalid characters: [client ::1:50025] AH00036: access to / failed (filesystem path 'C:/D:') [Fri Aug 23 16:29:26.848875 2019] [core:error] [pid 10784:tid 1092] (20024)The given path is misformatted or contained invalid characters: [client ::1:50025] AH00036: access to /favicon.ico failed (filesystem … -
How to add Dynamic URL part that contains a slash
I'm using a dynamic part in the URL in my Django project, as <str:item_code>, some times the str contains a slash / which causes an error not found. here is how my URL pattern looks like : path('find/the/item/<str:item_description>/', views.find_the_item, name="find_the_item"), is there anyway to force the url to ignore all slashes inside this ` part ? -
Django tinyMC failed to load in admin panel
I have problem with django-tinymce. This module doesnt load properly in admin panel and probably in normal form too. I used python manage.py collectstatic to collect static files. I'm running application with debug = False. I have 2 errors: Failed to load resource: the server responded with a status of 404 (Not Found) Uncaught ReferenceError: tinyMCE is not defined You can see errors in screenshoot. Settings: INSTALLED_APPS = [ 'tinymce', ... ] ... STATIC_URL = '/static/' MEDIA_URL = '/media/' ENV_PATH = os.path.abspath(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(ENV_PATH, '../public/static/') MEDIA_ROOT = os.path.join(ENV_PATH, '../public/media/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "tiny_mce") TINYMCE_JS_URL = os.path.join(TINYMCE_JS_ROOT, "tiny_mce.js") TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats … -
Images uploaded with ImageField doesn't show
I have such problem: From django admin I'm trying to upload a cover image for my article, but image doesn't show on template, and its name is written in red in PyCharm. Here are my codes: settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' models.py: class Article(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=200) content = HTMLField() # image = models.CharField(max_length=2000) image = models.ImageField(upload_to='static/img') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) post_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, null=True, editable=False) def __str__(self): return self.title article.html: <div class="blog-item wide-blog-item"> <a href="/"><img src="/{{ article.image }}" class="image"/></a> <h3 class="font-reg"><a href="">{{ article.title }}</a></h3> <div class="blog-item-meta"> <span>{{ article.post_date }}</span> </div> <div class="blog-item-meta"> <span style="text-transform: capitalize;">{{ article.category }} . </span> </div> </div> -
Django Admin Dependant Combos Population
I want to populate dependent combos based on selection of parent combos. my code is as follow: class Species(models.Model): name = models.CharField(max_length=120, blank=False, null=False) description = models.TextField(max_length=300, blank=False, null=False) class SpeciesDetail(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) picture = models.ImageField(upload_to='pics') gender = models.CharField(max_length=1) health = models.CharField(max_length=120) class Pair(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) male = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='male_set') female = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='female_set') from django.contrib import admin from .models import Species, SpeciesDetail, Pair, class PairAdmin(admin.ModelAdmin): list_display = ('species', 'male', 'female',) search_fields = ('male', 'female', ) filter_horizontal = () list_filter = () ordering = ['species'] fieldsets = () -
How to provide different actions within just one form?
Here I have 3 different views for deleting,making active/inactive and featured/unfeatured for the selected articles and the views are working fine but the problem I encountered is how can I process these 3 different views within just one form and I want to keep this form within my table.Is there any solutions for this? <form action ="{% url '????' %}" method="post"> {% csrf_token %} <table> <thead> <tr> <th>SN</th> <th>Title</th> <th>Body</th> <th>Active</th> <th>Featured</th> </thead> <tbody> {% for article in articles %} <tr> <td> <input name ="articles" type="checkbox" id="article-{{article.pk}}" value="{{article.pk}}" > <label for="article-{{article.pk}}">{{ forloop.counter }}</label> </td> <td>{{article.title}}</td> .......... {% endfor %} </tbody> <button type="submit"> Delete Selected Articles </button> <button type="submit"> Enable/Disable featured for selected </button> <button type="submit"> Enable/Disable active for selected </button> </form> views.py def delete_selected_articles(request): articles = Article.objects.filter(id__in=request.POST.getlist('articles')) articles.delete() messages.success(request, '{} articles deleted.'.format(articles.count)) return redirect('view') def feature_selected_articles(request): articles = Article.objects.filter(id__in=request.POST.getlist('articles')) for article in articles: if not article.featured: article.featured = True article.save() return redirect('.view') else: article.featured = False article.save() return redirect('view') def active_deactive_selected_articles(request): articles = Article.objects.filter(id__in=request.POST.getlist('articles')) for article in articles: if not article.active: article.active = True article.save() return redirect('view') else: article.active = False article.save() return redirect('view') -
How to Access and use Token Authentication and show API result at the front end in Django-REST-Framework with Ajax/jQuery/Javascript
I had been using Django and it's powerful templates for quite some time but suddenly I had to Switch to the Front End languages and technology (completely different and new) that includes JavaScript, jQuery and AJAX. I want to access my API data at the front end using HTML,CSS,Javascript,Ajax,jQuery (whichever combination is suitable) I am able to get my data and manipulate it easily without any difficulties using jquery and Ajax by using simple $.ajax() method but the problem is that I do not have any clue about how to get the data that requires permissions? { "detail": "Authentication credentials were not provided." } What is the procedure to access this data? I am using Token Authentication provided to each user. How can I access the Token if I am not using Python and Django views at the front End? DO I have to login with every request? What is the actual Procedure? Can Someone Guide me through it? According to Documentations, I am supposed to put the token in header. but How would I get the Token from DB and access it for every user and with every request? -
How to get the list of task already send to celery?
I'm unable to get the list of the tasks (actives, scheduled ..) in Celery. With django, my web application send a task with celery each time the url is asked with : tasksend = calcul.delay() I don't want to launch this calcul if it is already in progress in celery. So, I want to list the tasks Received by Celery and not yet finished : if my 'calcul' task is already in progress, i will then be able not to ask again for calcul.delay() I already search a lot and the responses in Retrieve list of tasks in a queue in Celery are not good for my celery version. I use : - django 2.0.13 - python 3.4.2 - celery v4.3.0 with redis I already tried : def inspect(method): app = Celery('app', broker='redis://localhost:6379') inspect_result = getattr(app.control.inspect(), method)() app.close() return inspect_result and print( inspect('active') ) always return None (the same result is achieved with 'registered') I would like to be able to get the name of the task in progress and scheduled in celery, any idea ? -
How to add user in admin page after verification of an account?
I am trying to add user in admin page after verification of an account. But whenever I register, the new user adds itself in admin page, although I didn't verify email address. How to do it? views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Account.' message = render_to_string('users/active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/confirm_email.html') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return render(request, 'users/confirmed_email.html') else: return HttpResponse('Activation link is invalid!') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() -
How can i receive errors having status code 500 only on self hosted sentry
I have hosted sentry, now i want to receive only those errors which have status code in 5xx(500) and not in 4xx(400,404,...). I am unable to find any option to do it. Just for reference, i am using sentry to track issue in Pyramid(python) project. -
Returning JSON reponse in Django from a specific function
I just started with Django today, I'm trying to get a JSON response from a certain function I have and save it all into database This is my function code: import nmap def nm_scan(ip): nm = nmap.PortScanner() nm.scan(ip, '0-65535') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname()), 'State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): lport = sorted(nm[host][proto].keys()) for port in lport: print('port : %s\tservice : %s' % (port, nm[host][proto][port]['product'])) I have my urls.py ready like so. urlpatterns = [ path('scan/', views.nm_scan), ] So I'm trying to understand how I would pass the parameter which would come in /scan/:ip and pass it to my function as parameter, then return the JSON data I have tried looking at some sample codes but I'm still stuck with just nonsense such as def nm_scan(request, ip): if request.method == 'POST': data = JSONParser().parse(request) # rest of the function here If someone could help me it would be great. Thanks.