Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python packages for Windows (pywin32, pywinauto) hosted on Linux server
I made Django project for automation on Windows machines (user machines will be also on Windows platform) using pywinauto package. I wanted to deploy it on Linux server but it cannot install pywin32 and pywinauto packages. What is the right way of solving this problem, Dockerizing, using some other alternative packages that is similar to the pywinauto style like -> ( send_to = zoom_app.Zoom.child_window(title_re="Send to.*", control_type="Edit", found_index=0).wrapper_object() ) or something else ? I try to deploy it on Linux and also creating Docker image but I had to write in requirments.txt for these packages that they are for Windows platform... -
NextJS POST requests with fetch or axios are switched to GET in production
I have a project using NextJS and Django as a RESTful API. Locally, when running the project, everything works fine. The POST requests are running well. On production server, Ubuntu, using Nginx as the webserver, pm2 for running NextJS and Gunicorn for running the Django project, I don't know why, for some reason, all the POST requests from the server-side of NextJS are getting transformed to GET (I am logging the API logs, and it shows me GET requests instead of POST) Does anyone know what could be the possible cause? -
Django authentication and redirect in views vs in template include
I'm using django for a web project I wan't to render a page for unauthenticate users and one for authenticated. Is it better to define this directly in my view : def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return render (request, 'unauthenticated.html') else: return render (request, 'authenticated.html') Or use only one view, but root them in my template : def get(self, request, *args, **kwargs): return render (request, 'index.html') <!-- index.html --> {% if not user.is_authenticated %} {% include "unauthenticated.html" %} {% else %} {% include "authenticated.html" %} {% endif%} (My question is about both security and implementation) -
Why my def perform_update() doesn't work in Django rest framwrok?
i want when user update a data of leave request django will send email to supervisor of that user perform_create is work but perform_update don't work Here's my code that's problem def perform_update(self, serializer): with transaction.atomic(): try: leave_request = serializer.instance serializer.save() supervisor = leave_request.user.supervisor if supervisor and supervisor.email: self.send_leave_request_email(leave_request, supervisor.email, "Updated Leave Request") except Exception as e: logger.error(f"Error during leave request update: {str(e)}") raise e Here's CLass class LeaveRequestList(generics.ListCreateAPIView): serializer_class = leave_requestsSerializer def get_queryset(self): queryset = leave_requests.objects.all() location = self.request.query_params.get('location') if location is not None: queryset = queryset.filter(testLocation=location) return queryset def perform_create(self, serializer): with transaction.atomic(): try: leave_request = serializer.save() supervisor = leave_request.user.supervisor if supervisor and supervisor.email: self.send_leave_request_email(leave_request, supervisor.email, "Leave Request") except Exception as e: logger.error(f"Error during leave request creation: {str(e)}") raise e def perform_update(self, serializer): with transaction.atomic(): try: leave_request = serializer.instance serializer.save() supervisor = leave_request.user.supervisor if supervisor and supervisor.email: self.send_leave_request_email(leave_request, supervisor.email, "Updated Leave Request") except Exception as e: logger.error(f"Error during leave request update: {str(e)}") raise e def send_leave_request_email(self, leave_request, supervisor_email, subject): try: datetime_start_formatted = leave_request.datetime_start.strftime("Date: %d %B %Y Time: %I:%M:%S %p") datetime_end_formatted = leave_request.datetime_end.strftime("Date: %d %B %Y Time: %I:%M:%S %p") duration = (leave_request.datetime_end - leave_request.datetime_start) days = duration.days hours, remainder = divmod(duration.seconds, 3600) minutes, _ = divmod(remainder, 60) first_name = … -
pyperclip not working on ubuntu 22.04 server
When I was running my install requirement.txt file I got: Warning Using legacy 'setup.py install' for pipfile, since package 'wheel' is not installed Also Pyperclip could not find a copy/paste mechanism for your system Uninstalled it: pip uninstall pyperclip As suggested here, I tried: https://github.com/dependabot/dependabot-core/issues/5478 pip install pyperclip --use-pep517 And pip install wheel pip install pyperclip Tried both solutions at different times, no more warning Then when using my webapp I was getting this error: Pyperclip could not find a copy/paste mechanism for your system Went to this page https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error Tried sudo apt-get install xsel uninstall sudo apt-get install xclip uninstall pip install PyQt5 and PyQt6 uninstall Tried a combo of sudo apt-get install xsel pip install PyQt5 Nono of them worked This is beyond me, was hoping just by adding this commands it would resolve it but feels like something is missing, like the packages are not communicating. On my template I have a submit input tag. This runs a function on my view that parses the user's table and generates a text, I want to use pyperclip to copy this text to the user's clipboard. As a good noob I want to say, 'It runs on my machine', … -
Optimizing Django app for large users requests and dataset in Elastic beanstalk
i have a web app which is hosted in EB and working perfectly but i notice that whenever the users on the website are getting larger or the requests are getting larger the websites slows and even run to Gateway Timeout in fron-end and also Target.Timeout in the instance heath but when the requests on the website or the users on the website get low againn the website will load faster. i have change my Database instance type to db.t3.medium but stiill use to have more upto 99% usage when the website is slow. the EC2 on the EB is running on t3.micro and i have make the auto scaling to have upto 10 instance but sometimes it create upto 8 EC2 instance. Please i am looking for the best way to know what eexactly and why the website laoding slow so i can know what to do next. If you need any other information kindly ask and it will be providded Thanks -
django not showing correct page with url
here is my url code: from django.urls import path from .views import index urlpatterns = [ path('', index), path('join', index), path('create', index), path('join/1', index) ] here is the react code: import React, { Component } from 'react'; import RoomJoinPage from './RoomJoinPage'; import CreateRoomPage from './CreateRoomPage'; import { BrowserRouter as Router, Routes, Route, Link, Redirect } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Routes> <Route exact path='/' element={<p>This is the Home Page</p>} /> <Route path='/join' element={ <RoomJoinPage /> } /> <Route path='/create' element={ <CreateRoomPage /> } /> </Routes> </Router> ); } } and to sum up my issue, I am not seeing the react component "RoomJoinPage" when navigating to /join/1. -
Django is saying that the url doesn't match itself
`from django.urls import path from .views import index urlpatterns = [ path('', index), path('/join', index), path('/create', index) ]` " Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/join Using the URLconf defined in music_controller.urls, Django tried these URL patterns, in this order: admin/ api/ /join /create The current path, join, didn’t match any of these. " someone please tell me how join doesn't match join? thank you. -
How to solve "cannot import name 'livereload_host' from 'livereload' "
I'm getting this error when i enter "python manage.py livereload" after changing all the parameters in django app I'm using django-livereload-server "C:\Users\ADMIN\Desktop\projects\websites\buddiestouronlines>python manage.py livereload Traceback (most recent call last): File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\template\backends\django.py", line 128, in get_package_libraries module = import_module(entry[1]) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\livereload\templatetags\livereload_tags.py", line 4, in <module> from livereload import livereload_host, livereload_port ImportError: cannot import name 'livereload_host' from 'livereload' (C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\livereload\__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ADMIN\Desktop\projects\websites\buddiestouronlines\manage.py", line 22, in <module> main() File "C:\Users\ADMIN\Desktop\projects\websites\buddiestouronlines\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\management\base.py", line 454, in execute self.check() File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\management\base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ADMIN\AppData\Roaming\Python\Python312\site-packages\django\core\checks\templates.py", line 60, in check_for_template_tags_with_the_same_name for module_name, … -
css doesn't work when DEBUG = False django
I'm making 404 page and i made DEBUG to False after that i fix my css of admin and static images but my css file that its in static file doesn't fix my static file static images[folder] template[folder] style.css My _Layout <head>: <head> {% load static %} <link rel="icon" type="image/x-icon" href="{% static 'images/EasyBuyIcon.png' %}"> <link rel="stylesheet" type="text/css" href="{% static 'template/style.css' %}"> <title>{% block title %}{% endblock %}</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> -
Creating API to Login User in Django
The main error here is basically django doesn't recognizing authentication outside admin page and my main login view I'm trying to apply authentication in my api, as a way to study apis building in django, I have this view in my api app: @api_view(['POST']) def loginUser(request): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(): serializer.perform_login() return Response({"Success:", "User logged succesfully"},status=status.HTTP_200_OK) else: print(serializer.is_valid()) return Response({"ERROR":"NO PERMISSION."}, status=status.HTTP_400_BAD_REQUEST) For this view, I have this REST formalizer: class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField() password = serializers.CharField() class Meta: model = User fields = ['username','password'] def validate(self,validated_data): user = authenticate(username=validated_data['username'],password=validated_data['password']) if not user: raise ValidationError("user doesn't exist.") validated_data['user'] = user return validated_data def perform_login(self): user = self.validated_data['user'] print(user) login(user) Consider all the prints in the view and in the formalizer a humble way to understand what's happening with The problem is: No Wrong information, no invalid credential, testing and testing through shell, through postman, through everything. username=x password=y, whatever is the data, being valid credentials or not, error is being returned CHATGPT warned me it could be because of importing the AbstractUser function for the User model and not AbstractBaseModel, BUT it's working fine for user authentication in my main view and in django admin -
Why Celery does not executed tasks scheduled as result of @worker_ready signal execution?
I have a dockerized application running Django (Gunicorn) and Celery (both worker and beat - django_celery_beat - one in each container), with Redis, Nginx and Postgres. The celery process are started after django heathcheck returns OK, to wait all steps needed to start django (migrate, fixtures, add users, collect static etc). I need to schedule tasks according data stored in my model every time the application starts. I'm using the signal worker_ready to do it. The tasks scheduled are saved in django_celery_beat's tables, but non task are executed as expected. docker-compose.yml services: redis: container_name: redis image: redis:latest restart: unless-stopped networks: - redisnet postgres: container_name: postgres image: postgres:latest env_file: - ./.env environment: POSTGRES_USER: ${LOCALDEV_POSTGRES_USER:-postgres} POSTGRES_PASSWORD: ${LOCALDEV_POSTGRES_PASSWORD:-changeme} POSTGRES_DB: ${LOCALDEV_POSTGRES_DB:-db} volumes: - pgdata:/var/lib/postgresql/pgdata ports: - 5432:5432 networks: - postgresnet restart: unless-stopped django: container_name: django build: dockerfile: Dockerfile command: /home/app/web/django-entrypoint.sh volumes: - static_volume:/home/app/web/static expose: - 8000 env_file: - ./.env networks: - postgresnet - redisnet - webnet depends_on: - redis - postgres celery_worker: container_name: celery_worker build: dockerfile: Dockerfile command: /home/app/web/worker-entrypoint.sh env_file: - ./.env networks: - postgresnet - redisnet - webnet depends_on: - redis - postgres - django celery_beat: container_name: celery_beat build: dockerfile: Dockerfile command: /home/app/web/beat-entrypoint.sh env_file: - ./.env networks: - postgresnet - redisnet - webnet … -
django-modeltranslation choice field issue
I'm having a problem using the application django-modeltranslation with a choice field. My model Plan has a field called interval with the following choices: class IntervalChoices(models.TextChoices): DAY = DATE_INTERVALS.DAY, _("Day") WEEK = DATE_INTERVALS.WEEK, _("Week") MONTH = DATE_INTERVALS.MONTH, _("Month") YEAR = DATE_INTERVALS.YEAR, _("Year") class Plan(SoftDeleteBasedMixin): INTERVALS = IntervalChoices interval = models.CharField( choices=INTERVALS.choices, max_length=12, default=INTERVALS.MONTH, help_text="The frequency with which a subscription should be billed.", ) I'm using django-modeltranslation to translate the label and the description of the plan on the admin by directly typing them on the Django Admin, but since those choices are preset I cannot edit them in the Admin. I already used gettextlazy on the choices names and have the translations on the django.po #:plan.py:44 msgid "Day" msgstr "Dia" #:plan.py:45 msgid "Week" msgstr "Semana" #:plan.py:46 msgid "Month" msgstr "Mês" #:plan.py:47 msgid "Year" msgstr "Ano" But when I change both the site or the admin to Portuguese, which is one of the languages I'm translating to the interval is shown in English. This is my translation.py from billing.models.plan import Plan from modeltranslation.translator import TranslationOptions, register @register(Plan) class PlanTranslationOptions(TranslationOptions): fields = ("label", "description") Can someone help me to see how can I proceed with this? -
Select Sub_Category according to its category
class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Sub_Category(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='product') price = models.IntegerField() date_created = models.DateField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=False) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE, default='', null= False) def __str__(self): return self.name now if user add a new product in admin panel all sub_category are shown i want to show sub_category related to its category. @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name'] @admin.register(Sub_Category) class Sub_CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'category'] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'image', 'price', 'date_created', 'sub_category'] raw_id_fields = ("sub_category",) i find this solution but it didn't work -
Subprocess command in Django working for localhost but not on openlitespeed vps server
I have the following function code in views.py of my django project: def word_to_pdf_logic(view_func): def wrapper_function(request, *args, **kwargs): if request.method == "POST" and request.FILES.get('word_file'): word_file = request.FILES['word_file'] # Generate unique temporary file name temp_filename = f"{uuid.uuid4()}.docx" temp_file_path = os.path.join(settings.MEDIA_ROOT, 'word_to_pdf', temp_filename) # Save uploaded Word file to temporary location fs = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'word_to_pdf')) temp_file = fs.save(temp_filename, word_file) word_filename = word_file.name print(f'word_filename : {word_filename}') print(f'temp_filename : {temp_filename}') out_path = os.path.join(settings.MEDIA_ROOT, 'word_to_pdf') # subprocess.call(['lowriter', '--headless', '--convert-to', 'pdf', '--outdir', out_path, temp_file_path]) subprocess.call(['libreoffice', '--headless', '--convert-to', 'pdf', '--outdir', out_path, temp_file_path]) output_pdf_filename = os.path.splitext(word_filename)[0] + '.pdf' output_pdf_path = os.path.join(settings.MEDIA_ROOT, 'word_to_pdf', temp_filename.replace(temp_filename.split('.')[1],'pdf')) print(f'output_pdf_filename : {output_pdf_filename}') print(f'output_pdf_path : {output_pdf_path}') if output_pdf_path: # Serve the PDF file for download with open(output_pdf_path, 'rb') as pdf_file: print(f'Pdf_file {pdf_file.name}') response = HttpResponse(pdf_file.read(), content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename={os.path.basename(output_pdf_path)}' return response else: return HttpResponse("Error converting file to PDF") else: return view_func(request, *args, **kwargs) return wrapper_function Code is woking fine on localhost but the subprocess doesn't work in hosted VPS openlitespeed server on hostinger (os is Ubuntu 22.04). libreoffice and lowriter commands as working on vps if used with terminal to convert word (doc/docx) file into pdf, But if I use it through the django app it gives error. The same code is working on … -
Django React Communication Api
I have a confusion and it is killing be inside. When we work with website that uses react in frontend and Django in backend, what we do is create APIs in django, and then calls the APIs endpoints in our react app to get data. Then populate our frontend with the response data. But my question is, the api can be used by anybody, if he inspects the source code using dev tool. Because, the APIs are accessible by our react app without any authentication. And it should be so. Because, when someone first enters our website without any authentication credentials, we need to render our first webpage (homepage) and API should also be accessible there. But the same way, a hacker can make a lots of request on that server endpoint and thus effect our server, maybe make our server down. The First page of our site is authentication free. Homepage. Homepage is basically not logged in required. So New people try to access it. Its normal. The thing that is not normal is, if someone tries to access that endpoint outside of the browser. We should make sure the request is coming from client browser. Please help me … -
Cannot get Django ModelForm to display neither connect custom HTML form to database
I am currently creating a Django app that is a rental apartments homepage. It is supposed to have a booking form connected to a database. However I can't get the form from forms.py to be displayed on my bookings.html page. I'd appreciate help tons as I have no idea which detail I am missing. This is my code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_name") booking_date = models.DateField(auto_now=True) status = ( ('Requested', 'Requested'), ('Confirmed', 'Confirmed'), ('Cancelled', 'Cancelled'), ) booking_status = models.CharField(choices=status, blank=True, null=True, default='Requested') first_name = models.CharField(max_length=100, unique=True) last_name = models.CharField(max_length=100, unique=True) birth_date = models.DateField() email = models.EmailField(max_length=100, unique=True) phone_number = models.BigIntegerField() address = models.CharField(max_length=200) zip_code = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) booking_object = ( ('Upper Apartment', 'Upper Apartment'), ('Lower Apartment', 'Lower Apartment'), ('Whole House', 'Whole House'), ) booking_item = models.CharField(choices=booking_object) arrival_date = models.DateField() departure_date = models.DateField() guest_nationality = ( ('German', 'German'), ('Other', 'Other'), ) nationality = models.CharField(choices=guest_nationality) passport_number = models.CharField(max_length=100, blank=True, null=True) animals = models.BooleanField(blank=True, null=True) message = models.TextField(max_length=1000) class Meta: ordering=['last_name','first_name'] def __str__(self): return f'Booking: {self.last_name}, {self.first_name}' forms.py from django.forms import forms, ModelForm from .models import Booking class BookingForm(ModelForm): class Meta: model … -
Django add to cart not working with product variation
I am building an e-commerce website where both products with variations and products without variation can be sold. So I have a cart view which adds a product to a cart and creates a cart instance, but it is not working now that I have modified it for products with variation. So if a product has variations, eg colors and sizes, users can select the variations, eg red and XL, and the selected variations show up on this section of product_detail.html: <div id="selected-variations" class="mt-5"> <div class="text-title">Selected Variation:</div> <div class="mt-3"> <span id="selected-color">Color: None</span> / <span id="selected-size">Size: None</span> </div> </div> Now what I want is to take those selected variation values from there and then add the product to the cart with the selected values. But in doing so, the js is not working, I think my cart view logic is fine. It all seemed very easy in the beginning, since I am literally printing the selected variation values from the user above, just was supposed to take those values and create a cart instance with them. But now for some reason my main.js code won't accept it. Is there any way to fix this? My models.py: class Business(models.Model): BUSINESS_TYPE_CHOICES = [ … -
Django - Aggregate of an Aggregation
I am working with DRF and am having issues defining my queryset for use in my view class. Suppose I have three models like so: class ExchangeRate(...): date = models.DateField(...) rate = models.DecimalField(...) from_currency = models.CharField(...) to_currency = models.CharField(...) class Transaction(...): amount = models.DecimalField(...) currency = models.CharField(...) group = models.ForeignKey("TransactionGroup", ...) class TransactionGroup(...): ... I want to create a queryset on the TransactionGroup level with the following: for each Transaction in the transaction group, add an annotated field converted_amount that multiplies the amount by the rate on the ExchangeRate instance where the currency matches the to_currency respectively then sum up the converted_amount for each Transaction and set that on the TransactionGroup level as the annotated field converted_amount_sum An example json response for TransactionGroup using this desired queryset (assumes the exchange_rate.rate = 0.5: [ { "id": 1, "converted_amount_sum": 2000, "transactions": [ { "id": 1, "amount": 1000, "converted_amount": 500, "currency": "USD", }, { "id": 2, "amount": 3000, "converted_amount": 1500, "currency": "USD", }, }, ... ] I can get the annotations to work properly on the Transaction model - but trying to then sum them up again on the TransactionGroup level throws the error: FieldError: Cannot compute Sum('converted_amount'), `converted_amount` is an aggregate My … -
How can I E2E test celery task called in async function?
Although not recommended by the celery documentation CELERY_TASK_ALWAYS_EAGER = True option allows E2E testing where celery task is called inside a function with delay() method. async def wanna_test_function_e2e(): #.... logic dummy_task.delay() #<- modifies some db value The problem is when i mix sync function (for django transaction) in celery task: @celery_app.task # type: ignore[misc] def dummy_task() -> None: with tranaction.atomic(): User.object.get(id=1) <- note that this is sync operation The task runs fine locally, the issue is with the testing. With EAGER option, I am unable to run test: raise SynchronousOnlyOperation(message) kombu.exceptions.DecodeError: You cannot call this from an async context - use a thread or sync_to_async. As EAGER option forces celery to run in a main process but it was invoked in async context. If I follow Celery's guide and use pytest-celery without EAGER option: @pytest.fixture(scope='session') def celery_config(): return { 'broker_url': "memory://", 'result_backend': 'rpc', } @pytest.fixture(scope="session", autouse=True) def celery_register_tasks( celery_session_app, celery_session_worker, socket_enabled ) -> None: celery_session_app.register_task(dummy_task) Now there is huge problem: async def test_dummy_task( self, celery_session_worker, celery_register_tasks, ) -> None: ... import asyncio await asyncio.sleep(10) <- without this the remaining test can run before task runs user = await User.objects.aget(id=1) assert user.is_modified <- without sleep this fails! even worse if I … -
Django-MySQL remote connection trouble
I was trying to connect my app with a remote MySQL database (usually obtained from our hosting through cPanel) and encountered this error. Can anyone help me out? I'm stuck here. Does Django really allow remote MySQL connections? (https://i.sstatic.net/M6KXToRp.jpg) I tried the official documentation for the Django-MySQL connection, but it didn't work for me. I couldn't find any suitable tutorials on YouTube either. -
Adding frequently used context objects to a view in Django
I have several Django apps within a single project. What I am running into is that I often tend to add the same object(s) to the render call that renders a particular screen. In this example below, I have a view that displays a form with a dropdown of categories that you can choose from. Now I need to add these categories every time I display the create.html page. This is simplified, but imagine I have 6 more views that could potentially show the create.html page, all of them have to remember to add the categories array. def createmeeting(request): if request.method == "POST": categories = MeetingCategory.objects.all() // Some error checking, omitted for this example error_msg = "invalid content" if error_msg: return render(request, "meetings/create.html", { "categories": categories, "error_msg": error_msg, }) else: // Create the meeting here, omitted for this example return redirect("/meetings/profile/") else: categories = MeetingCategory.objects.all() return render(request, "meetings/create.html", { "categories": categories }) Is there a better way of handling cases like this? -
Deploying Wagtail on Ionos VPS
I have an Ionos VPS and have a Wagtail site installed on it. It is accessible when I use the command python manage.py runserver (ip address of VPS):8000 and it displays correctly. However, I tried to deploy it but I keep running in to issues. I used nginx and got a 502 error and the logs show that ModuleNotFound error: module 'wagtail' not found and couldn't get any further. I have now reinstalled wagtail on a freshly made image on my VPS and not sure what to do next. -
Why is DATA_UPLOAD_MAX_MEMORY_SIZE not working? Django, TinyMCE text field
I have a DATA_UPLOAD_MAX_MEMORY_SIZE = 209_715_200 FILE_UPLOAD_MAX_MEMORY_SIZE = 209_715_200 in settings. However, when im trying to add 5 images in a tinymce text field (the total weight of the images is > 2.5 mb) i'm getting error: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. How could i fix it? settings.py Django settings for mainApp project. Generated by 'django-admin startproject' using Django 5.0.3. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path from django.contrib import staticfiles from django.urls import reverse_lazy from dotenv import load_dotenv, find_dotenv import os # 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/5.0/howto/deployment/checklist/ load_dotenv(find_dotenv()) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["olimpiadnik.pythonanywhere.com", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'tinymce', 'mainApp', 'portfolio', ] TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking … -
How to implement reload-on-rss is not available in mod_wsgi?
In uwsgi, reload-on-rss helps to prevent the Django server from running into OOM. How do you implement reload-on-rss on mod_wsgi in Django? I would like the Django server to reload after a certain memory limit.