Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.FieldError: Cannot resolve keyword 'transactions' into field. Choices are: amount, created_at, id, received_transfers, sent_
class Transaction(models.Model): CHARGE = 1 PURCHASE = 2 TRANSFER_RECEIVED = 3 TRANSFER_SENT = 4 TRANSACTION_TYPES_CHOICES = ( (CHARGE, 'Charge'), (PURCHASE, 'Purchase'), (TRANSFER_SENT, 'Transfer sent'), (TRANSFER_RECEIVED, 'Transfer received'), ) user = models.ForeignKey(User, related_name='transactions', on_delete=models.RESTRICT) transaction_type = models.PositiveSmallIntegerField(choices=TRANSACTION_TYPES_CHOICES, default=CHARGE) amount = models.BigIntegerField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user}: {self.get_transaction_type_display()} -> {self.amount} Rial' @classmethod def get_report(cls): positive_transactions = Sum('transactions__amount', filter=Q(transactions__transaction_type__in=[cls.CHARGE, cls.TRANSFER_RECEIVED])) negative_transactions = Sum('transactions__amount', filter=Q(transactions__transaction_type__in=[cls.PURCHASE, cls.TRANSFER_SENT])) users = User.objects.all().annotate( transactions_count=Count('transactions__id'), balance=Coalesce(positive_transactions, 0) - Coalesce(negative_transactions, 0) ) return users @classmethod def get_total_balance(cls, user): query_set = cls.get_report() return query_set.aggregate(Sum('balance')) @classmethod def user_balance(cls, user): positive_transactions = Sum('amount', filter=Q( transactions__transaction_type__in=[cls.CHARGE, cls.TRANSFER_RECEIVED])) negative_transactions = Sum('amount', filter=Q( transactions__transaction_type__in=[cls.PURCHASE, cls.TRANSFER_SENT])) user_balance = user.transactions.all().aggregate( balance=Coalesce(positive_transactions, 0) - Coalesce(negative_transactions, 0)) return user_balance.get('balance', 0) class UserBalance(models.Model): user = models.ForeignKey(User, related_name='balance_records', on_delete=models.RESTRICT) balance = models.BigIntegerField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user}: {self.balance} - {self.created_at}' @classmethod def record_user_balance(cls, user): user_balance = Transaction.user_balance(user) instance = cls.objects.create(user=user, balance=user_balance) return instance @classmethod def record_all_users_balance(cls): for user in User.objects.all(): cls.record_user_balance(user) when i run UserBalance.record_all_users_balance() in console i get this error: >>>UserBalance.record_all_users_balance() Traceback (most recent call last): File "*\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() File "<input>", line 1, in <module> File "*\Python\PythonWebProjects\djangoProject01\transaction\models.py", line 76, in record_all_users_balance cls.record_user_balance(user) File "*\Python\PythonWebProjects\djangoProject01\transaction\models.py", line 68, in record_user_balance user_balance = Transaction.user_balance(user) … -
link to a different admin object in an admin template
I don't want to get my hands dirty with js. I have two models, car and model. How can I manually add a link from a car to it's model in a custom admin template? I can do: <a href="{% url 'admin:appname_carmodels_changelist' %}">access changelist</a> But how would I access the model with pk=42? I tried: <a href="{% url 'admin:appname_carmodels_change' 42 %}">access changeform</a> But I end up with a NoReverseMatch at /admin/appname/carmodel/.../change/. Is this possible? Or do I have to use some extra_context that can carry the reverse function? -
nothing gets logged at logging for a 500 error (Django)
I have copied pasted this at the settings.py (but done nothing else) I am in production and debug is set to False because I have read that his how you have to do it I have placed the log file in a place where the owner of the application can write, yet nothing is written. The error comes after I try to save a form. The form has 3 tables, address, property and pictures. address and property are saved perfectly, pictures saves nothing. The app works in my local computer perfectly. Without any reason, it fails here in production. I copy pasted this but it doesn't save anything to the file LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { # Include the default Django email handler for errors # This is what you'd get without configuring logging at all. 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR', # But the emails are plain text by default - HTML is nicer 'include_html': True, }, # Log to a text file that can be rotated by logrotate 'logfile': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': '/home/bills/alvar/myapp/dapp.log' }, }, 'loggers': { # Again, default Django configuration to email unhandled exceptions 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': … -
How can i connect my django uploads to the firebase storage?
this is my first time using firebase storage for file upload. I don't know if this is the way to structure and do it but. currently I have my product models and other related models to product as given below: #product/models.py import os from django.db import models from dripshop_apps.core.abstract_models import AbstractItem from dripshop_apps.category.models import Category from dripshop_apps.brand.models import Brand from django.contrib.contenttypes.fields import GenericRelation from django.utils import timezone from django.dispatch import receiver from django.db.models.signals import pre_save, pre_delete from dripshop_apps.core.receivers import slugify_pre_save, publish_state_pre_save, update_featured_on_publish, update_visibility_on_publish from .tasks import upload_to_firebase from .utils import product_thumbnail_upload_path, product_image_upload_path, sanitize_for_directory_name class Product(AbstractItem): price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.SET_NULL,related_name='product_category', null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='product_brand', null=True, blank=True) thumbnail = models.ImageField(upload_to=product_thumbnail_upload_path, blank=True, null=True, max_length=255) visible = models.BooleanField(default=True, editable=False) stock = models.PositiveIntegerField(default=0) objects=ProductManager() class Meta: verbose_name = "Product" verbose_name_plural = "Products" def __str__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to=product_image_upload_path, blank=True, null=True, max_length=255) updated = models.DateTimeField(auto_now=True) pre_save.connect(publish_state_pre_save, sender=Product) pre_save.connect(slugify_pre_save, sender=Product) pre_save.connect(update_featured_on_publish, sender=Product) and I am using the functions product_thumbnail_upload_path and product_image_upload_path to upload the image to the desired directory structure to the firebase with the use of a celery task which is also given below it #product/utils.py import os from django.utils import timezone … -
ValueError: Expected n_neighbors <= n_samples (mismatch between the number of neighbors specified and the number of samples in the data)
I want to implement multi-view spectral clustering. The supervised_multi_view_spectral_clustering function takes multiple views of feature matrices (X_views), a target variable (y), and clustering parameters, and performs spectral clustering on the concatenated features. The second function finds the optimal number of clusters based on silhouette scores when given a list of mixed representations. The final part of the code uses these functions to determine the optimal number of clusters and performs multi-view spectral clustering on the provided data (mixed_representation_all). By design, the input latent_representations_train_nmf is a dictionary of numpy array, whereas y is a multi-variate dataframe. The error indicates that there is a mismatch between the number of neighbors specified and the number of samples in the data. This is despite ensuring that n_neighbors is always less than or equal to the number of samples. Code: from sklearn.preprocessing import LabelEncoder from sklearn.cluster import SpectralClustering from sklearn.metrics import accuracy_score def supervised_multi_view_spectral_clustering(X_views, y, n_clusters, affinity='nearest_neighbors', max_neighbors=10): # Check if y is already encoded if isinstance(y.iloc[0, 0], str): # Assuming the first element of the dataframe is a string if not encoded # Encode labels if they are not numerical label_encoder = LabelEncoder() y_encoded = label_encoder.fit_transform(y) else: # Use the provided encoded y directly … -
Django - Oracle Cloud Bucket integration with django-storages
I have configured the django-storages to point to OCI bucket. Below is the configuration: AWS_S3_ACCESS_KEY_ID = env('AWS_BUCKET_KEY') AWS_SECRET_ACCESS_KEY = env('AWS_BUCKET_SECRET') AWS_BUCKET_NAMESPACE = env('AWS_BUCKET_NAMESPACE') AWS_STORAGE_BUCKET_NAME = env('AWS_BUCKET_NAME') AWS_S3_BUCKET_REGION = env('AWS_S3_BUCKET_REGION') AWS_S3_ENDPOINT_URL = f'https://{AWS_BUCKET_NAMESPACE}.compat.objectstorage. {AWS_S3_BUCKET_REGION}.oraclecloud.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = f'{AWS_S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}' AWS_DEFAULT_ACL = 'public-read' STATICFILES_STORAGE = 'custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' # Use AWS_S3_ENDPOINT_URL here if you haven't enabled the CDN and got a custom domain. STATIC_URL = '{}/{}/'.format(AWS_LOCATION, 'static') STATIC_ROOT = 'var/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] MEDIA_URL = '{}/{}/'.format(AWS_LOCATION, 'media') MEDIA_ROOT = 'media/' and this is the custom storage config from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = 'static' class MediaStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = 'media' All my static files are being served and no issues, but the application doesn't recognize the style files at all. Also when I try to upload a new file, it gives the following error: botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the PutObject operation: The secret key required to complete authentication could not be found. The region must be specified if this is not the home region for the tenancy. What could be the issue? -
Why when i use 0 as parameter is not found, but is completely fine when the parameter is 1, 2, 3, ... in Django-Redirect
articles = { 'sports': 'Sports news', 'music': 'Music news', 'travel': 'Travel news', 'tech': 'Tech news', } def num_page_view(request, num_page): topic_list = list(articles.keys()) print(topic_list) topic = topic_list[num_page] return HttpResponseRedirect(topic) I'm currently learning dynamic url. Here's when i use /0 it is shown not found Error input 0 But, when i use /1 it's completely fine, it redirected into "music" page. Please Help! I tried print the topic_list, and it is shown like this: ['sports', 'music', 'travel', 'tech'] when i print topic_list[0] it is shown as "sport" but i dont know, i cant do redirect. -
Django can't connect to Postgresql
I'm working on my first ever Django project. I've Create a Postgresql Database on a host(which my project is already on that host) which is accessible on public network too .I can connect to the database on my local computer so the database is created. But in production I'm trying to migrate to the database but I got the FATAL: database "postgre" does no t exist I tried to connect it on my local with public network host and port but still got the same error. here is my db code : DATABASES = { 'default': { 'ENGINE': config('ENGINGE', default='django.db.backends.postgresql'), 'NAME': config('NAME', default='postgre'), 'USER': config('USER', default='postgre'), 'PASSWORD': config('PASSWORD', default='postgre'), 'HOST': config('HOST', default='postgre'), 'PORT': config('PORT', default='5432'), } } I'm passing the variables with .env. Also I tried to connect with dj-database-url like this : DATABASES = DATABASES['default'] = dj_database_url.config('DATABASE_URL') And in both cases I've got the same error. Does anyone got any idea what's wrong here? -
How to resolve error: collectstatic - Could not find backend 'storages.custom_azure.AzureStaticStorage'
I have a django app and I have installed the module: django-storages[azure] with the command: pipenv install django-storages[azure] And now I try to run the collectstatic command. But if I enter the command: python manage.py collectstatic I get this error: Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure' So my pipfile looks: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" django-storages = {extras = ["azure"], version = "*"} [dev-packages] [requires] python_version = "3.10" settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "uploader", "storages" ] STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'uploader.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'storages.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "name" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' and I have a file custom.azure.py in the app uploader: from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = ''name' # Must be replaced by your <storage_account_key> account_key= 'key' azure_container = 'media' expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = 'name' account_key = 'key' azure_container = 'static' expiration_secs = None Question: how to resolve the error: Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure' -
How to add django-filter Rangefilter class?
I am try to add bootstrap class in to price range filter but i can't, import django_filters from panel.models import Product, Category,Size,TopNote, BaseNote, MidNote from django import forms class ProductFilter(django_filters.FilterSet): price = django_filters.RangeFilter( # widget = forms.TextInput(attrs={'class':'form-control'}) ) class Meta: model = Product fields =['name', 'category_id', 'price', 'top_notes', 'base_notes', 'category_id', 'size'] when I am add class using widget = forms.TextInput(attrs={'class':'form-control'}) range filter convert into 1 textbox i dont't know why ???/ -
How to properly aggregate Decimal values in a django app: 'decimal.Decimal' object has no attribute 'aggregate'
I'm in a django-tables2 Table, trying to compute the sum of a column (based on a MoneyField (django-money) in the model, see hereunder): import django_tables2 as table class PriceAmountCol(table.Column): # print(f"Total price is: {record.price.amount}") # print(f"Type of total price is: {type(record.price.amount)}") def render(self, value, bound_column, record): total_price = record.price.amount.aggregate( total=Sum("price") ) Class MyTable(table.Table): # Fields price = PriceAmountCol( verbose_name=_("Price [EUR]"), ) #... But this error is raised: File "/code/djapp/apps/myapp/tables.py", line 192, in render total_price = record.price.amount.aggregate( AttributeError: 'decimal.Decimal' object has no attribute 'aggregate' If not commented out, the two print instructions give: Total price is: 112.80 Type of total price is: <class 'decimal.Decimal'> How could I properly aggregate price values (Decimal) in my current table column? The field in the model is as follow: price = MoneyField( default=0.0, decimal_places=2, max_digits=12, default_currency="EUR", verbose_name=_("Price [EUR]"), ) Version info django 4.2.8 djmoney 3.4.1 django-tables2 2.7.0 python 3.10.6 Related information https://django-tables2.readthedocs.io/en/latest/pages/column-headers-and-footers.html#adding-column-footers Django-tables2 column total Django-tables2 footer sum of computed column values -
taking picture from the django admin panel to a website with zip
There will be a field in the Django admin panel, I will select zip from this field. there will be about 60 to 70 images in the zip file. I want to be able to display these images as slides on my website, but I haven't found a solution. I've tried multiple solutions, but none of them have been successful, so I can't share the codes. -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/login/login/
I stored the user registration details in the database, but when I attempt to log in with the entered data, it is not working; instead, it displays the following message. enter image description here here is urls.py urlpatterns=[ path('',views.index,name='index'), #path('counter',views.counter,name='counter'), path('register/',views.register,name='register'), path('login/',views.login,name='login.html'), path('logout/',views.logout,name='logout.html'), path('post/<str:pk>',views.post,name='post.html') #path('',views.display_records,name='table.html'), ] here is views.py def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('/') else: messages.info(request,'Invalid User Login') return redirect('login') else: return render(request,'login.html') here is login.html <h1>Login Now</h1> <style> h3{ color: red; } </style> {% for message in messages %} <h3>{{message}}</h3> {% endfor %} <form action="login/" method='POST'> {% csrf_token %} <p>Username</p> <input type="text" name="username" placeholder="username"/> <p>Password</p> <input type="password" name="password" placeholder="password"/> <br> <br> <input type="submit"/> </form> After completion of registration.it is not redirecting to login page instead showing this. type here enter image description here -
Sending Django celery task to AWS GPU
I have a question related to designing the backend and frontend of an application that I'm currently working on. Although this might be more suited to AWS, I am asking here first because the community is great and very helpful. I have developed an application that works well locally, but now I want to move it to the cloud. I'm facing some issues while doing so. The application is standalone and requires GPU for the celery task. The task is initiated when the user uploads an image, and once it's done, everything is saved and the GPU machine is turned off. However, the application needs to run continuously without requiring the GPU. The user should be able to login and see the dashboard and upload job process data anytime. How can I achieve this? Should I separate my application into two parts? I have researched and found that many people suggest using AWS API, but before doing so, I need to know how to make a setup for it. Has anyone done this combination of Django and AWS before? If not, what are you using for your ML inferences in production? My appliction is working well in laptop. how to … -
Django OSError: [Errno 22] Invalid argument in \\.venv\\Lib\\site-packages\\admin_tools
I have cloned a Django project from Gitlab repository and I get this error when I try to run the server. OSError: [Errno 22] Invalid argument: 'C:\\Users\\irina\\project\\.venv\\Lib\\site-packages\\admin_tools\\theming\\templates\\admin:admin\\base.html' Dependencies are installed via poetry. I think the error is due to the encoding. How can this be fixed? I'm working on Windows 11. -
Django Celery not able to fetch data from particular DB schema
We are facing the issue fetching the data from particular schema's table which is available and the data fetching issue occurs intermediately after few hours of restart of supervisorctl where celery worker is defined. Below is the code mentioned: with schema_context("public"): try: client = Client.objects.get(subdomain=hostname) except ObjectDoesNotExist: client = Client.objects.using("paid").get(subdomain=hostname) Also i have set the connection to particular schema using schema_context function. We have rabbitmq as middleware and we have 3 different queues set and this problem occurs in all queues. we are using libraries celery==4.4.7 django-celery==3.3.0 -
Why can't we view Google Drive public file for longer without getting 403 Forbidden Error?
I am working on a Django project where I allow user to upload their images on google drive with public access and then I display all the uploaded images user-wise. Everything done, I can create folder, and then uploading file in it and getting the file-id. But on viewing that image, I have stucked badly. I have used so many ways not to get a 403 Forbidden Error but still no success! https://drive.google.com/file/d/{file-id}/preview https://drive.google.com/uc?id={file-id}&export=download https://drive.google.com/uc?export=view&id={file-id} File (which is just an image) I can view only few times but then I starts getting this annoying 403 forbidden error. I am really frustrated with this error, please help. -
how to solve 'Error Dict' object is not callable error [closed]
views.py from django.contrib import messages from django.shortcuts import render, redirect from clgapp.forms import StudentForm def student_form(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() messages.success(request, "order confirmed") return render(request,'student_form.html',{'form': form}) else: form.errors() else: form = StudentForm() return render(request, 'student_form.html', {'form': form})` -
django.server logs are not shown in CloudWatch - Using Zappa
My django application is running on AWS Lambda with zappa. I recently added the following to configure logs. LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, "filter_user_id": {"()": "<path_to>.UserIdFilter"}, }, "formatters": { "django.server": { "format": "[%(asctime)s] %(message)s user_id:%(user_id)s ", } }, "handlers": { "console": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler", }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server", }, }, "loggers": { "django": { "handlers": ["console"], "level": "INFO", }, "django.server": { "handlers": ["django.server"], "filters": ["filter_user_id"], "level": "INFO", "propagate": False, }, }, } This is working well when I run this on docker / local server. But when I deployed this to AWS Lambda it is not showing the corresponding logs in the Cloudwatch. Could anyone help? Thanks in advance. -
Creating and Sending PDF file directly to printer without print preview in react and django?
here is any chance to Creat Pdf file and Send PDF file directly to printer without open print preview?? currently! i am able to create pdf and save it in my local.And im also able to print once pdf file is created by opening pdf. Here what im looking for: Generate pdf first and save it to my local and it should be print to my printer once pdf file is created without opening print preview window. what i tried: currently i am able to generate pdf and print them as well by open pdf file form my local. here is my sample code for pdf functionality: model.py: class OrderTransactionPDF(models.Model): pdf_file = models.FileField(blank=True, null=True, validators=[FileExtensionValidator( allowed_extensions=['pdf'])]) transaction_time = models.DateTimeField(default=datetime.datetime.utcnow()) view.py: @csrf_exempt def search_pdf(request): if request.method == "GET": from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') pdf_url_list = [] from_date = datetime.strptime(from_date, '%Y-%m-%d') to_date = datetime.strptime(to_date, '%Y-%m-%d') from_date = datetime.combine(from_date.date(), time(0, 0, 0, tzinfo=pytz.timezone('UTC'))) to_date = datetime.combine(to_date.date(), time(23, 59, 59, tzinfo=pytz.timezone('UTC'))) order_transaction_pdfs = OrderTransactionPDF.objects.filter( transaction_time__range=[from_date, to_date] ).order_by('-transaction_time') for pdf in order_transaction_pdfs: pdf_url_list.append({ 'pdf_url': pdf.pdf_file.url, 'transaction_time': pdf.transaction_time }) return JsonResponse({'pdf_url_list': pdf_url_list}, safe=False) urls.py: path('generate_pdf', generate_pdf), js code: const handleViewOrder = async () => { try { const response = await fetch('/generate_pdf', { method: 'POST', … -
Is there a way to add formset in django-admin without using inline?
I have a model called Employee which is defined as follows: class Employee(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField("Name", max_length=255) address = models.CharField("Address", max_length=255) department = models.ForeignKey(Department, on_delete=models.SET_NULL) team = models.ForeignKey(Team, on_delete=models.SET_NULL) position = models.ForeignKey(Position, on_delete=models.SET_NULL) Is there a way to add multiple name and address of employee for the same department, team and position in django-admin form? I want something like formset including fields name and address for the model Employee where you can enter the department, team and postion and just add the formsets multiple times like how you would do for inlines. I have not tried anything as of yet. -
Duplicate entries in admin view due to M2M field
class User(AbstractBaseUser): organizations = models.ManyToManyField(Organization) facilities = models.ManyToManyField(Facility) class Organization(models.Model): ..fields here class Facility(models.Model): ..fields here Whenever I enter multiple entries for organization the user value is duplicated that many times in the admin view list, but not for facility. -
Django forms not rendering CharFields
In my Django form, only CharFields are exclusively not showing up. Other fields work just fine (e.g. the EmailField and a TurnstileField using django-turnstile). I cannot figure out why. I followed the Django docs and tried to build a form. Code is as follows: auth.html {% block body %} <form action="https://artimaths.com/auth/{{ action }}/" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py from django.core.exceptions import ValidationError from django.http import HttpResponse, HttpResponseRedirect from django.core.mail import send_mail from django.template import loader from .models import Member from .forms import SignupForm, LoginForm from modules import context import hashlib import re def signage(request, action): t = loader.get_template("auth.html") if action != "register" and action != "login" and action != "logout": return HttpResponse(STATUS_DICT[str(400)] + str(400)) if action == "register": req_context["form"] = SignupForm req_context["form_class"] = SignupForm elif action == "login": req_context["form"] = LoginForm req_context["form_class"] = LoginForm if req_context["status"] is not 200: return HttpResponse(STATUS_DICT[str(req_context["status"]) + req_context["status"]]) return HttpResponse(t.render(req_context, request)) forms.py from django import forms from turnstile.fields import TurnstileField from .models import Member class SignupForm(forms.Form): username = forms.CharField(label="Username"), password = forms.CharField(label="Password"), email = forms.EmailField(label="Email") terms = forms.BooleanField(label="I agree with the Terms of Service and Privacy Policy of Artimaths") captcha = TurnstileField(theme="dark", size="compact") class Meta: … -
How to make multiple post requests with one button handler in React?
I am trying to generated PDF for my application.Pdf functionality is working well.I have two PDF functionality for post request which is seperate right now.Those two PDF post functionality is setting up two indivisual button handler. Ex1: const handleViewOrder = async () => { const response = await fetch('/generate_pdf', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); } Ex2: const handleProductSellsPdf = async () => { const response = await fetch('/**generate_item_pdf**', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); what im trying now that,combine those Ex1 and Ex2 in one button handler and generate pdf once i click button. backend code is working fine. problem is that i dont know how to do it in in react/java script. any suggestion please this is my code of pdf generate functionality for diffrent button handler in react : const handleViewOrder = async () => { try { const response = await fetch('/generate_pdf', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); const responseData = await response.json(); const pdfURL = responseData.pdf_url; localStorage.setItem("pdf_url",pdfURL) window.open(pdfURL, '_blank'); if (!response.ok) { throw new Error('Network response was not ok'); } } catch (error) { console.error('Error fetching data:', error); } }; const handleProductSellsPdf = async () => … -
How to set a (Django) celery beat cron schedule from string value
I am using Django with celery beat. I would like to configure the cron schedule via env var (string value of the cron). We are currently setting the cron schedule like this, using celery.schedules.crontab: CELERY_BEAT_SCHEDULE = { "task_name": { "task": "app.tasks.task_function", "schedule": crontab(minute=0, hour='1,3,5,13,15,17,19,21,23'), }, } I would like to configure the schedule by passing a crontab in string format, like this: CELERY_BEAT_SCHEDULE = { "task_name": { "task": "app.tasks.task_function", "schedule": '0 15 10 ? * *', }, } However, I cannot find any documentation for how I can do this. The naive attempt above does not work. I could parse the cron string into minute/hour/day etc values, and then pass them into crontab with the relevant kwargs, but that feels quite messy. It seems there should be an elegant way to do this.