Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django: models.Model.objects.filter(pk) return nothing [closed]
I started learn Django framework. Following the official tutorial I have model Question that is derived from django.db.models.Model After all migrations, In views.py I created function called detail that is supposed to show me question by quest_id here is the code def detail(request, quest_id): by_id = Question.objects.filter(id=quest_id).first() by_index = Question.objects.all()[quest_id] response = f"Via filter \"{by_id}\" Via index \"{by_index}\"" return HttpResponse(response) In urls.py I added corresponding path to urlpatterns Next I added two records of Question to my database, but when I tried to Question.objects.filter(quest_id).first(), I've always get None even if I have Question with id=quest_id Here Is result of detail for id quest_id -
Index file shown but not the live website
enter image description hereI have deployed my website in the cpanel of namecheap but it shows the following problem in the given image. How can i fix it? I tried to change the .htacces file but it still did not work, please help me because i cannot fix this porblem by myself. -
django modelForm : dynamically adjust field according to related field
I've been working on a hospital project exercice and am wondering how to render a given field (model "doctor") according to a speciality selection: user has to select first a medical speciality and according to that one, the doctor's list will be dynamically updated. How can I design my modelForm to achieve that goal? Do I need some javascript embedded in the template file? Here is the related code in my django project: # models.py class Speciality(models.Model): specialite_id = models.AutoField(primary_key=True) nom = models.CharField(max_length=50, unique=True, verbose_name="Spécialité") def __str__(self): return f"{self.nom}" class Doctor(CustomUser): medecin_id = models.AutoField(primary_key=True) matricule_medecin = models.CharField(max_length=50, unique=True) specialite = models.ForeignKey(Specialite, on_delete=models.CASCADE) admin = models.ForeignKey(Administrateur, on_delete=models.SET_NULL, null=Tru e, blank=True) def __str__(self): return f"Dr {self.nom} {self.prenom}, spécialité : {self.specialite}" # forms.py class CreateSejour(forms.ModelForm): class Meta: model = Sejour fields = '__all__' widgets = {'date_entree': forms.SelectDateWidget(years=range(2015, 2025)), 'date_sortie': forms.SelectDateWidget(years=range(2015, 2025)), 'motif': forms.Textarea()} I don't see how to tackle this situation : do I have to implement some logic inside the modelForm or in my view? Thanks for your help. De716 Actually i'm stuck to that stage, my django experience doesn't allow me to address this and I have no experience in javascript -
Why do I have a Flutter web CORS issue despite having set CORS in django backend
I'm developing a Flutter web application that needs to make requests to a Django backend. However, I'm encountering a CORS error when I try to make a request. The error message is: Access to XMLHttpRequest at '<API_URL>' from origin 'http://localhost:63730' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I've already set up CORS in my Django settings as follows: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True Despite this, I'm still getting the same CORS error. Interestingly, I have other applications built with React and Vue that are able to make requests to the same Django backend without encountering any CORS errors. I'm not sure why my Flutter web application is encountering CORS errors while my React and Vue applications are not. Any help would be greatly appreciated. -
my Django registration page redirect isn't working
i'm trying to make a registration page for my Django project. When i compile the registration form it gives me the error in the image because it tries to go to this path (he doubles users/register): localhost/users/register/users/register/. How can i fix it? this is my code: Error image: users/view.py: def register_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('homepage') else: form = UserCreationForm() return render(request, "users/register.html", {"form": form}) users/urls.py: urlpatterns = [ path('register/', views.register_view, name="register"), ] main/views.py: def homepage(request): return render(request, 'homepage.html') main/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name="homepage"), path('music/', include('music.urls')), path('users/', include('users.urls')), ] -
Kubernetes Persistent Volume not shared when uploading a file with Django and Nginx
I created 2 persistant volumes, one for static files and other for media files. The static files one works just fine, nginx serves the data. For media volume, nginx does not see the uploaded file and the volume content does not update. The nginx conf is fine. The location works but volume does not contain the uploaded file. This is my media pv and pvc: apiVersion: v1 kind: PersistentVolume metadata: name: mediafiles-pv spec: storageClassName: manual capacity: storage: 1Gi accessModes: - ReadWriteMany hostPath: path: "/usr/src/app/backend/media" apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mediafiles-pvc namespace: default spec: storageClassName: manual accessModes: - ReadWriteMany resources: requests: storage: 1Gi volumeName: mediafiles-pv This is my deployment for backend (django): apiVersion: apps/v1 kind: Deployment metadata: name: backend labels: app: backend spec: replicas: 1 selector: matchLabels: app: backend template: metadata: labels: app: backend spec: volumes: - name: staticfiles persistentVolumeClaim: claimName: staticfiles-pvc - name: mediafiles persistentVolumeClaim: claimName: mediafiles-pvc containers: - name: backend image: loopedupl/backend:latest imagePullPolicy: Always ports: - containerPort: 8000 volumeMounts: - name: staticfiles mountPath: "/usr/src/app/backend/static" - name: mediafiles mountPath: "/usr/src/app/backend/media" and for nginx: apiVersion: apps/v1 kind: Deployment metadata: name: nginx labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: volumes: - name: … -
Pass requests from host to container with domain socket
I have uwsgi running on a docker container. Nginx running on host. Current setup: ;uwsgi.ini http-socket=:8080 With docker, I've forwarded the host's 8080 port to containers 8080 port. Nginx is configured like server { listen 443 ssl http2; server_name domain.example.com; location / { proxy_pass http://127.0.0.1:8080; } } This works fine, only problem: my port 8080 is exposed and I can directly request the port on the public IP. I should be able to use domain sockets to mitigate this, but I don't know how the set up would look like. Here's my half attempt: ; uwsgi.ini in container socket=/path/uwsgi.sock # nginx on host upstream prod_server { server unix:///path/uwsgi.sock; } server { listen 443 ssl http2; server_name example.domain.com; location { uwsgi_pass pror_server; } } Since nginx is in host, it will look for the path on host server, is adding the socket as a volume the right way to go? Is there another best practice? How would you recommend the setup? Thank you.