Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'CustomUser' object is not iterable
I am trying to establish a user type base register/login system for my e-commerce app. I have used the following codes in my views file. here's the code snippet from my models.py. Just given the customer class as i am focusing on that first. class CustomUser(AbstractUser): user_type_choices=((1,"Merchant"),(2,"Customer")) user_type=models.CharField(max_length=255,choices=user_type_choices,default=1) class Meta(AbstractUser.Meta): swappable = "AUTH_USER_MODEL" class CustomerUser(models.Model): auth_user_id=models.OneToOneField(CustomUser,on_delete=models.CASCADE) user=models.OneToOneField(CustomUser,on_delete=models.CASCADE, related_name='customer', null= True,blank=True) name= models.CharField(max_length = 255, null= True) firstname = models.CharField(max_length = 255, null=True) lastname = models.CharField(max_length = 255, null=True) email = models.CharField(max_length = 255, null=True) profile_pic=models.FileField(default="") created_at=models.DateTimeField(auto_now_add=True) So, as far I can say that I am logged in but can't access my home page as I got the following error. TypeError at / 'CustomUser' object is not iterable ....... Local vars F:\rewards\projectreward\rewardapp\userviews.py, line 152, in store data = cartData(request) … Local vars F:\rewards\projectreward\rewardapp\utils.py, line 43, in cartData order, created = Order.objects.get_or_create(request.user, complete=False) … I'm not sure why my cartData function in utlis.py is affected by this. It worked perfect when I didn't used user type base login. However, here's the cartData from utils.py. def cartData(request): if request.user.is_authenticated: order, created = Order.objects.get_or_create(request.user, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] … -
How to serve staticfiles from docker django app to hosted nginx
My goal is to serve the staticfiles to nginx on ubuntu from a docker django app container without using docker nginx I setup the reverse proxy to django all works fine in dev mode but when i turn Debug to False nginx doesn't recognize the staticfiles path here's a screenshot Here's my dockerfile for django app FROM python:3.9 RUN mkdir /app WORKDIR /app COPY . /app RUN pip install pipenv RUN pipenv install --system --deploy --ignore-pipfile EXPOSE 8000 ENTRYPOINT ["python", "manage.py"] CMD ["runserver", "0.0.0.0:8000"] And here's my nginx config upstream django { server 127.0.0.1:8001; } server { server_name django.com; listen 80; listen 8000; client_max_body_size 100M; location / { proxy_pass http://django; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header X-Forward-Proto http; proxy_set_header X-Nginx-Proxy true; proxy_redirect off; proxy_read_timeout 1000; proxy_connect_timeout 1000; proxy_send_timeout 1000; } } -
How to get value of django form within that same form before submission?
I'm creating a django form with 3 choice fields. I want the 3rd choice field (object field) to populate based on the first 2 choice fields. Boiling it down, I guess my question would be how do I get the values of the first 2 choice fields so I can use those values within the same form.py before submitting? Here is what my forms.py looks like, which is currently giving me the error "maximum recursion depth exceeded": class MyForm(forms.Form): season = forms.ChoiceField( widget=forms.Select(attrs={"class": "form-control test"}), label="season", choices=SEASON_CHOICES, ) episode = forms.ChoiceField( widget=forms.Select(attrs={"class": "form-control"}), label="episode" ) object = forms.ChoiceField( widget=forms.Select(attrs={"class": "form-control"}), label="object", ) def __init__(self, *args, **kwargs): super(forms.Form, self).__init__(*args, **kwargs) form = MyForm() season = form.cleaned_data.get["season"] episode = form.cleaned_data.get["episode"] try: snow = Snowflake() snow_data = snow.query( f"""select * from modern_family""" ) object_data = snow.query( f"""select * from {season}.{episode}""" ) snow.close() self.fields["episode"].choices = [(sd[0], sd[0]) for sd in snow_data] self.fields["object"].choices = [(sd[0], sd[0]) for sd in object_data] except Exception as e: print(e) -
How to resend the same request again in Django api
I have a BuyproducTviewset using createModelMixin that create an instance when post request is made however I want to repeat the same create request again after 5 seconds from the api depending on a condition if the price is greater than a specific range. class BuyProductViewset(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer_class = UserproductSerializer queryset = Userproducts.objects.all() def data_serialize(self, user_id, product_ID): data = {"user": user_id, "product": product_ID} serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return serializer, headers def create(self, request, *args, **kwargs): user_id = request.data["user_id"] product_id = request.data["product_id"] total = request.data["total"] upper_bound = request.data["upper_bound"] lower_bound = request.data["lower_bound"] product = ( product.objects.filter(product_id=product_id) .order_by("timestamp") .reverse()[:1] .values("id", "name", "price", "availability") .get() ) product_ID = product["id"] product_price = product["price"] product_availability = product["availability"] product_name = product["name"] if product_price >= int(lower_bound) and product_price <= int(upper_bound): serializer, headers = self.data_serialize(user_id, product_ID) product.objects.create( product_id=product_ID, name=product_name, price=product_price, availability=product_availability - int(total), ) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) else: time.sleep(5) # RESEND THE SAME REQUEST WITH THE SAME DATA return a response -
How to create a Domain Name for a Django App in a LAN
I recently built a Django app that I am running on a Linux machine with Gunicorn and NGINX. The app is being run inside my company's network which is predominantly a windows environment. Currently, I am able to access the web app via the server's IP address. I know if it was a windows machine I could use the DNS to have it called by a DN. How accomplish this given that it's a Linux machine? For example, I would like to have the company users call the web app from a browser using http://analytics instead of its IP address. Would make the app much more user-friendly instead of always typing in the IP and just for best practice it's probably not secure to be showing the end user the IP anyways. -
What is the equivalent of <input id="id"> with Django form
I am trying to input results from Autocomplete in (a.js file) into a Django form (html). Currently the html file looks like this: Template <input class="field" id="street_number" disabled="true" /> Obvioulsy, I cannot input directly {{form.street_number}}. I have found a few posts on the topic, (in particular this one: How to get form fields' id in Django), but I am not too sure to understand how this solves the problem. .js file function initAutocomplete(){ autocomplete = new google.maps.places.Autocomplete(document.getElementById("autocomplete"),{ componentRestrictions: {'country':['uk']}, fields: ['name','geometry','address_components'], types:['establishment','geocode'] }); autocomplete.addListener('place_changed', fillInAddress ); } function fillInAddress(){ // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); //showsdiffrent address components (click on 'inspect' on webpage to see) console.log(place); document.getElementById('business').value = place.name; //loop through address components detailed in consol for (let i = 0; i < place.address_components.length; i++) { for (let j = 0; j < place.address_components[i].types.length; j++) { ... if (place.address_components[i].types[j] === "street_number") { document.getElementById('street_number').value = place.address_components[i].short_name; } ... I suppose the question is how do I translate <input id="id"> into django form terms? Maybe there is a possibility to apply an id in the django form.py itself? I tried a solution found on here, but I am getting an error saying TextInput is not … -
Get Django API data from a non-static url using Ajax-Jquery [Without REST Framework]
In my server-side app created with Django, I need to show articles based on the url, which contains year, month and user_id of articles. blog/1/2022/8 should shows all articles of august. In client-side app (Jquery), I have to call an API which returns all articles filtered by year and month. How can I set the url in ajax with the variable informations of year and month? urls.py (I have to use these urlpatterns): app_name = 'blog' urlpatterns = [ #link to API path('API/<int:user_id>/<int:year>/<int:month>', views.get_articles, name='get_articles'), #link to html file path('<int:user_id>/<int:year>/<int:month>', views.index, name='index'), ] Model: from django.contrib.auth.models import User class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() title = models.CharField(max_length=50) content = models.TextField() def __str__(self): return self.title def get_year(self): return self.pub_date.year def get_month(self): return self.pub_date.month Views: def index(request, **kwargs): return render(request, template_name='blog/index.html', context={'user_id':kwargs.get('user_id')}) #return json data with articles filtered by year and month of url def get_articles(request, **kwargs): articles = Article.objects.filter( pub_date__year = kwargs.get('year'), pub_date__month = kwargs.get('month'), ).values('title','author','pub_date') data = { 'articles' : list(articles) } return JsonResponse(data) index.html: {% block content %} <div class="container"> <br><h3>Articoli</h3> <div id="article_list"></div> </div> {% endblock content %} blog.js: $(document).ready(function(){ $.ajax({ url: WHICH URL?, dataType:'json', success: function(data){ for(var i=0; i < data.length; i++){ var item = … -
Django + Mongoengine - settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
And here I am again. I am trying to connect my app to MongoDB as I want to implement a non-rel database. The application works fine with SQL3Lite and I was also able to use Djongo. Yet, I am planning to use MongoEngine models and therefore I am trying to use it as DB Engine. However, for whatever reason I receive an error settings. "DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details." Here is what I did: django-admin startproject projectname python manage.py startapp appname Models.py: from django.db import models from django.db.models.fields.related import ForeignKey from django.db.models.query import EmptyQuerySet from django.contrib.auth.models import User,AbstractUser, UserManager import datetime import mongoengine # Create your models here. class Project(mongoengine.Document): projectName = mongoengine.StringField() Settings.py mport os from pathlib import Path import mongoengine mongoengine.connect(db="testdatabase", host="mongodb+srv://<Username>:<Password>@cluster0.qspqt0a.mongodb.net/?retryWrites=true&w=majority") # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = secretKey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Django testing doesn't recognize dirty_fields?
One of my models uses dirty_fields. The save method detects when the field scale_mode changes. Once this happens, it goes through all the related grade objects and changes the field score for each affected grade. The goal is if VSB is swapped with VSBPLUS, then APP is swapped with APP+. model: class GradeBookSetup(DirtyFieldsMixin, models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=CASCADE) VSB = 'VSB' VSBPLUS = 'VSBPLUS' SCALEMODE = [ ('VSB', 'BEG DEV APP EXT'), ('VSBPLUS', 'BEG DEV APP APP+ EXT'), ] scale_mode = models.CharField( max_length=7, choices=SCALEMODE, blank=True, default=VSB) def save(self, *args, **kwargs): super(GradeBookSetup, self).save(*args, **kwargs) if self.is_dirty(): dirty_fields = self.get_dirty_fields() if 'scale_mode' in dirty_fields: if self.scale_mode == "VSB": n = 0 objs = Grade.objects.filter(user=self.user) for grade in objs: if grade.score == "APP+": objs[n].score = "APP" n = n + 1 Grade.objects.bulk_update(objs, ['score']) elif self.scale_mode == "VSBPLUS": objs = Grade.objects.filter(user=self.user) for grade in objs: if grade.score == "APP": objs[n].score = "APP+" Grade.objects.bulk_update(objs, ['score']) class Grade(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) INCOMPLETE = 'I' BEGINNING = 'BEG' DEVELOPING = 'DEV' APPLYING = 'APP' APPLYINGPLUS = 'APP+' EXTENDING = 'EXT' score = models.CharField( max_length=4, blank=True, default=INCOMPLETE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) assessment = models.ForeignKey( Assessment, on_delete=models.CASCADE, null=True, blank=True) objective = … -
Passing object to Django custom filter
I am using Django 3.2 I am writing a moderation app, and I want to be able to display only approved values in my template. I want to be able to use the new filter like this: {{ moderated_object.field_name | approved }} This is what I have so far: from django import template register = template.Library() @register.filter(name='approved') def moderator_approved_field_value(moderated_object, fieldname): return moderated_object.approved_value(fieldname) As I have written the filter above, I can only use it like this: {{ moderated_object| approved: fieldname }} Which is ugly. Is there a way that I can pass the object to the function behind the scenes, so that I can use the cleaner way of using the filter in my template? -
Get all objects' django guardian permissions of the authenticated user in template
I have an application where I am using django-guardian for object-level permission. In my ListView, I am listing all my instances in a table. In each row, I need to show the edit button if the user has the permission to edit this object. So, I doing something like: {% extends "base.html" %} {% load guardian_tags %} {% block content %} <table> <thead>...</thead> <tbody> {% for i in items %} <tr> <td>{{ i.name }}</td> <td> {% get_obj_perms request.user for i as "i_perms" %} <!-- this one --> {% if "change_item" in i_perms %} <a href="{% url 'edit_item' i.id %}">Edit</a> {% endif %} </td> </tr> {% endif %} </tbody> </table> {% endblock %} Problem Doing it that way is not optimized solution from database-wise. This solution makes a database query for each object to get the user permissions. How can I do so but with a single hit to the database to get all the objects' user permissions? -
Is there a way to make the 'One' table optional in OneToManyRelationship in Django
I have two tables, one is Anonym the other is Userdatabase. I want my app to work without requiring any login info therefore it will work with Anonym only by using the deviceid of the user to process account information. If however, a user wants to access extra features they need to create a user with username/password. Then I will process the data using Userdatabase table. A user can have multiple devices so there is a OneToMany relationship in there, but a device doesn't have to have a User (they don't need to register) which breaks the relationship. Is there a way to make the Userdatabase table optional while keeping the OneToMany relationship? Perhaps by inserting a method or another class within UserDatabase? Please find the code below: --Models-- class Anonym(models.Model): deviceid=models.ForeignKey(Userdatabase,max_length=200,on_delete=models.SET_NULL,null=True) accounttype=models.TextField(default='Free') numberofattempts=models.IntegerField(default=0) created=models.DateField(auto_now_add=True) class Userdatabase(models.Model): username=models.CharField(max_length=20,unique=True) password=models.CharField(max_length=20) deviceid=models.TextField(default='inputdeviceid') accounttype=models.TextField(default='Free') numberofattempts=models.IntegerField(default=0) created=models.DateField(auto_now_add=True) --urls-- urlpatterns=[path('deviceregister/<str:id>/',views.deviceregistration)] --views-- def deviceregistration(request,id): import time deviceid=id newdevice-models.Anonym(created=time.strftime("%Y-%m-%d"),deviceid=deviceid) newdevice.save() return HttpResponse('Succesful registration') When I send a request as '/deviceregister/123456/' for example, django raises an ValueError saying Cannot assign "'123456'": "Anonym.deviceid" must be a "Userdatabase" instance. -
Adding onclick into the field that's created by adding can_delete to formset
How can I add onclick="functionName()" to the field that is created by using can_delete=True in formset? <input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" onclick="functionName()"> -
Does UserRateThrottle get overridden by ScopedRateThrottle?
We have a number of endpoints that we need burst speeds for which seems to perfectly be what ScopeRateThrottle is for, but we also have a number of endpoints we want to generally rate-limit. Is UserRateThrottle compatible with ScopedRateThrottle? Does one override the other? For example, can ScopedRateThrottle have a higher number than UserRateThrottle? "DEFAULT_THROTTLE_CLASSES": [ "rest_framework.throttling.AnonRateThrottle", "rest_framework.throttling.ScopedRateThrottle", <--- Maybe this is evaluated by order? "rest_framework.throttling.UserRateThrottle", ], "DEFAULT_THROTTLE_RATES": { "anon": "20/hour", "user": "60/hour", "burst": "100/minute", }, -
Django 3.2.5 read-only DateTimeField
I'm trying to get to show the creation date of a model inside the Django administration, but everytime I use auto_now_add, it disappears from the user (superuser) view. In models.py: class Project(models.Model): readonly_fields=('creation_date', 'modified') project_id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) name = models.CharField(max_length=200) description = models.TextField(blank=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=datetime.now) #This is what I want to show modified = models.DateTimeField(auto_now=datetime.now) #I also want to show this one start_date = models.DateField(blank=True, null=True) # Orders the projects by date class Meta: ordering = ['start_date'] def __str__(self): return '{} - {}'.format(self.brand.customer.name, self.name) My admin.py: from django.contrib import admin from .models import Customer, Project, Brand, Supplier, Quotation, Expense admin.site.register(Customer) admin.site.register(Brand) admin.site.register(Project) admin.site.register(Supplier) admin.site.register(Quotation) admin.site.register(Expense) -
How to Pass the request to another Serializer for Validation
I have two tables in my database to insert a product record. I am storing the product info in the Product table and the rest of the info like Pirce, Quantity etc storing to another table which is ProductStock. I am planning to send the data to a server something like this. { "name":'product name', "brand":"socialcodia" "product_stock":{ "price":"100", "quantity":"50" } } I am easily able to validate the product info from ProductSerializer. But I don't have any perfect idea to validate the ProductStockSerializer data. ProductSerializer from rest_framework import serializers from .models import Product from .models import Medical class ProductSerializer(serializers.ModelSerializer): medical = serializers.CharField(read_only=True) id = serializers.CharField(read_only=True) is_visible = serializers.CharField(read_only=True,default=True) class Meta: model = Product fields = ['id','medical','category','item','brand','is_visible'] def validate(self, attrs): request = self.context.get('request') attrs['medical'] = Medical.objects.get(pk=request.info.get('medical')) return attrs Here I want to validate the product_stock info as well. cuz it's coming with a single request. So is there any way that i can import the ProductStockSerializer into ProductSerializer and pass the data to that serializer. then validate it. ProductStockSerializer from rest_framework import serializers from .models import ProductStock from medical.models import Medical class ProductStockSerializer(serializers.ModelSerializer): medical = serializers.CharField(read_only=True) class Meta: model = ProductStock fields = ['medical','distributer','product','variant','batch','purchase_price','price','quantity','location','low_stock','expire_date'] def validate(self, attrs): attrs['medical'] = Medical.objects.get(self.context.get('request').info.get('medical')) batch … -
Still getting validation error despite using save(commit=False)
Model form: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['title', 'slug', 'category', 'description', 'thumbnail', 'status', 'author'] view: if request.method == 'POST': form = ArticleForm(request.POST, request.FILES) if not request.user.is_superuser: art = form.save(commit=False) # Error line art.author = request.user art.status = 'd' art.save() return HttpResponseRedirect(reverse('account:home')) elif form.is_valid(): form.save() return HttpResponseRedirect(reverse('account:home')) return render(request, 'registration/add-update-article.html', { 'form': form }) If the user is not a superuser, they can not fill some fields in the form so I want to set their values in this view. Isn't commit=False supposed to prevent raising validation errors? Why do I still get an error? -
'bytes' object has no attribute 'name' django
so i want read file txt what i was input. but the file became in bytes because i encode it. how to open the file and can be print out? i want to encrypt that message in the file txt. the error message like this f = open('media/txt/'+f.name, 'r') AttributeError: 'bytes' object has no attribute 'name' i was trying like this to read the file def read_file(f): f = f.encode("utf8") f = open('media/txt/'+f.name, 'r') file_content = f.read() f.close() print(file_content) and i called that function plaintext = Audio_store.objects.all().values_list('password').last() pt = plaintext[0] read_file(pt) -
Django using functions outside of classes
I have this model class model(models.Model): user_fk = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) JGB_A1 = models.IntegerField(default=0) JGB_B1 = models.IntegerField(default=0) JGB_C1 = models.IntegerField(default=0) JGB_D1 = models.IntegerField(default=0) JGB_E1 = models.IntegerField(default=0) Davon_E3 = models.CharField(max_length=100, blank=True, null=True) @property def sum_of_1(self): return self.JGB_A1 + self.JGB_B1 + self.JGB_C1 + self.JGB_D1 + self.JGB_E1 def __str__(self): return '{}'.format (self.user_fk) and I need the calculations displayed in another model for further calculations. The goal is to have models with values from users and another model which calculates everything together and display other values based on users values a lot of values. What are my options, I thought about singals or using functions outside of classes but trying that gave me instant a server error -
BooleanField in ModelSerializer
I want to display the content of Trader class through an API call. But I don't know where am I wrong. models.py class Trader(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="trader") bot_status = models.BooleanField(blank=False, default=False) active_group = models.ManyToManyField(Entry, blank=True, related_name="active_group") def __str__(self): return f'{self.user.username}' def __repr__(self): return f'Trader=(bot_status={self.bot_status}, active_group={self.active_group})' serializers.py class BotStatusSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source = 'user.username') class Meta: model = Trader read_only_fields = ('bot_status', ) views.py class BotStatusView(viewsets.ModelViewSet): serializer_class = BotStatusSerializer def get_queryset(self): return self.request.user.trader.bot_status When I make the request I get the following Error. Error: return [ TypeError: 'bool' object is not iterable -
How to download file using django as backend and nginx
I have a filefield in a document model from which i can upload files like this document=models.FileField(max_length=350 ,validators=[FileExtensionValidator(extensions)]) uploading is working good, now i want to implement download feature for the frontend, but only those files which are uploaded by the user. using url method is think less secure, another way i saw is creating download function in the views, and another i saw using nginx i can implement. Kindly guide me which method is best, and what steps to take to implement the download feature, and will i need docker too if i am using nginx? -
List of objects return empty - using django - mixins, generic views
views.py class ReviewList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Review.objects.all() serializer_class = ReviewSerializer def get(self,request,*args,**kwargs): return self.list(request, *args, **kwargs) def post(self,request,*args,**kwargs): return self.create(request, *args, **kwargs) models.py class Review(models.Model): rating = models.PositiveIntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) description = models.CharField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) watchlist = models.ForeignKey(WatchList, on_delete=models.CASCADE, related_name='reviews') def __str__(self) -> str: return str(self.rating) + ' - ' + self.watchlist.title urls.py urlpatterns = [ path('list/', WatchListAV.as_view(), name='movie-list'), path('<int:pk>', MovieDetailsAV.as_view(),name='movie-details'), path('stream/',StreamPlatformAV.as_view(),name='stream-list'), path('stream/<int:pk>', StreamDetailAV.as_view(), name="stream-detail"), path('review/', ReviewList.as_view(),name='review-list'), ] serializers.py class ReviewSerializer(serializers.Serializer): class Meta: model = Review fields = '__all__' the list of reviews return empty as attached in photo the list of reviews is empty, im new to django cant figure it out -
Log with django rest framework [closed]
I'm working on a registration system, where I need to view all the changes that have been made to this registration. If the user changes the age, I need to see the before and after. Does anyone know a django rest framework function that does this? -
Django/Celery - Filter each task result with periodic_task_name
I am quit new to Celery. Here is my code for conifguring Celery Beat. app.conf.beat_schedule = { # EMAILS 'send-feedback-mail-every-2-weeks': { 'task': 'stocks.tasks.send_ask_feedback', 'schedule': crontab(day_of_week=6), }, 'get-terminal-data-frequently': { 'task': 'stocks.tasks.get_terminal_data_func', 'schedule': crontab(minute="*"), }, # NEWS 'get-newyorktimes-api': { 'task': 'stocks.tasks.get_news_nyt', 'schedule': crontab(minute="*"), }, I am wondering how to query the associated tasks for the periodic task 'get-newyorktimes-api' in my view to pass the result of each into the context. I tried: context['celery'] = TaskResult.objects.filter(periodic_task_name='get-newyorktimes-api') It returned an empty queryset eventhough I've ran the task successfully multiple times. Where is my fault in this Task filter? -
InvalidCursorName, ProgrammingError, OperationalError related to postgres cursor while changing model
When we moved from aws to local provided we started to observe these three errors. It appears randomly while changing model. InvalidCursorName /core/family/{object_id}/change/ cursor "_django_curs_140667503112576_sync_1371" does not exist ProgrammingError /core/family/{object_id}/change/ cursor "_django_curs_140667503112576_sync_1139" already exists OperationalError /core/family/{object_id}/change/ cursor "_django_curs_140667503112576_sync_4004" does not exist This problem doesn't appear on our staging server, I can't neither reproduce it locally. Any ideas?