Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password field in Signup/Login form not appearing properly | Django | HTML | Bootstrap
I am trying to create a custom signup form using HTML, CSS, Bootstrap as front end, and Django as backend, when I create the form, firstname, lastname, and email are appearing as required, but the password and confirm_password fields are not appearing as required, from forms.py, the widget's placeholder and class=form-control is also not being applied to it. I asked ChatGPT, it is asking to clear Cache, switching to incognito or a different browser, I tried all things, and still it is appearing the same. I am providing all the files associated with the signup form I created. models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name=None, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set.') if not first_name: raise ValueError('The First Name field must be set.') if not password: raise ValueError('Password cannot be left blank.') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] def __str__(self): return self.email forms.py from django import forms from django.contrib.auth.forms import … -
reasons for using rust api over django, node?
Has anyone made a large scale rust web api and if so why did you choose it over easier languages like python. Is there significant performance, lower response times, concurrency, etc from using rust compared to python or is it negligible. Assume we’re talking about a social media app which wouldnt be heavy mathematically. It was suggested to me that a web api is dominated by the speed and efficiency of database operations and this using a faster language like rust compared to python has negligible benefits in real world, is this true in your experience? -
How to pass a Django form response through another template
I am creating a site for users to record their chicken's weights and I am trying to design a confirmation form for if a user tries to submit another weight for the same chicken on the same day. In other words, if a record already exists for that date, how to ask the user if it should be overwritten without the user re-entering the weight. This is all I have so far: # views.py def add_record(request, chicken) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse: """ View for the "record_weight.html" Post & Get methods """ if request.method == "POST": form = RecordForm(request.POST) if form.is_valid(): record = form.save(commit=False) record.chicken = Chicken.objects.filter(number=chicken).first() record.date = datetime.now().date() try: Record.save(record) except ValidationError: # There is a record for that day, render another form asking if they want to overwrite return render(request, "tags/duplicate_record.html", {"bird": record.chicken}) return redirect("/admin/tags/record/") form = RecordForm() try: birds = Chicken.objects.all() req_bird = birds.filter(number=chicken).first() except Chicken.DoesNotExist: raise Http404("Bird does not exist") try: req_records = Record.objects.filter(chicken_id=chicken).order_by("date").reverse() except Record.DoesNotExist: req_records = [] return render(request, "tags/record_weight.html", {"bird": req_bird, "records": req_records, "form": form, "nav_filter": get_birds_navbar(birds)}) # duplicate_records.html (styling removed for easier reading) {% extends "tags/layout.html" %} {% block content %} <div> <div> <h2>There is already a weight for today!</h2> … -
Image Field in Django forms is not working
urls.py: urlpatterns = [ path("",views.index,name = "index"), path("signup/",views.signup,name = "signup"), path("login/",views.login,name = "login"), ] urlpatterns+=static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT ) settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' forms.py: class SignUp(forms.Form): is_doctor = forms.BooleanField(label = "Are you a doctor?",required=False) f_name = forms.CharField(label = "First Name", max_length=200) l_name = forms.CharField(label="Last Name",max_length=200) username = forms.CharField(label = "Username",max_length = 100) email = forms.CharField(label = "Email",max_length=200) profile_pic = forms.FileField(label= "Profile Picture", widget = forms.ClearableFileInput(attrs={'class':'form-control'}),required=False) password = forms.CharField(label ="Password",max_length=200) confirm_password = forms.CharField(label = "Confirm Password",max_length=200) address = forms.CharField(label="Address",max_length = 400) views.py: form = SignUp(response.POST,response.FILES) In the html file I have the attribute: enctype="multipart/form-data" I cannot understaNd what else I need to do. I have read so many docs and watched so many videos. They're all saying the same thing. -
Django authencation problem- two different authencation one for custom admin and other for worker
I am facing this problem again n again. lemme explain you i am working on a complaint management site for my college, I have designed a separate customized admin panel which is working good, but the problem is occurring in making another admin panel for worker, where they can see allotted complaints and other things related to that, but I am not getting my desired result. ValueError at /worker-login/ The following fields do not exist in this model, are m2m fields, or are non-concrete fields: last_login **models.py def generate_id(): alphanumeric = string.ascii_uppercase + string.digits return ''.join(random.choices(alphanumeric, k=4)) class Assign(models.Model): id = models.CharField(max_length=4, primary_key=True, unique=True, default=generate_id) name = models.CharField(max_length=20) email = models.EmailField(max_length=30, unique=True) dob = models.DateField(null=True, blank=True) department = models.ForeignKey('Department', on_delete=models.SET_NULL, null=True, blank=True) phone_number = models.CharField(max_length=13, unique=True) profile_picture = models.ImageField(upload_to='profile_pictures/', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['dob'] class Meta: # Add this to prevent clashes with auth.User's groups and user_permissions default_related_name = 'assign_users' def save(self, *args, **kwargs): if not self.id: self.id = generate_id() super().save(*args, **kwargs) def __str__(self): return self.email **views.py def worker_login(request): if request.method == 'POST': email = request.POST.get('email') id = request.POST.get('id') user = authenticate(request, email=email, id=id) if user is not None: login(request, user, backend='app1.authentication_backends.AssignBackend') return redirect('worker_dashboard') else: messages.error(request, 'Invalid … -
why does self.filefield_field.path of an instance of a django model does not match the path where the file was actually uploaded
I am building an app in django (Django==3.1.14). the app should allow the user to upload zip files (in particular, they are shapefiles). I want django to upload and manage these files by storing them inside a model, having a FileField t host the file. I want each file to be uploaded at a specific path, like this: MEDIA_ROOT/shp/<timestamp>/<file_name>.zip NOTE: timestamp has seconds precision. my model has a field shp_file_folder_path that must have value equal to the path of the folder in which <file_name>.zip is stored, so MEDIA_ROOT/shp/<timestamp> Now, I have written the following model def generate_current_timestamp(): return datetime.datetime.now().strftime("%Y%m%d%H%M%S") def generate_uploaded_shp_file_relpath(): UPLOADED_SHP_FILES_DIR = 'shp' uploaded_shp_files_relpath_from_media_root = UPLOADED_SHP_FILES_DIR timestamp = generate_current_timestamp() current_file_subfolder = timestamp # relative path of the folder which will contain the uploaded file uploaded_shp_file_relpath = os.path.join( uploaded_shp_files_relpath_from_media_root, current_file_subfolder ) return uploaded_shp_file_relpath # Create your models here. class Shp(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000, blank=True) shp_file = models.FileField(upload_to=generate_uploaded_shp_file_relpath()) # this is a file, but in postgres is represented as path uploaded_date = models.DateField(default=datetime.date.today, blank=True) shp_file_folder_path = models.CharField(default='undefined', max_length=1000, blank=True) # this is to be not visible nor editable by admins # this defaultvalue is not required the function to be correct because it will be overwritten by the … -
raised unexpected: TypeError('send_verification() takes 1 positional argument but 3 were given') in celery
class CreateAccountView(APIView): permission_classes = [] def post(self, request): print(request.data) email = request.data.get('email') if User.objects.filter(email=email).exists(): return Response({"message": "User with this email already exists"}, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): domain = request.get_host() send_verification.delay(email,domain) serializer.save() return Response({"message": "Check your email to verify your account"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @shared_task(bind=True) def send_verification(self,email,domain): print(email) try: email_from = settings.EMAIL_HOST_USER token = generate_token(email) verify_url = f'http://{domain}{reverse("verify_email", args=[token])}' subject = 'Verify your email address' message = f'Click the link to verify your email: {verify_url}' send_mail(subject, message, email_from, [email]) print(message) except Exception as e: print(f'Error sending email: {e}') print("Done") return "Done" when i was try to send a verification link through celery and pass 2 arguments to the send_verification() function but it always says takes 1 positional argumentt and 3 where given -
How do I get my CSS to function in Chrome?
I am new to Python and taking a Django course online from Dave Gray. In the course we create CSS for Nav feature. * { margin: 0; padding: 0; box-sizing: border-box; } body { min-height: 100vh; background-color: black; color: whitesmoke; font-size: 3rem; display: flex; flex-flow: column; } nav { padding: 1rem; background-color: #44B78B; color: white; font-size: 2.5rem; } main { flex-grow: 1; display: grid; place-content: center; } h1, p { text-align: center; } a { text-decoration: none; color: #81dbb8; } a:hover { opacity: .85; } My Layout HTML is: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> {% block title %} Django App {% endblock %} </title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/main.js' %}" defer></script> </head> <body> <nav> <a href="/">🏡</a> | <a href="/about">😊</a> | <a href="/posts">📰</a> </nav> <main> {% block content %} {% endblock %} </main> </body> </html> My Home Page HTML is: {% extends 'layout.html' %} {% block title %} Home {% endblock %} {% block content %} <h1>Home</h1> <p>Check out my <a href="/about">About</a> page.</p> {% endblock %} I normally use Chrome and it did not look like his example. After reviewing the CSS I opened the … -
Flutterwave 403 Client Error: Forbidden for url: https://api.flutterwave.com/v3/payments
Please, I need help integrating flutterwave on my django project. Whenever I click on the checkout button on my payment page, I get the error above. Here is what my flutterwave view looks like: this view is used to get the slug of the particular product and price when the checkout button is clicked def flutterwave(request,slug,price): mobile = Mobile.objects.get(user=request.user) try: food_product = food.get(slug=slug,food_price=price) #soup_product = soup.get(soup_item=product) except food.DoesNotExist: return JsonResponse({"error": "Food product does not exist"}, status=404, safe=False) url = "https://api.flutterwave.com/v3/payments" headers = { "Authorization": f"Bearer {FLUTTERWAVE_LIVE_SECRET_KEY}", "Content-Type": "application/json" } payload = { "tx_ref": tx_ref(), "amount": float(food_product.food_price), "currency": "NGN", "redirect_url": "http://127.0.0.1:8000/payments/verify_payment/", "meta": { "consumer_id": 23, "consumer_mac": "92a3-912ba-1192a" }, "customer": { "email": request.user.email, "phonenumber": str(mobile.phone_no), "name": request.user.username }, "customizations": { "title": "Pied Piper Payments", "logo": "http://www.piedpiper.com/app/themes/joystick-v27/images/logo.png" }, "configurations": { "session_duration": 10, # Session timeout in minutes (maxValue: 1440 minutes) "max_retry_attempt": 5 # Max retry attempts for failed transactions } } try: print("URL:", url) print("Headers:", headers) print("Payload:", payload) response = requests.post(url, headers=headers, json=payload) print("Response Type:", type(response)) response.raise_for_status() # Raise an error for bad status codes # Assuming the response is JSON, you can access it like this: json_response = response.json() return JsonResponse(json_response, safe=False) except requests.exceptions.RequestException as err: error_message = f"Error: {err}" return JsonResponse({"error": … -
API for dota player information using Django
Good afternoon, I might be mistaken as I am new to Django and API, but hopefully someone can correct me if I am wrong. I have this task to create a webpage here is the sample https://impactosolardota.com/. I have to create a website for something similar like this is Cuban leaderboard and I want to do one for Colombia. How can I obtain the player information that updates constantly. As far as my understanding goes, I need an API to send information from another website to mine. My plan is to build a Django website and the frontend in React. However, I am starting to think that I might not need Django at all and maybe do only with React?. -
Django Admin automatically logs me out when i click the save button and won't allow me log in again
Whenever I click the save button to add user on the django admin interface, it automatically logs me out and won't re-authenticate me despite being the superuser. The design pattern: I created a class called CustomUser which inherited the django AbstractUser and another class UserProfile model which has OneToOneField to the settings.AUTH_USER_MODEL(main.CustomUser) and added some common fields among the student, parent and staff(e.g other_name), then student, staff and parent class inherited the UserProfile and I added their specific field. So I do add a user first, then go to the student model to add the user as a student. main is my app_name. Kindly help with on this as I have deadline which is near. I'll provide more details and code on request settings.py file from pathlib import Path import os import secrets from django.conf.urls import handler403 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-!&740lo5u6#-@c9d80ab*-!k1-8f$fu@r*3xp5ytke)7t+dwy+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition # SESSION_TIMEOUT_SECONDS = 120 … -
I'm having problems with the layout of a web page using the django framework
I'm taking a course at ww3school and in part of the course I see that it didn't look the same in the proposed exercise, I'm going to put two images to reference my problemIn this image the page layout is correct, this image was my result I'm using Visual Studio Code on Windows 10 Django version: I've made sure I'm using the same version of Django as the course. I made sure the project settings (like settings.py) are correct. I checked that I followed the same customization steps. I tried clearing the browser cache or opening the page in an incognito/incognito window. -
How to make content fetched during login persist even if the user logs out and logs in again?
I currently am working on a project where a user authenticates, and when they are redirected to the home page, a GET request to an API is made: def home(request): url = f'https://icanhazdadjoke.com/' headers = { "Accept": "application/json" } #Putting the application/json in the header to get a JSON result r = requests.get(url,headers=headers) #Making a get request to get a random dad joke data = r.json() #Converting JSON data to a python dictionary required_joke = {'joke': data['joke']} return render(request,'test_section/Home.html',required_joke) Now, I mainly have two requirements: When the user presses the refresh button, a new joke should be generated (satisfied). If the user logs out, and logs back in again, the same joke that was being shown on the screen previously should be shown. For example, if the user logs out now, and logs back in, he should see this same joke displayed. I will be very grateful if someone can guide me regarding how to tackle this. It looks simple but I do not understand where to start. -
Updating a django table, hashing a specific field in a table
I have a table that looks something like class PodUsage(models.Model): pod_id = models.CharField(max_length=256, db_index=True) pod_name = models.CharField(max_length=256) start_time = models.DateTimeField(blank=True, null=True, default=timezone.now) end_time = models.DateTimeField(blank=True, null=True) anonymised = models.BooleanField(default=False) user = models.ForeignKey("accounts.ServiceUser", null=True, blank=True, on_delete=models.CASCADE) As part of our GDPR requirement, we need to anonymize data after a certain period, which I could absolutely do as a loop: count = 0 records = PodUsage.objects.filter( anonymised=False, start_time__lte=timezone.now() - timedelta(weeks=settings.DATA_ANONYMISING_PERIOD_WEEKS) ) for record in records: record.pod_name = hashlib.sha256(record.pod_name.encode('utf-8')).hexdigest() record.user = None record.anonymised = True record.save() count += 1 # Log count somewhere however I think I should be able to do it with an update function: count = PodUsage.objects.filter( anonymised=False, start_time__lte=timezone.now() - timedelta(weeks=settings.DATA_ANONYMISING_PERIOD_WEEKS) ).update( pod_name = hashlib.sha256(pod_name.encode('utf-8')).hexdigest(), user = None, anonymised = True ) # Log count somewhere ..... but I can't figure out the correct incantation to reference the field in the update portion as given, pod_name is not defined sha256("pod_name".encode('utf-8')) obviously just encodes the string "pod_name" sha256(F("pod_name").encode('utf-8')) breaks the code with 'F' object has no attribute 'encode' Any suggestions? -
Django: Preload query from django-simple-history
I need to preload the update history queries saved with django-simple-history, to significantly improve the query execution time, for example, I have these models in my application: class Staff(models.Model): registration = models.CharField(max_length=100, unique=True) identification_type = models.CharField(max_length=2, choices=( ('V', 'V'), ('E', 'E'), ('J', 'J') ), default='V') identification_number = models.CharField(max_length=100, unique=True) first_names = models.CharField(max_length=100) last_names = models.CharField(max_length=100) birth_date = models.DateField() hire_date = models.DateField() hire_date_to_public_administration = models.SmallIntegerField(default=0) termination_date = models.DateField(null=True) sex = models.CharField(max_length=10, choices=( ('F', 'Femenino'), ('M', 'Masculino') )) address = models.TextField() marital_status = models.CharField(max_length=15, choices=( ('Soltero/a', 'Soltero/a'), ('Casado/a', 'Casado/a'), ('Divorciado/a', 'Divorciado/a') )) education_level = models.CharField(max_length=100) department = models.ForeignKey( Department, on_delete=models.RESTRICT, related_name='staffs' ) position = models.ForeignKey( Position, on_delete=models.RESTRICT, related_name='staffs' ) payroll_type = models.CharField(max_length=10, choices=[ ('Empleado', 'Empleado'), ('Obrero', 'Obrero'), ], default='Empleado') worker_type = models.CharField(max_length=10, choices=[ ('Fijo', 'Fijo'), ('Contratado', 'Contratado'), ('Pensionado', 'Pensionado'), ('Jubilado', 'Jubilado'), ], default='Contratado') status = models.CharField(max_length=100, choices=( ('Activo', 'Activo'), ('Inactivo', 'Inactivo'), ), default='Activo') bank = models.CharField(max_length=100) bank_number = models.CharField(max_length=100) concepts = models.ManyToManyField( Concept, related_name='staffs', blank=True ) salary = models.DecimalField(max_digits=8, decimal_places=2) children_number = models.SmallIntegerField(default=0) is_disabled = models.BooleanField(default=False) receive_complement = models.BooleanField(default=False) history = HistoricalRecords() class Meta: ordering = ['identification_number'] class Payment(models.Model): date = models.ForeignKey( Calendar, on_delete=models.RESTRICT, related_name="payments" ) staff = models.ForeignKey( Staff, on_delete=models.RESTRICT ) total = models.DecimalField(max_digits=8, decimal_places=2, default=0) total_deduction = models.DecimalField(max_digits=8, decimal_places=2, default=0) … -
creating custom validators for fields in Django REST framework serializers.Serializer
I am writing a serializer for a complicated put API with a large validate function. To simplify the logic and make it more readable, I want to create validators for individual fields (I want to make my serializer class as small as possible and hence don't want to write individual validate methods for each field). I am passing context to my serializer from the view and each of my fields share a common context. I want to use that context in the validator to perform the required checks. This is how I am attempting to create custom validators: My validator class: class MyCustomValidator: requires_context = True def __call__(self, value, serializer_field): context = serializer_field.context print(f"got this context: {context}") my serializer: class MySerializer(serializers.Serializer): my_field = serializers.IntegerField(required=True, validators=[MyCustomValidator()]) sending context in my view: def get_serializer_context(self): context = super().get_serializer_context() context.update({'test_context': {'key': 'value'}}) return context But when I am calling this API, I get the following error: __call__() missing 1 required positional argument: 'serializer_field' Can someone please tell me what am I missing here? Thank you... -
Trying to filter "managers" field to only show managers in the currently logged in user's department
I have 3 models The base User model that Django provides UserProfile, a model that has 2 fields: a foreignkey field with the user table a department field thats a choicefield with a dropdown, every user has 1 department And finally and Event model that contains a Manager field, a manytomany with the user model. I am trying to filter the manager field on the backend to only show managers that share the same department, since we don't want people to be able to add other departments as managers in their events This is the function that I'm trying to overwrite in my admin.py (using Django 5.0) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "managers": kwargs["queryset"] = Data.objects.filter(managers.userprofile.department == request.user.userprofile.department) return super().formfield_for_manytomany(db_field, request, **kwargs) I keep getting errors about the managers field not having a attribute of userprofile -
How serializer field can be set without showing it to enduser in DRF?
I have url like doc/<int:doc_id>/price/ for get and post and doc/<int:doc_id>/price/<int:id> for delete and patch or retrieve. My problem is, when creating a new price I want to set price.doc_id=self.kwargs['doc_id'] but at the same time I want that serializer field to be hidden in swagger documentation(I use drf-spectacular). The end-user should not be aware of that field. I know I can overwrite the create function of serializer and explicitly set the price or use serializers.save(doc=doc). But I ask this question to get a better solution. I tried hiddenfield as well but apparently it only takes default value and I do not know how to pass doc_id to it. class DocPriceOutHistorySerializer(ModelSerializerWithValidator): currency_name = serializers.CharField(read_only=True) type_price_name = serializers.CharField(read_only=True) class Meta: model = models.DictPriceList fields = ( 'id', 'dat', 'price', 'currency', 'currency_name', 'type_price', 'type_price_name', 'obj', 'doc', ) and in views.py data = request.data data['doc'] = self.kwargs['doc_id'] serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) this will work but I do not want to manually write a request schema for swagger. -
how to use AsyncIOScheduler in django?
I am developing an API using Djaongo Rest Framework that periodically calls an asynchronous method through AsyncIOScheduler(a component of APScheduler), making it run every few seconds. However, it is not working as expected, and nothing is printed to the console. Below is my code. Scheduler definition: scheduler = AsyncIOScheduler() log = logging.getLogger(__name__) def start_scheduler(): if not scheduler.running: scheduler.start() logging.info('scheduler started') Code to start the scheduler: class ApiConfig(AppConfig): name = 'api' def ready(self): from .scheduler import start_scheduler start_scheduler() API endpoint definition: class Boo(): async def test(): print("testFoo") await asyncio.sleep(1) print("testFoo done") class Foo(): def __init__(self): self.insideObjs = [Boo() for _ in range(10)] async def run(self): tasks = [boo.test() for boo in self.insideObjs] logging.info(f'waiting for jobs done') results = await asyncio.gather(*tasks) logging.info(f'all jobs done') class FooViewSet(viewsets.ViewSet): @action(detail=False, methods=['post'], url_path='start') def start(self, request): foo = Foo() scheduler.add_job(foo.run, 'interval', seconds=3, id="123", replace_existing=True) In my expection,'testFoo' and 'testFoo done' should be print in the console every 3 seconds,but they actually not,I tried to change my ready() function of ApiConfig class from: class ApiConfig(AppConfig): name = 'api' def ready(self): from .scheduler import start_scheduler start_scheduler() to class ApiConfig(AppConfig): name = 'api' def ready(self): from .scheduler import start_scheduler start_scheduler() try: asyncio.get_event_loop().run_forever() except (KeyboardInterrupt, SystemExit): pass then django server … -
Setup API response Logs to EC2 Django development Server with Gunicorn
I am new to EC2 and web development. Currently I have a Amazone Linux EC2 instance running, and have installed Django. I am creating a project. I already setup ngnix gunicorn configruation and run the project. But i don't want response like local API response logs. I run this command tail -f /var/log/gunicorn/mdm_access.log and this is response 127.0.0.1 - - [28/Jun/2024:12:55:35 +0000] "GET /auth.html HTTP/1.0" 404 2312 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36" 127.0.0.1 - - [28/Jun/2024:12:55:35 +0000] "GET /api/sonicos/auth HTTP/1.0" 404 2333 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36" 127.0.0.1 - - [28/Jun/2024:12:55:35 +0000] "GET / HTTP/1.0" 404 179 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36" 127.0.0.1 - - [28/Jun/2024:12:55:35 +0000] "GET /auth1.html HTTP/1.0" 404 2315 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36" 127.0.0.1 - - [28/Jun/2024:12:55:35 +0000] "GET /sslvpnLogin.html HTTP/1.0" 404 2333 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36" 127.0.0.1 - - [28/Jun/2024:12:55:35 +0000] "GET /api/sonicos/tfa HTTP/1.0" 404 2330 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 … -
Creating a new thread in an API in django and calling another API in that thread
I was told that creating a thread for running background tasks will cause problems because in production gunicorn will kill a thread once the response is recieved. So, if I create a thread and inside that I call another api which is defined in the same app in django, will gunicorn create another thread for this api and thus wait for it to finish processing ? -
Huey process stuck, but why?
I'm trying to debug why our huey queue seems to freeze. We have a huey queu with 4 threads, however since a few days it seems to freeze. My hypotheses is that there is a method/task that keeps on running, and is stopping other tasks from processing. However it's a rather large project with a lot of stuff going into the queue. Huey settings: 'huey_class': 'huey.PriorityRedisHuey', 'name': 'queue', 'result_store': True, 'events': True, 'store_none': False, 'always_eager': False, 'store_errors': True, 'blocking': False, 'connection': { 'host': 'localhost', 'port': 6379, 'db': 0, 'connection_pool': None, 'read_timeout': 1, 'url': None, }, 'consumer': { 'workers': 4, 'worker_type': 'thread', 'initial_delay': 0.1, 'backoff': 1.15, 'max_delay': 10.0, 'utc': True, 'scheduler_interval': 1, 'periodic': True, 'check_worker_health': True, 'health_check_interval': 1, }, How can I debug this? Perhaps there is a setting that I can use to kill any task after x-time and log this somehow? Or perhaps something else I'm missing? Or perhaps there is a command to see what is currently being processed? -
How to Resolve Null Field Errors in Django When Creating a Task with Subtasks and Users
I'm encountering issues when trying to create a task with subtasks and users in my Django application. The task creation fails due to validation errors, specifically with the subtasks and users fields. Here is the payload I'm sending to the backend: { "id": null, "title": "aa", "description": "aaaa", "due_to": "2024-06-27T22:00:00.000Z", "created": null, "updated": null, "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [ { "task_id": null, "description": "s1", "is_done": false }, { "task_id": null, "description": "s2", "is_done": false } ], "users": [ { "id": 6 }, { "id": 7 } ] } When I attempt to create the task, I receive the following error message from the backend: { "subtasks": [ { "task_id": [ "This field may not be null." ] }, { "task_id": [ "This field may not be null." ] } ], "users": [ { "email": [ "This field is required." ], "password": [ "This field is required." ], "name": [ "This field is required." ] }, { "email": [ "This field is required." ], "password": [ "This field is required." ], "name": [ "This field is required." ] } ] } I suspect the issue is related to how I'm handling the nested serializers and the model relationships … -
Is it possible to use the same Django application name in multiple locations within a project?
I have a similar project structure to one below. project_name/ │ ├── apps/ │ ├── items/ │ │ ├── purchases/ │ │ │ ├── migrations/ │ │ │ ├── templates/ │ │ │ ├── __init__.py │ │ │ ├── admin.py │ │ │ ├── apps.py │ │ │ ├── models.py │ │ │ ├── tests.py │ │ │ └── views.py │ │ │ │ │ └── sales/ │ │ ├── migrations/ │ │ ├── templates/ │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ │ │ └── tools/ │ ├── purchases/ │ │ ├── migrations/ │ │ ├── templates/ │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ │ │ └── sales/ │ ├── migrations/ │ ├── templates/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ └── views.py │ ├── project_name/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ └── manage.py settings INSTALLED_APPS=[ ... "items.purchases", "items.sales", ... "tools.purchases", "tools.sales", ... ] I am getting the … -
operator classes are only allowed for the last column of an inverted index
Since I migrated my Django application from MariaDb to CockraochDB which is basically Postgres I get the following error, I really do not understand, I also do not find any referenced on the web or where I can start to debug this. At my Django Application, I first do manage.py make migrations, to generate the migrations files, after that I do manage.py migrate to apply these against my CockroachDB and this happens: Running migrations: Applying App_CDN.0001_initial...Traceback (most recent call last): File "/venv/lib/python3.12/site-packages/django/db/backends/utils.py", line 103, in _execute return self.cursor.execute(sql) > ^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.12/site-packages/django_prometheus/db/common.py", line 69, in execute return super().execute(*args, **kwargs) > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.DatatypeMismatch: operator classes are only allowed for the last column of an inverted index The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib/python3.12/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/venv/lib/python3.12/site-packages/django/core/management/base.py", line 459, in execute output = self.handle(*args, **options) > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.12/site-packages/django/core/management/base.py", line 107, in wrapper res = handle_func(*args, **kwargs) > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.12/site-packages/django/core/management/commands/migrate.py", line 356, in handle post_migrate_state = executor.migrate( > ^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.12/site-packages/django/db/migrations/executor.py", line 135, in …