Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading a file from one django api to another on aws environment
Im developing my first microservice application, i created an api that work as a gateway, where i redirect the requests to another apis (inside aws private subnets). Json requests is working normaly, but multipart/form-data is not, the file reaches the gateway correctly,.gateway img, but in the other api, the files reaches there like this bug. It seems that that image is getting converted to binary when it reaches to the other api. This is the code in the gateway. class ProvidersMultipartGatewayView(APIView): url = os.environ.get("PROVIDERS_SYSTEM_URL") parser_classes = [MultiPartParser, FormParser, JSONParser] def post(self, request): token = request.META.get('HTTP_AUTHORIZATION') headers={'Authorization': f'{token}'} url_path = request.get_full_path() url_full = f"{self.url}{url_path}" response = requests.post(url_full, data=request.data, headers=headers, allow_redirects=True) status_code = response.status_code if status_code == 200 or status_code == 201 or status_code == 208: return Response(response.json(),status=status.HTTP_200_OK) return Response(status=status_code) And here, the code of the api that should save de file. class CompletedPaymentsView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser, JSONParser] def post(self, request): serializers = CompletedPaymentsSerializers(data=request.data) if not serializers.is_valid(): return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) if Handle_Board_Permissions(request, request.data["user_id"]): payment = CompletedPayments.objects.create(**serializers.data) payment.payment_file = request.data["payment_file"] payment.save() serializers = CompletedPaymentsSerializers(payment) return Response(serializers.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_401_UNAUTHORIZED) If i make a request directly to the providers api, it works, but if i make a … -
Converting SQL query to Django ORM query
I'm trying to convert the following from a raw SQL query to use Django's ORM: SELECT count(size_id) AS id, count(size_id) as count, name, size_id, product.product_id FROM product JOIN product_size size ON product.size_id = size.id WHERE product_id = '123' AND product.id NOT IN ( SELECT item_id FROM order JOIN product i ON order.item_id = i.id WHERE i.product_id = '123' AND (startdate - interval '10 days', enddate + interval '10 days') OVERLAPS ('01-01-2023', '02-01-2023') ) GROUP BY size_id, name, product.product_id ORDER BY size_id ASC I know I can filter() on startdate__overlap or a DateTimeTZRange and I can also filter on a sub-query, but I'm really struggling to put it all together! Essentially what the query does is look for availability by excluding the results in the sub-query. Can anyone help? -
How to pass use sync_to_async with a chain of methods
I have a case like the following: async def handler(self): await sync_to_async(Stock.objects.filter)(id__in=product_stock).update(is_filled=False) Where I am trying to pass the product_stock to the filter method then call the update on the filtered queryset. I understand that I can wrap the logic in another method and just pass it the arg as in the following: @classmethod def update_stocks( cls, product_stock: List[uuid.UUID] ) -> None: """Update stocks for order products.""" cls.objects.filter(id__in=product_stock).update(is_filled=False) async def handler(self): await sync_to_async(Stock.update_stocks)(product_stock=product_stock) But is is possible to do it all as in my attempt above which doesn't work of course since the result is a courotine and django queryset? I want to avoid having to use another method just for this if it is possible. Thank you. -
Trouble with form validation on multi-form view in django, using form within a table
As the title says, I'm running into an issue with form validation. The table and form both seem to 'know' the correct values, but when it gets to the view, the validation fails. I have Jobs, Costs, and Vendors, all interrelated. The form I'm trying to validate is part of a table of Costs that pertain to a particular Job, and the field I'm trying to update is the Vendor field, via a dropdown menu, per row of the Costs table, with a single Update button that submits all forms at once via Javascript. Through a ton of troubleshooting via print statements, the table and form both seem to be able to print the correct cost and vendors, but when validating, I keep being told that the 'cost' field is a required field, so I guess it's not receiving the Cost object from the form. Been stuck on this for far too long, and I would appreciate some help. Here's the view: class CostCreateView(SuccessMessageMixin, SingleTableMixin, CreateView): model = Cost fields = ['vendor','description','amount','currency','invoice_status','notes'] template_name = "main_app/cost_form.html" table_class = CostTable simple_add_vendor_form = AddVendorToCostForm cost_form = CostForm update_vendor_form = UpdateVendorForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.object=None currentJob = Job.objects.get(pk=self.kwargs['pk']) context['currentJob'] = currentJob … -
Django queryset returns an empty result while i have data in my database
I'm new in django framework. I was using a database with postgres and implemented schemas in my tables. Now I have a problem regarding with getting my data from django. Here is what I've tried.. I have a model in my accounts_app class ProfileBasicInfo(BaseModel, SoftDeleteModel): # One to one with CustomUserModel user = models.ForeignKey(CustomUserModel, on_delete=models.CASCADE) sex = models.CharField(max_length=4) birthdate = models.DateField() civilstatus = models.CharField(max_length=100) height_meters = models.FloatField(null=True, blank=True) weight_kg = models.FloatField(null=True, blank=True) bloodtype = models.CharField(max_length=4) photo_path = models.ImageField(max_length=600, blank=True, null=True) class Meta: db_table = 'accounts_app\".\"profile_basicinfo' verbose_name = 'profile_basicinfo' now I tried to import it in my selectors.py and still gives me a null queryset. Here is how I did it. from accounts_app.models import ProfileBasicInfo def get_user(user): data = object() querysetProfile = ProfileBasicInfo.objects.all() profile_data = list(querysetProfile.values()) print(profile_data) The print gives me an empty queryset but I have already added a data in my database. -
ModuleNotFoundError: No module named 'main_app/urls', but it does exist
Error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/taylordarneille/Code/Django/newenv/clientDB2/clientDB2/urls.py", line 20, in <module> path('', include('main_app/urls')), File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in … -
Django - how to create related models in new migrations for existing model objects
I'm adding couple of new models which have foreign key one-to-one relation to an existing model (existing model has thousands of objects already in database). The new models have default values for every field other than the foreign key. Example as below, class OldModel(models.Model): field1 = models.CharField(max_length=30) # As part of new migration class NewModel(models.Model): rel_field=models.OneToOneField(OldModel) value1=models.IntegerField(default=10) value2=models.IntegerField(default=10) So now 'OldModel' has upwards of 6000 objects in the database already, and I am adding the NewModel as part of a new migration. Is there any way that Django will autocreate the objects for NewModel for every existing object of OldModel? I have already written a receiver function using signals to autocreate the NewModel objects for future like below, @receiver(post_save,sender=OldModel) def create_new_rel(sender,instance,created,**kwargs): if created: NewModel.objects.create(rel_field=instance) I know we can write a script to query the old objects and create new one for each but just wondering if there is a proper "django way" to do this automatically? -
How to add a confirmation field in django form
I have an User abstract user model with some fields including mnemonic which is a CharField and an image that's an ImageField. I want to be able to use the mnemonic as a confirmation field to change the image in a form but I can't get the old mnemonic in the clean() method and so I get name 'user' is not defined. class User(AbstractUser): mnemonic = models.CharField(max_length=25, blank=True) image = models.ImageField(null=True, default='default.jpg', upload_to='pictures') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['image', 'mnemonic'] def clean(self): super(UserUpdateForm, self).clean() mnemonic = self.cleaned_data.get('mnemonic') if mnemonic != user.mnemonic: # name 'user' is not defined, line where I need to get the old mnemonic self._errors['mnemonic'] = self.error_class([ 'The mnemonic is wrong!']) return self.cleaned_data <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <p class="article-title"><b>Profile Info</b></p> {{ profile_form }} <p class="article-title"><b>Site settings</b></p> {{ site_form }} <div> <button type="submit">Update</button> </div> </form> -
Object's unique sequencial index for each user - Django models
I have a table for users and another for what I call 'documents' in my database (I use postgresql). That last one has a 'user/author' column as a foreign key. How can I set a sequential index column for each user/author? Here's what's on my mind: user1 fills the table with 10 rows, then that column varies from 1 up to 10. user2 fills the same table with 5 more items. For those user2's rows that same column varies from 1 up to 5. If any row of a user gets deleted, that column (for that user's data) gets "re-indexed", i.e., if user2 deletes the 3rd entry, the former 4th gets re-indexed to 3, and the former 5th to 4. How I came up with this problem? I want to use that column as an index in the url's model-view. I could use a uuid key instead, but I find, for example, myapp.com/edit/1,myapp.com/edit/2 and so on more organized. Currently I perform the above described actions at view level: every time a row gets deleted all rows for that user gets re-indexed; every time a new row gets added, it's index is set. The problem is that I feel that this … -
How the calculate how many days lef to due date in a query?
I have a model that has due_date field and I want to create a query that annotates overdue value that counts how many days are left until due_date. but I can't implement it in my code I'm getting this error: Case() got an unexpected keyword argument 'default' and if I remove the default I get: TypeError: QuerySet.annotate() received non-expression(s): PS: Some of the objects have null due_date query_list = file.qs.annotate(overdue=Case( When(due_date__gt=timezone.now().date(), then=Value((F('due_date') - timezone.now().date()))), When(due_date__isnull=True, then=Value(None)), default=Value(0), output_field=DurationField())).values_list('overdue', ...) -
How can i stop making authentication requests per second?
I'm making a web app using django for backend and react for frontend. The proble is that when a I login in the app and enter with the user, the app is making a lot of authentication request per second and don't understand why. enter image description here enter image description here here's the function that use the auth/me url: enter image description here if u need more parts of the fronted or backend for trying to help me, just ask. I just wanna avoid making a lot of requests by seconds, but idk how and where's the loop :( -
How to check if a recurring periodicTask executed in a particular day in celery?
I am creating a project using Django, celery, celery beat, etc. I made some recurring periodic tasks that will run daily at a given crontab schedule. Now I want to know if the recurring task is executed successfully on a particular day. How can I query it? Is there any connection between PeriodicTask and TaskResult? -
How can i increase the width of a drop-down field in a django form?
I want to increase width of dropdown field in Django form, I tried both inline CSS as well as widgets, below is code I have tried index.html {% extends "base_generic.html" %} {% block content %} <form action = "" method = "post"> {% csrf_token %} **<center>Product: <h6 style="width: 350px;">{{ form.product }}</h6></center>** <br> <center>Rules: {{ form.rule }}</center> <input type="submit" value=Compute> </form> {% endblock %} forms.py from django import forms PRODUCTS = ( ('hp','HP'), ('wipro', 'WIPRO'), ) class InputForm(forms.Form): class Meta: **widgets = {'product': forms.Select(attrs={'style': 'width:200px'})}** product = forms.ChoiceField(choices=PRODUCTS) rule = forms.CharField(widget= forms.Textarea, label="Rules") How can I achieve this? -
Is there any bug or issues in Django 4.1.7 for static files?
while trying to load static files (mostly images) from static directory but I'm getting 404 error. I have created directory named 'static' in root directory and put all my images in 'shouldknow' directory within 'static' directory like '/static/shouldknow/logo.svg'. in my settings.py -- STATIC_URL = 'static/' and DEBUG = True 'django.contrib.staticfiles' is already placed in settings.py under apps. I'm using template inheritence and in my index.html template, i put these lines of code to load static files: {% load static %} <a href=""> <img src="{% static 'shouldknow/logo.svg' %}" alt="..." width="30" height="24"> </a> After doing this, still images are not loading from the static directory. Error shown by the server is -- 'GET /static/shouldknow/logo.svg HTTP/1.1" 404 1816' -
docker python can't find address postgres
I run a container with postgresql and after that I run a container with python (Django). I am trying to connect to the database and in some cases I get an error. This error happen after deleting compose project and trying to create that in 50% cases.If restart the backend container separately, then everything works fine. This is my first time working with a docker, I hope for your help and possible django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "postgres" (192.168.128.2) and accepting TCP/IP connections on port 5432? -
Django internationalisation and digits behaviour
I have a website in English, Spanish, German and French. One of the tables has a meter bar like: <meter value="{{fav.value}}" min="0" max="10"></meter> I found the meter bar only works in the English version, particularly, the meter goes from 0 to 10 with 2 decimals accuracy. If I override the value in view.py with an integer value (e.g. fav.value = 2), it works in all languages. If I override the value with a float (e.g. fav.value = 2.5), it would only show the green meter fill in the English version. Anyone has any idea what why this may be happening? -
Sidebar Menu is not displayed in custom page which is extending admin/base.html
I Have created a custom page which I want to display in Django Admin Panel. I am using jazzmin admin template for my django project. Problem: I am not getting the sidebar menu only option I can see is Dashboard. Why is this happening and how do I get full sidebar menu which I am getting for all the page for the models registered in admin.py My Views.py from confluent_kafka.admin import AdminClient, NewTopic from base.constants import KAFKA_CONFIG from django.views.generic import TemplateView # Create your views here. KAFKA_EXCLUDE_TOPICS = {'__consumer_offsets': True} class QueueOperationsView(TemplateView): template_name = 'dataprocessing/queue_management/queue.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) admin_client = AdminClient(KAFKA_CONFIG) topic_metadata = admin_client.list_topics() has_purge_permissions = self.request.user.has_perm('masters.purge_dataprocessingqueuemaster') # add your context data here context['topics'] = [i for i in topic_metadata.topics if i not in KAFKA_EXCLUDE_TOPICS] context['has_purge_permissions'] = has_purge_permissions return context My Urls.py from basics.admin import wrap_admin_view from masters.views import QueueOperationsView from django.conf.urls import url url(r'^admin/queue-management/$', wrap_admin_view(QueueOperationsView.as_view()), name="queue_operations_view"), wrap_admin_view(): def wrap_admin_view(view, cacheable=False): """ Use this to wrap view functions used in admin dashboard Note: Only the views that require a admin login """ from django.contrib import admin def wrapper(*args, **kwargs): return admin.site.admin_view(view, cacheable)(*args, **kwargs) wrapper.admin_site = admin.site return update_wrapper(wrapper, view) Template: {% extends 'admin/base.html'%} {% load static %} … -
How to configure VSCode + Django + WindiCSS
I installed the 'WindiCSS IntelliSense' extension for VSCode and I don't know what to do next. To make it work I open each .html file separately, run the 'Compile CSS [Interpretation mode]' command, rename the output file to match with the .html file I compiled it for and then manually move it to my static directory + the extension doesn't read the windi.config.js file. How to make it compile a single .css file for all .html files in the template directory and automatically move it to the static directory? -
Python: Return pre stored json file in response in Django Rest Framework
I want to write an API, which on a GET call , returns pre-stored simple json file. This file should be pre-stored in file system. How to do that? register is app name. static is folder inside register. There I keep stations.json file. register/static/stations.json. Content of this "stations.json" file should be returned in response. settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'register/static/') ] STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') views.py: from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User from .serializers import RegisterSerializer from rest_framework import generics from django.http import JsonResponse from django.conf import settings import json class RegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = RegisterSerializer def get_stations(request): with open(settings.STATICFILES_DIRS[0] + '/stations.json', 'r') as f: data = json.load(f) return JsonResponse(data) urls.py: from django.urls import path from register.views import RegisterView from . import views urlpatterns = [ path('register/', RegisterView.as_view(), name='auth_register'), path('stations/', views.get_stations, name='get_stations'), ] setup/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('api/', include('register.urls')), ] When I hit GET request from Postman: "http://127.0.0.1:8000/api/stations/", I get error: 500 Internal server error. TypeError at /api/stations/ -
Django: How to calculate the uptime and downtime of a shop in the last hour, day, and week based on its business hours and status updates?
I have a Shop model that represents a retail store. Each store has ShopHour objects that define its business hours for each day of the week. The ShopHour model has the following fields: class ShopHour(models.Model): DAY_CHOICES = [ (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday'), ] store = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name='business_hours' ) day_of_week = models.IntegerField(choices=DAY_CHOICES) start_time_local = models.TimeField() end_time_local = models.TimeField() I also have a Status model that records the status of each shop at a given time. The Status model has the following fields: class Status(models.Model): STATUS_CHOICES = [ ('active', 'Active'), ('inactive', 'Inactive'), ] store = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name='updates' ) timestamp_utc = models.DateTimeField() status = models.CharField(max_length=10, choices=STATUS_CHOICES) I would like to create a hourly report Report for each Shop that shows its uptime and downtime in the last hour, day, and week, based on its business hours and status updates. Additionally if a shop has missing business hours, it's assumed to be open for 24*7. Specifically, I would like to know: How much time the shop was active and inactive in the last hour, day, and week How can I calculate this information efficiently and accurately? I would appreciate any … -
A user mapped to verifyPhone and VerifyEmail via OneToOneField using fastapi tortoise-orm. but if I run the server. It'll pop error show in the pix
main fastapi The error it displays I tried to Map User to its EmailVerify and PhoneVerify using OneToOneField as shown in here and also this is the modelenter image description here -
Clarification Regarding Pip Package Sub Dependencies Getting Upgraded
I have a doubt regarding pip installation. Suppose i have a requirements.txt file in python project as below Django==4.1.7 While downloading Django it also downloads sub dependencies. └─$ pip show Django Name: Django Version: 4.1.7 Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. Home-page: https://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD-3-Clause Location: /home/sunil/Desktop/pypro/venv/lib/python3.10/site-packages Requires: asgiref, sqlparse Required-by: From the above output we can notice that asgiref, sqlparse sub dependencies also got installed. Below is the output of pip freeze └─$ pip freeze asgiref==3.6.0 Django==4.1.7 sqlparse==0.4.3 since asgiref, sqlparse aren't pinned in requirements.txt, In future if i reinstall these packages from above mentioned requirements.txt is it possible that asgiref, sqlparse get upgraded to different versions ?? Or these sub dependency packages has their versions pinned with Django itself ?? Any docs or pointers could be helpful :) -
How to sort variables in order from highest to lowest in Python Django
So I do have variable that I need to sort and I have some difficulties to solve that: Problem is that I have {{new.likes.count}} that gave me just: 1 4 5 8 .... views.py from "post app" def news(request): queryset = News.objects.order_by('-created_date') tags = News_Tag.objects.order_by('-created_date') page = request.GET.get('page', 1) paginator = Paginator(queryset, 9) try: news = paginator.page(page) except EmptyPage: news = paginator.page(1) except PageNotAnInteger: news = paginator.page(1) return redirect('news') context = { "news": news, "tags": tags, "paginator": paginator } return render(request, 'news.html', context) def like_news(request, pk): context = {} new = get_object_or_404(News, pk=pk) if request.user in new.likes.all(): new.likes.remove(request.user) context['liked'] = False context['like_count'] = new.likes.all().count() else: new.likes.add(request.user) context['liked'] = True context['like_count'] = new.likes.all().count() return JsonResponse(context, safe=False) models.py class News(models.Model): user = models.ForeignKey( User, related_name='user_news', on_delete=models.CASCADE ) category = models.ForeignKey( News_Category, related_name='category_news', on_delete=models.CASCADE ) tags = models.ManyToManyField( News_Tag, related_name='tag_news', blank=True ) likes = models.ManyToManyField( User, related_name='news_user_likes', blank=True ) title = models.CharField( max_length=250 ) slug = models.SlugField(null=True, blank=True) banner = models.ImageField(upload_to='news_banners') description = RichTextField() created_date = models.DateField(auto_now_add=True) def __str__(self) -> str: return self.title def save(self, *args, **kwargs): updating = self.pk is not None if updating: self.slug = generate_unique_slug(self, self.title, update=True) super().save(*args, **kwargs) else: self.slug = generate_unique_slug(self, self.title) super().save(*args, **kwargs) {{new.likes.count}} variable has 4 … -
Django signal was not triggered after Apscheduler job updates Model record
I have an Apscheduler job that updates the active field in my subscription model and sets it to False. I created a post_save signal that should be triggered when the subscription model is updated, but it doesn't work. Here's my code. --job.py-- from django.conf import settings from subscription.models import AccountSubscription from django.utils import timezone def schedule_api(): try: data = {'is_active':False} AccountSubscription.objects.filter(expiry_date__lte=timezone.now(), is_active=True).update(**data) except Exception: pass -- signals.py-- @receiver(post_save, sender=AccountSubscription) def post_save_user_subscription_expired(sender, instance, created, **kwargs): """Notifies users of subscription expiration.""" try: if not created: if not instance.is_active: print("Notified users") except Exception as ex: print(ex) # context = { # 'status': 'error', # 'message': 'A subscription expiration notification error has occurred.' # } # raise exceptions.ParseError(context) Please is there something that I am doing wrongly? -
I can't display my data on the client side of the screen
I'm working on a simple Full CRUD app using react and Django. I'm having a problem seeing my data on the client side. const URL = 'http://localhost:8000/blog/'; const Main = () => { const [blogs, setBlogs] = useState(null); // Index const getBlogs = async () => { const data = await fetch(URL).then((res) => res.json()); setBlogs(data); }; // Create const createBlogs = async (blog) => { await fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }); getBlogs(); } // Update const updateBlogs = async (blog, id) => { await fetch(URL + id , { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }); getBlogs(); } // Delete const deleteBlogs = async (id) => { await fetch(URL + id , { method: 'DELETE' }); getBlogs(); } useEffect(() => { getBlogs(); }, []); return ( <main> <Routes> <Route path='/' element={<Index blogs={blogs} createBlogs={createBlogs} />} /> <Route path='/blog/:id' element={<Show blogs={blogs} />} updateBlogs={updateBlogs} deleteBlogs={deleteBlogs} /> </Routes> </main> ); } export default Main; I checked everthing is working on postman and it is working. I can create,edit,update and delete on postman.