Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what is different between wsgi.py and asgi.py file, and why we not use manage.py file in deployment
what is different between wsgi.py and asgi.py file, and why we not use manage.py file in deployment I expected, a reason, why we not used manage.py file in devlopyment,if we deploy a web-application through manage.py then what is sceurity threat -
checkbox getlist return max two values from request GET in django
I have a problem with the getlist function in Django. Specifically, I have several checkboxes listed using a for loop. The form is written in HTML without Django Forms. The problem is that the getlist function returns a maximum of two values even if I check more than two checkboxes. Where could the error be? if 'category' in request.GET: print('Category in request GET.') if len(request.GET.getlist('category')) == 1: print(request.GET.getlist('category')) filters['category_id'] = Category.objects.get( slug='-'.join(request.GET.get('category').lower().split())).id if len(Property.objects.filter(**filters)) == 0: queryset.clear() messages.info(request=request, message='No Results.') return redirect(to='properties') else: request.session['sorted_type'] = 'Newest Properties' request.session['filters'] = filters context.update(sidebar_context(**filters)) queryset.clear() queryset.extend(Property.objects.filter(**filters)) else: print('More than one Category.') filters['category__pk__in'] = [Category.objects.get(slug='-'.join(obj.lower().split())).id for obj in request.GET.getlist('category')] if len(Property.objects.filter(**filters)) == 0: queryset.clear() messages.info(request=request, message='No Results.') return redirect(to='properties') else: print(request.GET.getlist('category')) request.session['sorted_type'] = 'Newest Properties' request.session['filters'] = filters context.update(sidebar_context(**filters)) queryset.clear() queryset.extend(Property.objects.filter(**filters)) <form data-properties-filters-form class="properties__filters__filters-form theme-form" method="get" action="{% url 'properties' %}"> <div style="opacity: 0; position: absolute; top: 0; left: 0; height: 0; width: 0; z-index: -1;"> <label>leave this field blank to prove your humanity <input type="text" class="url" autocomplete="off" tabindex="-1"> </label> </div> {% if categories %} <div class="properties__filters__title h4">Category</div> <div class="form__row"> <div class="form__field"> <div data-change-category class="form__input-wrap form__checkbox-wrapper"> {% for category in categories %} <label> <input data-checkbox data-input type="checkbox" name="category" value="{{ category|lower }}"{% if category|lower in request.GET.category … -
Can't connect Django with Mysql
I tried to connect Django with Mysql server But the error show up when I ran python manage.py migrate I already created the database in Mysql and modify the settings.py in Django. I also check if the Mysql server is running which it's currently running. Library installed mysqlclient pymysql Here is my settings.py Here is the error django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") I tried restart the service of Mysql8services0 but still does not work for me -
400 Bad Request in Apollo Client querying Django Backend
I'm getting the following error when I attempt to make a GraphQL query using Apollo Client in my React frontend from my Django/Django Rest/Graphene Backend. I have also gotten some CORS errors so I have disabled cors on the client with: fetchOptions: { mode: "no-cors", }, and on the backend with csrf_exempt. I am able to make the query work just fine in Postman and GraphiQL but not in React. Here is my query: export const STOCKS_BY_ADJ_CLOSE_RANGE_AND_DATE_QUERY = gql` query StocksByAdjCloseRangeAndDate { stocksByAdjCloseRangeAndDate( low: 100 high: 105 start: "2024-03-01T00:00:00Z" end: "2024-03-10T00:00:00Z" ) { ticker datetime open high low close adjClose volume } } `; Here is my client: const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { console.log("graphQLErrors", graphQLErrors); } if (networkError) { console.log("networkError", networkError); } }); const client = new ApolloClient({ cache: new InMemoryCache(), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, connectToDevTools: true, link: from([ errorLink, new HttpLink({ uri: "http://127.0.0.1:8000/graphql", fetchOptions: { mode: "no-cors", }, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true", }, }), ]), }); Here are my Django routes: urlpatterns = [ # path("", router.urls), # path("", include(router.urls)), path( "api-auth/", include("rest_framework.urls", namespace="rest_framework") ), path("admin/", admin.site.urls), # path("", TemplateView.as_view(template_name="frontend/build/index.html")), path("api/", include(router.urls)), path("", home), path( … -
Problem with "{% load static %}" in Django
I'm just starting with django, and when I put {% load static %} in the html it doesn't complete it, that is, it doesn't take it as code, I need helpenter image description here I tried importing it through a link, adding a general folder but I don't know what happens -
Could not deserialize class 'Functional'
I did transfer learning to VGG16 model in order to classify images to cat or dog and here is portion of the code snippet : prediction_layer = tf.keras.layers.Dense(1) prediction_batch = prediction_layer(feature_batch_average) def manual_preprocess_input(x, data_format=None): if data_format is None: data_format = tf.keras.backend.image_data_format() if data_format == 'channels_first': # If channels are first, move them to the last dimension x = tf.transpose(x, perm=[0, 2, 3, 1]) # Mean subtraction (ImageNet means in BGR order) mean = [103.939, 116.779, 123.68] x = x - tf.constant(mean, dtype=x.dtype) # Zero-centering by subtracting 127.5 x = x / 127.5 return x inputs = tf.keras.Input(shape=(224, 224, 3)) x = data_augmentation(inputs) x = manual_preprocess_input( x ) x = base_model(x, training=False) x = global_average_layer(x) x = tf.keras.layers.Dropout(0.2)(x) outputs = prediction_layer(x) model = tf.keras.Model(inputs, outputs) and here is the view code where I loaded my model : then I saved it using model.save('my_model.keras'), then I loaded in a django view but the problem is whenever I load it and make post request to the view, in the line where I load the model I encounter this error : def testSkinCancer(request): model = tf.keras.models.load_model( os.getcwd()+r'\media\my_model.keras', safe_mode=False) print(">>> model loaded") if not request.FILES: return HttpResponseBadRequest(json.dumps({'error': 'No image uploaded'})) # Access the uploaded image … -
How to get the foreign key value into href attribute of a hyperlink element as a url parameter in Django template
I have data table showing list of vehicles from the Vehicle model with Driver column. When user clicking on the Driver column value, I want to redirect the user to driver detail page url driver-detail/license_number. I tried to pass the license_number to href attribute of hyperlink element like href="{% url 'driver-detail' vehicle.driver.license_number %}". This does not help me, it's always empty. If I omit the license_number in the href value it will pass the __str__(self) return value of the Driver model, which is combination of license_number and fullname. If I change the return value of __str__(self) in the Driver model it will work. But I don't want to change the return value of __str__(self). Any help is much appreciated! Model.py class Driver(models.Model): license_number = models.CharField(primary_key=True, max_length=50) fullname = models.CharField(max_length=25) license_issue_date = models.DateField("Issued Date") def __str__(self): return self.license_number + " " + self.fullname class **Vehicle**(models.Model): license_plate = models.CharField(max_length=25, primary_key=True) model = models.CharField(max_length=100, verbose_name="Vehicle model") driver = models.ForeignKey(Driver,on_delete=models.SET_NULL,null=True, blank=True) template.html <a href="{% url 'driver-detail' vehicle.driver.license_number %}" > {{vehicle.driver.license_number}}{{vehicle.driver.fullname}} </a> urls.py urlpatterns = [ path('driver-detail/<str:pk>/', views.driverDetail, name='driver-detail'), ] -
Celery and Celery beat wit django after running in docker container running some job
I am trying to run django celery and celery beat after i start celery and celery beat this process is running every second is this normal celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.478374+05:30) celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.766830+05:30) celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully I tried clearing redis db also tried uninstalling and installing redis,celery -
Django PasswordResetView not working properly with app_name causing DisallowedRedirect
I'm encountering an issue with Django's built-in password reset functionality within my project. Specifically, I have an app named 'user' and I've defined the app_name variable in my urls.py as app_name = 'user'. However, this seems to be causing problems with Django's password reset views. Initially, I encountered the "Reverse for 'url name' not found" error when using auth_views.PasswordResetView. To address this, I tried setting the success_url parameter to 'user:password_reset_done' and providing a custom email_template_name. However, now I'm facing a new issue where the debugger is raising a DisallowedRedirect exception with the message "Unsafe redirect to URL with protocol 'user'" when attempting to access the password reset functionality. This occurs during the execution of django.contrib.auth.views.PasswordResetView. the error is: Unsafe redirect to URL with protocol 'user' Request Method: POST Request URL: http://127.0.0.1:8000/accounts/reset_password/ Django Version: 5.0.2 Exception Type: DisallowedRedirect Exception Value: Unsafe redirect to URL with protocol 'user' Raised during: django.contrib.auth.views.PasswordResetView Here's a summary of my setup: urls.py (within the 'user' app): from django.urls import path from django.contrib.auth import views as auth_views app_name = 'user' urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name='registration/reset_password.html', success_url='user:password_reset_done', email_template_name='registration/password_reset_email.html'), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete') ] registration/reset_password.html: {% block content %} <h1>Password reset</h1> <p>Forgotten your … -
creating migrations in Django [closed]
I was following a YouTube video guide on django, and I ran into a problem when after filling out the file models.py I went to cmd and wrote python manage.py makemigrations, but instead of the created file in the migrations directory, I was met with a long error. This is my first experience with django and no migrations have been created before. The code models.py - ` from django.db import models class Articles (models.Model): title = models.CharField('Name', max_length=50) anons = models.CharField('Announcement', max_length=250) full_text = models.TextField('Article') date = models.DateTimeField('Publication date') def __str__(self): return self.title` ` error - `C:\Users\глеб\Desktop\pip\books> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\глеб\Desktop\pip\books\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 16, in cached_import return getattr(module, class_name) AttributeError: module 'django.db.models' has no attribute 'Bi gAutoField' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\db\models\options.py", line 275, in _get_default_pk_class pk_class = import_string(pk_class_path) File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 32, in import_string raise ImportError( ImportError: Module "django.db.models" does not define a "Bi gAutoField" attribu te/class The above exception … -
Creating a model through the admin panel inside the test
I'm new to Python. I'm trying to create a test that will create an item inside the admin panel, but when I run the test I get: AssertionError: False is not true. Help me please class ItemAdminTest(TestCase): serialized_rollback = True def setUp(self): self.client = Client() self.user = User.objects.create_superuser(email='admin@example.com', password='admin') def test_create_item_admin(self): self.client.login(email='admin@example.com', password='admin') response = self.client.post('/admin/product/item/add/', { 'title': 'Test Item', 'description': 'Test Description', 'price': 10.00, 'code': 123456, 'color': 'Red', 'weight': 1.5, 'height': 10.0, 'width': 5.5, 'types': ["КБТ", "МБТ"], 'amount': 5, }) self.assertTrue(Item.objects.filter(title='Test Item').exists()) At the same time, I am absolutely sure that a superuser is created and authorization is successful, but for some reason the item itself is not created. -
Invalid credentials even putting right credentails django
I have created a sign in form for my user and when I’m trying to log in it says invalid student_ID or password even though I put my credentials properly I’m using postgresql via Railway I’m a beginner (https://i.stack.imgur.com/iRQcJ.png) This is my forms.py from django import forms from django.forms import ModelForm from .models import StudentInfo class StudentInfoForm(forms.ModelForm): class Meta: model = StudentInfo fields = ['student_id', 'firstname', 'lastname', 'middlename', 'course','year', 'section', 'password', 'confirm_password',] widgets = { 'password': forms.PasswordInput(), 'confirm_password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'].required = True self.fields['firstname'].required = True self.fields['lastname'].required = True self.fields['course'].required = True self.fields['section'].required = True self.fields['password'].required = True self.fields['confirm_password'].required = True class SignInForm(forms.Form): student_id = forms.CharField(label='Student ID', max_length=10) password = forms.CharField(label='Password', widget=forms.PasswordInput) This is my models.py from django.db import models from django.contrib.auth.hashers import make_password # Create your models here. class StudentInfo(models.Model): student_id = models.CharField(max_length=10, unique=True, primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) middlename = models.CharField(max_length=100, blank=True, null=True) course = models.CharField(max_length=100) year = models.CharField(max_length=1) section = models.CharField(max_length=1) password = models.CharField(max_length=128, null=True) confirm_password = models.CharField(max_length=128, null=True) def __str__(self): return f"{self.firstname} {self.lastname}" def save(self, *args, **kwargs): self.password = make_password(self.password) super(StudentInfo, self).save(*args, **kwargs) This is my urls.py from django.urls import path from . import views urlpatterns = [ … -
how to make a django model with no id column and primary key?
i am working with big data and i can have an extra column like id. i cant put the primary key to any other single column, because of duplicate. and even more i cant have primary key on two column or more because my data is not unique. so the only way to get rid of the id column with a primary key left for me is to stop django making it! and i don't know how... i tried to edit the operation part of the migration file before doing the migrate command but it didn't work. even if i delete the id column in the migration file it still make it /:(. -
Query using reverse relationship or objects manager?
from .models import Comment user = request.user comments_1 = user.comment_set.all().count() comments_2 = Comment.objects.filter(user=user).count() Between comments_1 and comments_2, which one is faster? Can someone explain to me? Any help will be greatly appreciated. Thank you very much. I looked in Django Documentation Making queries, but does not really say about the difference in performance. -
Django - Redirection to Strava API Auth Page is not working
So I'm Trying to redirect my django web app after the user submitted the form AND if the user chose 'Strava Link' Option from the form. What I'm currently doing is to open Strava's API Authorization Page for code/token exchange so my app will fetch the data from user's Strava account. My current problem is that it does not redirect to my Strava API's Authorization page (No Error, nothing) and I tried printing the Authorization URL so I can debug it. I Tried Manually opening the Authorization URL and It is working. I've watched some Strava API tutorials using python and all of them manually enters the link to copy the code after the user clicked 'Authorized'. Is My method correct? Form Submission -> Redirect the user to Strava's API Authorization Page (stuck on this step) -> Callback to return the code/token -> Fetch the data Here's my current code innside views.py: async def index(request): if request.method == 'POST': #Start of process after Form Submitted try: data_dict = link_validation(request, data_dict) #Rest of the code Here (Irrelevant and not related to Strava API) except Exception as e: return render(request, 'index.html', {'error_message': str(e)}) else: return render(request, 'index.html') def link_validation(request, data_dict): redirect_to_strava_auth(request) #Rest … -
NextJs not setting the cookie from django csrf_token
My nextjs application integrated with django has an authentication system based on csrftoken and sessionid. Once the nextjs application runs, it makes a request to the backend for the csrf route, which automatically sets a cookie to the destination of the request. This works normally running locally. But when running nextjs in docker in the production environment you can see that the cookie is set in the response headers, but it does not actually create a cookie. I had seted CSRF_COOKIE_SAMESITE = None and SESSION_COOKIE_SAMESITE = None But still not setting the cookie, even in the headers showing the set cookie XHRGET https://api.viajahturismo.com.br/api/v1/csrf/ [HTTP/2 204 23ms] csrftoken expires "2025-03-09T00:38:39.000Z" path "/" samesite "None" value "8UayLGpyXUF0cc2AlM5zqBd4kdOHSfXf" csrftoken "8UayLGpyXUF0cc2AlM5zqBd4kdOHSfXf" My django setting: """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import os from pathlib import Path # 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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY … -
Error deploying Django project on Railway
I'm trying to deploy a Django project on Railway and I'm getting a runtime error saying "The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages." As far as I'm aware I've installed Apache but have probably missed something -
AWS ElasticBeanstalk container_commands: Commands trigger errors even if they were correct
I have a django project that I want to deploy with ElasticBeanstalk, I defined a [xxxx.config] file in .ebextensions, the content of the file is: xxxx.config container_commands: acvenv: command: "source /var/app/venv/*/bin/activate" migrate: command: "python /var/app/current/manage.py migrate" But the project doesn't deploy unless I remove xxxx.config. I follow the documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html What am I doing wrong? -
Django UpdateView not Updating
I have created a Django app that allows users to enter their stock trades, as a journaling tool. When a user clicks on an individual journal entry from the index page, they will be taken to a detail page showing all the information on that individual entry (single_entry.html). This page is handled by an UpdateView. From this page, a user can edit/update any info, as well as DELETE that specific entry. There are two buttons on the form, one for 'Delete' and another for 'Update'. The deleting works fine. The updating used to work, but now is not for some reason! Nothing updates in the Entry. Also I can't figure out why the 'messages' middleware is not being output to the screen. Same with all my print() statements, nothing is coming out on the console. Thanks for your help! Here's my views.py: from django.forms.models import BaseModelForm from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.views import View from django.contrib import messages from django.urls import reverse_lazy from .forms import EntryForm from .models import Entry from django.views.generic.edit import UpdateView, DeletionMixin from django.views.generic import DeleteView # Create your views here. class EntryView(View): def get(self, request): entries = Entry.objects.all().order_by("entered_date") form = … -
Data is not being returned to Django Template, Data Does Exist
I am having an issue not getting data to return to a template, but this is not happening with other models in the same template. I can properly submit data on another page to this data model (TechnicianLabor) via a form, but the data will not publish from my calls in the html, what am I missing?: models.py class TicketList(models.Model): identifier = models.AutoField(primary_key=True) name = models.CharField(max_length=150, null=True, blank=True) description = RichTextField(default="Add description for Ticket: ", null=True, blank=True) client = models.ForeignKey('ClientCompany', blank=True, null=True, on_delete=models.CASCADE) assignment = models.ManyToManyField(TechnicianUser, null=True, blank=True) create_date = models.DateField(auto_now_add=True) end_date = models.DateField(null=True, blank=True) due_date = models.DateField(null=True) class TechnicianLabor(models.Model): ticket = models.ForeignKey(TicketList, on_delete=models.CASCADE) minutes = models.BigIntegerField(default=0) is_tracked = models.BooleanField(default=False) created_by = models.ForeignKey(TechnicianUser, on_delete=models.DO_NOTHING) created_at = models.DateTimeField() views.py def apps_tickets_details_view(request, pk): tickets = TicketList.objects.get(pk=pk) projects = ProjectList.objects.filter(pk=tickets.project_id) labors = TechnicianLabor.objects.all() comments = TicketComment.objects.filter(ticket_id=tickets) comment_count = comments.count() technicians = TechnicianUser.objects.all() replies = TicketCommentReplies.objects.filter(ticket_id=tickets) context = {"tickets":tickets,"comments":comments,"projects":projects, "replies":replies, "technicians":technicians, "labors":labors, "comment_count":comment_count} if request.method == "POST": form = TicketListAddForm(request.POST or None,request.FILES or None, instance=tickets) if form.is_valid(): print(comments) form.save() messages.success(request,"Ticket Updates Successfully!") #return redirect("apps:tickets.list") return redirect(reverse("apps:tickets.details", kwargs={'pk':tickets.pk})) else: print(form.errors) messages.error(request,"Something went wrong!") return redirect("apps:tickets.list") #return redirect(reverse("apps:tickets.list", kwargs={'pk':tickets.pk})) return render(request,'apps/support-tickets/apps-tickets-details.html',context) html <h6 class="card-title mb-4 pb-2">Time Entries</h6> <div class="table-responsive table-card"> <table class="table align-middle mb-0"> <thead class="table-light … -
Deploying Django in PAAS (Clever-Cloud) / can't find my app
I am trying to deploy my django (5.0.3) in Clever cloud It can't locate my app on the server, although it works fine locally Here is my tree structure Here is my settings.py Here are my env variables in cleveer-cloud Here is the error : 2024-03-09T14:55:49+01:00 ModuleNotFoundError: No module named 'photos' What could be the root cause ? -
Django: The static tag not loading on extended html when linking an image but works for CSS style sheet?
I have a layout.html file as follows: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static 'app/styles.css' %}" rel="stylesheet"> </head> <body> {% block body %} {% endblock %} </body> </html> and a extended.html as follows: {% extends "layout.html" %} {% block body %} <div class="maincontainer"> <h1>Extended</h1> <img src="{% static 'app/images/image.svg' %}" alt="image"> </div> {% endblock %} When I load the exnteded.html I get the follwoing error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'static', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have tested a few scenarios out: If I remove the <img src="{% static 'app/images/image.svg' %}" alt="image"> from the extended.html the CSS style sheet loads perfectly. If I add {% load static %} to the extended.html the image and CSS style sheet both load. I have had a look at the Django docs and have ensured that the settings.py file does have django.contrib.staticfiles in INSTALLED_APPS and STATIC_URL = "static/". Am I missing something here? -
django-celery-beat loading task but celery worker not receiving it
I've been having these issues on my celery beat and worker where my celery beat creates task, but celery worker does not receive it . I am using elasticmq as the broker My celery beat logs docker exec -it app-1 celery -A app beat --loglevel info celery beat v5.3.6 (emerald-rush) is starting. __ - ... __ - _ LocalTime -> 2024-03-09 16:25:41 Configuration -> . broker -> sqs://user:**@sqs:9324// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2024-03-09 16:25:41,744: INFO/MainProcess] beat: Starting... [2024-03-09 16:25:41,821: INFO/MainProcess] Scheduler: Sending due task beat_task (app.tasks.beat_task) [2024-03-09 16:25:51,782: INFO/MainProcess] Scheduler: Sending due task beat_task (app.tasks.beat_task) My celery worker log docker exec -it kole-app-api-app-1 celery -A app worker --loglevel info/usr/local/lib/python3.11/site-packages/celery/platforms.py:829: SecurityWarning: You're running the worker with superuser privileges: this isabsolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(SecurityWarning(ROOT_DISCOURAGED.format( -------------- celery@b4d9d70aafdc v5.3.6 (emerald-rush)--- ***** ------- ******* ---- Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with 2024-03-09 16:26:10 *** --- * --- ** ---------- [config] ** ---------- .> app: app:0x7fd2fe122f90 ** ---------- .> transport: sqs://user:**@sqs:9324// ** ---------- .> results: disabled:// *** --- * --- .> concurrency: 6 (prefork)-- ******* ---- .> task … -
send data from javascript to django without sending request, post, get
I have a project is about web game, if the player end the game #e.g. bool state == false then it will send the score back to the django backend, but i don't want the player have to press the submit button, is there any ways to do that? i have no any complete idea, i just found some solution is about ajax, fetch api..., but i don't really know if those work or not. my post can't pass the quality standard, is that means my post's word too less? -
how to use django validation with bootstrap tab list
I am trying to use bootstraps tab list with django, Basically i have grouped my fields under several fieldsets in the modelform. in the html template i generate bs nav-pills and tab-control to show the fields. it renders fine. below is the code. However whenever the user leaves a required field empty in a tab which is not active and clicks submit, django cannot put the focus on the required field. the same form works fine without bs tabs. So is there a way for me to be able to use django validation or do I need to write my own js to loop through all required fields and set focus? ========= the model form ================ class PostSellTutorForm(forms.ModelForm): class Meta: model = SellTutor exclude = default_exclude + ['post'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fieldsets = [ ['Basics', {'comment': 'about the tutor', 'fields': ['english', 'languages', 'years_of_experience', 'primary_occupation', 'message']}], ['Cost', {'comment': 'tutor cost', 'fields': ['hourly_rate', 'free_trial', 'free_trial_hours']}], ] def get_fieldsets(self): return self.fieldsets ============ the render function =============== def render_post_form(request, template, form, title, post_id, post_type, partial_save): context = {} # context['fieldsets'] = form.Fieldsets.value context['form'] = PostSellTutorForm context['page_title'] = title return render(request, template, context) =========== the template ======================= {% load static %} <!-- …