Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding Django to already made HTML/css site
Hey guys so I been looking into making a site and was going to learn php for it but after a lot of research I saw how I can use Django for the backend of the site so I already started creating a site with HTML/css/js before I decide to use Django. Is there any possible way you can connect HTML/css to Django or do I need to re write everything in Django. I did look at some tutorials and saw how all the HTML was in django and I also did try looking it up too but couldn't find the right answer I'm looking for. If anyone could tell me I'll be very appreciated!! Thanks! -
django ajax crud request not loading for edit but works for create
I am trying to modify a simpleisbetterthancomplex.com tutorial to allow a crud for creating questions in a quiz. When I create a question the modal opens up just fine. When I try to open up the modal with edit which is a GET nothing loads. My View looks like: def save_question_form(request, quiz, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): question = form.save(commit=False) question.inquiz = quiz question.save() data['form_is_valid'] = True questions = quiz.question_set.all() data['html_question_list'] = render_to_string( 'quiz/partial_question_list.html', { 'questions': questions}) else: data['form_is_valid'] = False context = {'quiz': quiz, 'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def question_create(request, quiz_id): quiz = get_object_or_404(Quiz, pk=quiz_id) if request.method == 'POST': form = MCQuestionForm(request.POST) else: form = MCQuestionForm() return save_question_form(request, quiz, form, 'quiz/partial_question_create.html') def question_update(request, quiz_id, question_id): quiz = get_object_or_404(Quiz, pk=quiz_id) question = get_object_or_404(Question, pk=question_id) if request.method == 'POST': form = MCQuestionForm(request.POST, instance=question) else: form = MCQuestionForm(instance=question) return save_question_form(request, quiz, form, 'quiz/partial_question_update.html') My question.js: $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-question").modal("show"); }, success: function (data) { $("#modal-question .modal-content").html(data.html_form); } }); }; var saveForm = function () { var form … -
Django: m doesn't look like a module path
I can vistit the /admin url but went I login admin or call my login api. I got this error message error: ImportError at /admin/login/ m doesn't look like a module path Request Method: POST Request URL: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Django Version: 1.8.17 Exception Type: ImportError Exception Value: m doesn't look like a module path Exception Location: /root/.virtualenvs/areyoutired/lib/python3.4/site-packages/django/utils/module_loading.py in import_string, line 21 Python Executable: /usr/local/bin/uwsgi Python Version: 3.4.3 Python Path: ['.', '', '/root/.virtualenvs/areyoutired/lib/python3.4', '/root/.virtualenvs/areyoutired/lib/python3.4/plat-x86_64-linux-gnu', '/root/.virtualenvs/areyoutired/lib/python3.4/lib-dynload', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/root/.virtualenvs/areyoutired/lib/python3.4/site-packages'] -
Django REST Framework viewset doesn't obey pagination_class
I've successfully implemented a custom pagination_class for a certain ModelViewSet in my app, but I'm having issues implemeting a separate custom pagination_class for a basic ViewSet. Here's the working pagination_class and related ModelViewSet: class Model1Pagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class Model1ViewSet(viewsets.ModelViewSet): """ API endpoint that returns the instances of Model1 """ queryset = Model1.objects.all() serializer_class = Model1Serializer pagination_class = Model1Pagination @list_route() def extra(self, request) .... return <something> And this is the pagination_class and ViewSet which isn't working: class Model2Pagination(PageNumberPagination): page_size = 1 page_query_param = 'page_size' max_page_size = 1 class Model2GenericViewSet(viewsets.ViewSet): """ API endpoint to return the instances of Model2 """ def get_queryset(): return Model2.objects.all() pagination_class = Model2Pagination def list(self, request): queryset = self.get_queryset() serializer = Model2Serializer(queryset, many=True, context={'request': request}) return Response(serializer.data) I suppose I could alter the Model2GenericViewSet to function as a ModelViewSet, but I was hoping to avoid the refactor, and the DRF docs mention: Pagination is only performed automatically if you're using the generic views or viewsets So I figured using a ViewSet would be alright. I didn't originally specify a get_queryset() on the ViewSet, and my initial thought was that I needed to do so, however adding that didn't affect behavior. After … -
DRF Serializer Field return value different from value saved to database
How can I create a custom Serializer Field that returns a value different from the value saved to the database? For example: Database currently has the value ['alpha', 'bravo', 'delta'] It's updated with the value ['alpha', 'delta', 'E'] It should save ['alpha', 'delta', 'echo'] to the database and run a delete function on 'bravo' It should return ['alpha', 'delta', {'foo': 'E', 'bar': 'echo'}] in the 201 response (dictionary not necessary in 200 responses) -
create token and cookie when creating invite object
I want to implement the feature where users are not given to signup account directly. A request invitation button will be there. When user clicks for request invitation with an email address, a link will be send with token and when user clicks on that link, the user will be redirected to signup page. class Invite(models.Model): # INVITE_CHOICES = ( # ('G', 'General'), # ('I', 'Invitational'), # ) user = models.OneToOneField(User) cookie = models.UUIDField(default=uuid.uuid4) token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) timestamp = models.DateTimeField(auto_now_add=True) class InviteForm(forms.ModelForm): email = forms.EmailField() class Meta: model = Invite fields = ['email'] def clean_email(self, *args, **kwargs): email = self.cleaned_data.get('email') print('###############################') print ('email', email) email_qs = Invite.objects.filter(email__iexact=email) if not email: raise forms.validationError('Please! fill in your email address') if email_qs.exists(): print ('sorry the email exists') raise forms.validationError('Sorry! This email already exists') return email def invite_user(request): if request.method == 'POST': form = InviteForm(request.POST or None) if form.is_valid(): # data for sending mail form_email = form.cleaned_data.get('email') # from_email = settings.EMAIL_HOST_USER user = User.objects.create_user(form.cleaned_data.get('email')) user.is_active = False user.save() invite = Invite.objects.create(user=user, cookie=) send_mail('Subject', 'http://devfhrhzsne.connyct.com/%s' %invite.get_absolute_url(),'From', [form_email]) context = { "form": form, } return render(request, 'invitation.html', context) -
Multiple forms and one submit in django. Errors on the form that is not submitted
I am able to successfully update any of the three forms. However, my problem is that if the change password form is empty it throws errors on it (like passwords too short, incorrect current password etc), unlike the other forms where I don't get errors if I leave them unchanged. How can I approach the fix? I tried setting request.POST or None to no avail and I am running out of ideas. I also don't use {{ form.as_p }}, but rather go field by field. Could that be an issue? The form forms.py from django.contrib.auth.forms import PasswordChangeForm class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') widgets = { 'first_name': forms.TextInput(attrs={ 'class': 'lnd-user__input', 'id': 'first_name', 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={ 'class': 'lnd-user__input', 'id': 'last_name', 'placeholder': 'Last Name'}), 'email': forms.TextInput(attrs={ 'class': 'lnd-user__input', 'id': 'email', 'placeholder': 'Email'}), } class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('mobile',) widgets = { 'mobile': forms.TextInput(attrs={ 'class': 'lnd-user__input', 'id': 'mobile', 'placeholder': 'Phone Number'}) } class MyPasswordChangeForm(PasswordChangeForm): old_password = forms.CharField( label=("Old password"), required=False, strip=False, widget=forms.PasswordInput(attrs={ 'class': 'lnd-user__input', 'id': 'new_password2', 'type': 'password', 'placeholder': 'Old Password'}), ) new_password1 = forms.CharField( label=("New password"), required=False, widget=forms.PasswordInput(attrs={ 'class': 'lnd-user__input', 'id': 'new_password2', 'type': 'password', 'placeholder': 'Enter new Password'}), strip=False, … -
Django - Copying model field to another field
I did a lot of search but couldn't find a proper way to do it. I want to copy some model object data to another model object data. I've added my codes below. I got 3 models. as you can see I got a FK , the Receipt model related with receipt field. when I want to add Receiptitem object I wanna copy amount , vat and total_amount exactly. I didn't understad save method. class Receipt(models.Model): amount = models.DecimalField(max_digits=5, decimal_places=2) vat = models.DecimalField(max_digits=5, decimal_places=2) total_amount = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return str(self.total_amount) class ReceiptItem(models.Model): receipt = models.ForeignKey('Receipt', on_delete=models.CASCADE ) product = models.ForeignKey('Product', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2) vat = models.DecimalField(max_digits=5, decimal_places=2) vat_rate = models.DecimalField(max_digits=5, decimal_places=2) sub_total = models.DecimalField(max_digits=5, decimal_places=2) name = models.CharField(max_length=200) class Product(models.Model): name = models.CharField(max_length=200) vat_rate = models.DecimalField(max_digits=5, decimal_places=2) amount = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name -
How to add assigned variable to nextline in django template tags
I am currently writing a django template tag and it working well however it looks ugly since i have a lot of variables to assign and it is very long. {% include "snippetSelect.html" with fieldName=form.status.name fieldValue=form.status.value fieldData=mission.status_as_dict fieldLabel="Select a Status" only %} it there any way i can just add the assigned variable next line like this {% include "snippetSelect.html" with \ fieldName=form.status.name \ fieldValue=form.status.value \ fieldData=mission.status_as_dict \ fieldLabel="Select a Status" only %} Thank you in advance. -
How do I call a angularJS function after a row selection event in django
I need to display the selected row id when a row selection event occurs in datatable worklist. I'm trying to do with an angularJS function as below, function selectedrows($scope){ dtWorklist = datatable_worklist.get_selected_rows; if (dtWorklist.length>0) { console.log("dt", dtWorklist[0].id);} } selectedrows($scope); How do I call the function which I created after the row selection event? Will it be a proper way to create an event and call the function? Or could it be done by giving a load time to this function? Any new approaches is welcome. Thanks. -
Error using Django, Windows 10 Python 3.5-32 (Python Crash Course)
I'm working through the book Python Crash course and I'm on chapter 18, where we learn about Django. I've followed all of the instructions and when I try to run the first code models.py I get this error: Traceback (most recent call last): File "models.py", line 3, in <module> class Topic(models.Model): File "models.py", line 5, in Topic text = models.CharField(max_length=200) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", line 1043, in __init__ super(CharField, self).__init__(*args, **kwargs) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "C:\Python35-32\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__ self._setup(name) File "C:\Python35-32\lib\site-packages\django\conf\__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried looking on here and trying a few solutions but nothing seems to work. Any help would be appreciated. Thank you very much -
Loading Csv file to Sqlite
Create a shell command that cleans the Csv file and converting all words to lowercase, and remove any characters that are not [0-9 a-z] and loads it into the database.How do i do this? Any help would be appreciated ! -
Removing "recipients" field from Django form using django-postman, and setting automatically
I'm building a project in which users can (amongst other things) click onto a "product" page, and then message the owner of that particular product, by clicking on a "Send Message" button from the product page. I'm using the django-postman application for my messaging system, and seem to have it working correctly. However, I'd like the "receiver_id" of the message object to be set automatically to the user_id of the product owner, but there is a "recipients" field in the message-writing form that I don't seem to be able to remove. I tried creating a custom WriteForm in which I excluded the "recipients" field, and yet it still showed up on the form (even though when I tried excluding other fields instead, they did as expected and stopped showing up), so there must be more going on there than I'm aware of. (Incidentally, I am aware that removing this field, with the app working as it does currently, would mean that no "receiver_id" could actually be submitted, but I was hoping it would be simple to stop it appearing on the form despite this, and then I could worry about how to actually set the receiver.) This is what I … -
File in the pipeline: JSON File >> Django >> HTML >> API >> Json File
We need read a json file (multi object), build a form table to edit the values and write over original json file via API. We have two problems: 1. The process on the web mixes the json objects 2. The api request write in the file the csrf token We need the same file than the original if I dont change anything. Thanks data.json [ { "species": "Dahut", "name": "Hypatia" }, { "species": "Felis Stultus", "name": "Billie" } ] view import json def go(request): template = loader.get_template('information/go.html') file = open('data.json', 'r') data = json.loads(file.read()) file.close() context = { 'data': data, } return HttpResponse(template.render(context, request)) go.html <form enctype='application/json' action="http://localhost:8000/api/data/" method="post"> {% csrf_token %} {% for row in data %} {% with forloop.counter0 as counter %} {% for key, value in row.items %} <input type="text" name='[{{ counter }}][{{ key }}]' value='{{ value }}'> {% endfor %} {% endwith %} {% endfor %} <button type="submit">Send</button> </form> Api.view class ChartData(APIView): def post(self, request, *args, **kw): data = json.dumps(request.POST) file = open('data.txt', 'w') file.write(data) file.close() response = Response(data, status = status.HTTP_200_OK) response['Access-Control-Allow-Origin'] = '*' return response Wrong Data.txt Result All in one object, with csrf {"csrfmiddlewaretoken": "tTvcjS6khz21F0qj4H5LEUNiy6rYZeSCNQOukFaeukzsUvbUYlY4zCGOs8RFrgOs", "[1][species]": "Felis Stultus", "[0][name]": "Hypatia", "[1][name]": "Billie", "[0][species]": … -
django customizing user view?
i make customizing user. so i need to login with email. user = authenticate(email=email, password=password) seems not working... help me... let me know of how to fix my views.py. here is my view. from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from django.core.urlresolvers import reverse from django.shortcuts import render from LanguageExchange.forms import UserCreationForm,UserChangeForm def index(request): context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"} return render(request, 'LanguageExchange/index.html', context=context_dict) def register(request): # A boolean value for telling the template # whether the registration was successful. # Set to False initially. Code changes value to # True when registration succeeds. registered = False if request.method == 'POST': user_form = UserCreationForm(data=request.POST) # change_form = UserChangeForm(data=request.POST) # if the two forms are valid.. if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() #if change_form.is_valid(): # change = change_form.save() # change.set_password(user.password) # change.user = user registered = True else: print(user_form.errors) else: user_form = UserCreationForm() # change_form = UserChangeForm() return render(request, 'LanguageExchange/register.html', {'user_form': UserCreationForm, 'registered': registered}) def user_login(request): if request.method == 'POST': username = request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your Rango account is disabled.") else: print("Invalid login details: {0}, {1}".format(email, password)) return HttpResponse("Invalid login … -
Django request in html
I have set up django to work in my local environment. I have a python function which takes two parameters and returns data in JSON format. This is set up in my views.py and urls.py as follows: views.py : from django.http import Http404, HttpResponse from X import calculate def calculate_X(request, para1, text): #para1 is ignored on purpose return HttpResponse(calculate(text)) urls.py : urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^calculate-X/(\d+)/([a-zA-Z0-9_ ]*$)',calculate_X), url(r'^$', TemplateView.as_view(template_name='base.html')), ] urlpatterns += staticfiles_urlpatterns() In the base.html file I have a single button which should make the request to the calculate-x url as follows /calculate-X/1/stringdataexample which would then create an alert() with the contents of the httpresponse ( JSON ) How can I make this request? (There is another question asked here on SO however it uses request processors which do not relate to my question) -
Django: - NoReverseMatch error
I'm following the djangoforgirls.org tutorial on making my first django site. I'm trying the stage "extending your template" to make a link to an article within my website that uses the general template. I keep get thrown the error: "NoReverseMatch at /, Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$']" Some variable and file names may seem strange, the use of the website was music sampling but I used the tutorial's names for things in case that was what was wrong. My urls.py for entire project: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('sample.urls')), ] My urls.py for the specific app (sample): from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), ] My views.py for the app: from django.utils import timezone from .models import AudioSample from django.shortcuts import render, get_object_or_404 def post_list(request): samples = AudioSample.objects.order_by('length') return render(request, 'blog/post_list.html', {'samples': samples}) def post_detail(request, pk): post = get_object_or_404(AudioSample, pk=pk) return render(request, 'blog/post.html', {'post': post}) And the line of code from the base template that's the link to another page in the website: <a href="{% url 'post_detail' pk=post.pk … -
Crispy Field helper not modifying input
I thin this should be pretty simple. I'm testing out using django-crispy-forms with Bootstrap. I've got a pretty simple forms.py and I'm just trying to get a user to enter a date. I would like to take advantage of the nice UI features that come with an <input type='date'> will render as but I cannot seem to get it to render. Here is my forms.py from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, Field, ButtonHolder class MonthForm(ModelForm): self.helper.layout = Layout( Field('first_of_month', type='date') ) But when I render the form this corresponds to I get the following html: <input class="dateinput form-control" id="id_first_of_month" name="first_of_month" type="text" required=""> I have tried adding other kwarg arguments and everything else renders in the outerHTML for the field. I cannot figure out why type appears to be special unless it is some sort of reserved keyword, but then I would expect to see some posts about how to get around it and I have not thus far. I have the template pack in my settings.py set to CRISPY_TEMPLATE_PACK="bootstrap3" Any insights would be most appreciated, Thanks! -
Proxy my Elastic Search connection through Django for filtering
I believe I need to proxy my ElasticSearch connection via a Django URL in order to do filtering by user token. So instead of going via localhost:9200/_search, I want to use localhost:8000/myapi/elastic/_search. I am unsure how to connect them. I've tried using a serializers/views setup myapp/search.py class TaskIndex(DocType): title = String() class Meta: index = 'task-index' # Bulk indexing function, run in shell def bulk_indexing(): TaskIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.Task.objects.all().iterator())) # Simple search function def _search(title): s = Search().filter('term', title=title.text) response = s.execute() return response api/serializers.py from myapp.search import TaskIndex class ElasticSerializer(serializers.ModelSerializer): class Meta: model = TaskIndex api/views.py class ElasticViewSet(viewsets.ModelViewSet): queryset = TaskIndex.objects.none() serializer_class = ElasticSerializer api/urls.py router.register(r'elastic', ElasticViewSet) -
Python Django Datetime Field that doesn't need all the information
I am looking to have a model that can accept a partially completed date as one of its field. The field is supposed to represent the date that a historical event happened. Some of these events are only known to the year or month and not to the day. Is there any graceful way to handle this? -
Configurable password validator startup errors
I'm implementing a custom password validator that refers to settings in the database that an admin user can change. A simplified example: class ConfigurableMinimumLengthValidator(object): def get_value(self): return MyConfigModel.objects.first().password_minimum_length def validate(self, password, user=None): min_len = self.get_value() if len(password) < min_len: raise ValidationError("Password too short, must be > %s long." % min_len) def get_help_text(self): min_len = self.get_value() return "Password must be > %s long." % min_len Django calls get_help_text() during its initial setup, which is roughly equivalent to making a database call during module import. This causes all kinds of chicken-and-egg problems: If the MyConfigModel table doesn't exist yet, say on a new database, it raises an OperationalError. If the table exists but the password_minimum_length field doesn't exist, it raises a ProgrammingError. Finally, if the field exists but there are no rows in the table, that's a MyConfigModel.DoesNotExist exception. That one is manageable. The first two make it impossible to resolve without taking the password validator out of settings.py, as the error happens during ./manage.py migrate and every other management command. At first I planned to just catch these exceptions and return a default value; it'll query again during actual validation. But I'm not sure I've thought of all of the possible … -
django- why persian texts not display properly?
i worked on a django project. now i deployed the project on real physical server.but there is a problem.in the production, site does not display persian texts that saved in Database(MySQL) properly, while in my laptop (localhost) it displays persian texts without any problem. as you see, other texts(that are not from the database) was displayed correct, but those texts that are from the database, was displayed ????????? . what's the problem and how to solve it? tanx. -
roblem with property in Django Model
I want to improve my view in django using property in Models. commentd code worked fine but when I add property in Model I got blank space in template views.py: cal_day = {} cal_day['day'] = day cal_day['day_event'] = False cal_day['sports'] = [] for event in event_list: if day >= event.reservation_date.date() and day <= event.reservation_date.date(): cal_day['day_event'] = True hours_week.append(event.reservation_date.time()) # a = Reservation.objects.get(id=event.id) # d = dict() # d['id'] = a.id # d['sport'] = a.sport # d['trainer'] = a.trainer # d['reservation_date'] = a.reservation_date # d['free_space'] = (a.sport.capacity - a.users.count()) # d['duration'] = a.sport.duration # d['time'] = a.reservation_date.time() # cal_day['sports'].append(d) print(Reservation.reservation_info) cal_day['sports'].append(Reservation.reservation_info) models.py class Reservation(models.Model): sport = models.ForeignKey('Sport') trainer = models.ForeignKey('MyUser' ,related_name='Trainer') users = models.ManyToManyField('MyUser', blank = True) reservation_date = models.DateTimeField(null = True, blank = True) @property def reservation_info(self): d = dict() d['id'] = self.id d['sport'] = self.sport d['trainer'] = self.trainer d['reservation_date'] = self.reservation_date d['free_space'] = (self.sport.capacity - self.users.count()) d['duration'] = self.sport.duration d['time'] = self.reservation_date.time() return d def __str__(self): return '{} , {}'.format(self.sport, self.reservation_date) in terminal get printed objects: If someone can help to understant what I am doing wrong and how i can improve it to fork fine i will by greatefull :) -
Django: allowing for "None" in ForeignKey queryset filter
I have two models that look like this: class Color(models.Model): ... class Item(models.Model): color = models.ForeignKey(Color, blank=True, null=True) ... I have a list of Color objects that I've ended up at through some complicated process. Call it my_colors. If I want to get all Item objects which have a color in my list, I can do this: Item.objects.filter(color__in=my_colors) However, notice that an Item object can have no color. I want all Item objects which have a color in my list, or have no color. Restated, I want a queryset of all Item objects, excluding those which have a color that is not in my list. I can do this with a Q query: Item.objects.filter(Q(color__in=my_colors) | Q(color=None)) But I'm not sure if that is the best way to do this. Is using the Q the best approach for this? -
Python/Celery - catch SoftTimeLimitExceeded
I have i code where i try to start a many "small" tasks from current "big" task. # This function try to fetch content and parse separate URL. Time limit = 10 sec @celery_app.task( soft_time_limit=10, autoretry_for=(OperationalError, ), max_retries=3, ignore_result=False ) def search_job(...) try: markup, error = get_content(url) # my code here except SoftTimeLimitExceeded: print ("Ops in!") log += url + " - Soft Time Limit Exceeded Error Catch!\n" return result # This function create a group job and waits for their result @celery_app.task( queue="ta", soft_time_limit=600, autoretry_for=(OperationalError, ), max_retries=3, base=BaseCeleryTask ) def search(...): try: group_work = group(search_job.s(..., url) for url in list_urls)() while not group_work.ready(): time.sleep(1) except SoftTimeLimitExceeded: # so, if the "big" task waits for group result more than 600 sec i want to revoke all "small" tasks and logs a error for this "big" task group_work.revoke() log = "Big task time limit exceeded!" else: with allow_join_result: results = group_work.get() But there are a problem - Celery catch only one exception in "small" task. Here is a terminals output: [2017-03-14 18:41:57,384: WARNING/PoolWorker-1] START URL = http://www.relaxa.ru/shop/634-assazhnye_krovati_i_stoly/659-massazhnye_krovati/ [2017-03-14 18:41:57,876: WARNING/MainProcess] Soft time limit (1s) exceeded for seo_work.ta.search_job[7a597fe7-6bdc-4e07-8f50-83fdc99412c8] [2017-03-14 18:41:57,878: WARNING/PoolWorker-1] Ops in! [2017-03-14 18:41:57,886: WARNING/MainProcess] Soft time limit (1s) exceeded for …