Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django add filtes in template is not work expectedly
I am a Django and Python beginner, and I encountered a problem while using Django. I hope to use a filter in the template to get the string I need, but the result below is not what I expected. # filter definition @register.filter def to_class_name(obj): return obj.__class__.__name__ # HTML template for UpdateView (This template will be used by multiple models.) # object = Order() {{ object|to_class_name }} #reulst: Order {{ 'wms'|add:object|to_class_name }} #result: str, expect: object I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it. {{ 'wms'|add:(object|to_class_name) }} #cause SyntaxError Is there any way to solve this problem? Or is there a better way to determine the page data I need to output based on the model class when multiple models share one template? Thank you all. -
Download files uploaded to the "static" folder - Django
I need the .wav file that is created in the "static" folder to be able to be downloaded via a link inserted via HTML or viewed via FileResponse. I tried things like: <a href="{% static 'files/{{ filename }}' %}">Download: {{ filename }} </a> But this didn't work because it doesn't find the resource. -
Django: "Select which login to update" dialog
I am creating a django app that has a part to change user's password with a form. The form gets old_password & new_password from user and I handle that in views.py file. My problem is when I submit the form, browser showing me a dialog that says "Select which login to update" and listed the django.contrib.auth.models.User's data. I didn't write anything in my views.py file. you can see that bellow. views.py @login_required def profile_home(request): user = User.objects.get(username=request.user.username) # Find original user object if request.method == 'POST': if request.POST.get('password'): form_change = ChangePasswordForm(request.POST) if form_change.is_valid(): data = form_change.cleaned_data return redirect('panel:login_home') else: # something for other form else: # GET return Dialog image: -
To render contents for a website frontend from django backend
Im going to build a website in angular and I need to render the contents from the backend on MySQL I need help for designing a data model for the website How to plan the data model for content management for a website from the backend. I need a clear explanation for database structure. -
How to change status field automatically from 1 to 0 when end_time is reached
This is my Auction model. class Auction(models.Model): auction_id = models.AutoField(primary_key=True) crop = models.ForeignKey(Crop, on_delete=models.CASCADE) image = models.ImageField(upload_to="crop-image") farmer = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'user_type': 'farmer'}) creation_time = models.DateTimeField(auto_now_add=True) end_date = models.DateField() end_time = models.TimeField() status = models.BooleanField(default=True) qty = models.IntegerField() unit = models.CharField(max_length=10, choices=[('kg', 'Kilograms'), ('tonne', 'Metric Tons'), ('bushel', 'Bushels'), ('crate', 'Crates')]) hammer_price = models.IntegerField() description = models.CharField(max_length=200) payment = models.BooleanField(default=False) class Meta: verbose_name_plural = "Auctions" def __str__(self): return self.crop.title When combined end_date and end_time is reached, status which is by default set to 1 on auction creation should be changed to 0. -
Python Django HTMLCalendar How To Set First Weekday To Sunday
Like title states goal is to get the weeks in the calendar to lead with Sunday as opposed to Monday like the below shows. I know calendar.setfirstweekday(calendar.SUNDAY) should be able to do the trick here. I just can't figure out how/where to add it in this code or if there's a different method needed. Won't waste your time with the dumb things I've tried to get Sunday to lead the week in the calendar. Current Code That Displays Monday Week Start: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, group=None): self.year = year self.month = month self.group = group super(Calendar, self).__init__() def formatday(self, day): d = '' if day != 0: return f"<td name='date-event-input' id={date(year=self.year, month=self.month, day=day)}><span " \ f"class='date'>{day}</span><ul>{d}</ul></td>" return '<td></td>' def formatweek(self, theweek): week = '' for d, weekday in theweek: week += self.formatday(d) return f'<tr> {week} </tr>' def formatmonth(self, withyear=True): cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar" id="calendar-table-id">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week)}\n' return cal Appreciate any help -
Error when trying to get SSL Lets Encrypt in Apache Django web app ubuntu oc
I wanted to get the free ssl and so i installed the lets encrypt. I was aware of the errors wirh WSGI module and duplicate and solved them successfully. But when i go to the adress isabelcanvas.ru it doesnt load. There is no indicators in error.conf log. No indicators in apache2 service. It just doesnt fucking work. And btw when i input isabelcanvas.ru in my url it successfully does the https:// response but says its not safe. Here are my files: 000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName isabelcanvas.ru DocumentRoot /var/www/html <Directory /var/www/html/isabelcanvas/isabelcanvas> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess isabel python-path=/var/www/html/isabelcanvas python-home=/var/www/html/myenv WSGIProcessGroup isabel WSGIScriptAlias / /var/www/html/isabelcanvas/isabelcanvas/wsgi.py WSGIApplicationGroup %{GLOBAL} Alias /static /var/www/html/static <Directory /var/www/html/static> Require all granted </Directory> Alias /media /var/www/html/media <Directory /var/www/html/media> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =isabelcanvas.ru RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> 000-default-le-ssl.conf: <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName isabelcanvas.ru DocumentRoot /var/www/html <Directory /var/www/html/isabelcanvas/isabelcanvas> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess sslisabel python-path=/var/www/html/isabelcanvas python-home=/var/www/html/myenv WSGIProcessGroup sslisabel WSGIScriptAlias / /var/www/html/isabelcanvas/isabelcanvas/wsgi.py WSGIApplicationGroup %{GLOBAL} Alias /static /var/www/html/static <Directory /var/www/html/static> Require all granted </Directory> Alias /media /var/www/html/media <Directory /var/www/html/media> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLCertificateFile /etc/letsencrypt/live/isabelcanvas.ru/fullchain.pem SSLCertificateKeyFile … -
Django app -> Elastic Beanstalk instance deployment instance - Site hanging
I've been following this tutorial to deploy a Django app on AWS EB instance, and got to the eb deploy stage. My log files seem to imply that everything is ok, except the health checker raises some issues: ---------------------------------------- /var/log/nginx/access.log ---------------------------------------- 172.31.2.9 - - [28/Mar/2024:17:00:57 +0000] "GET / HTTP/1.1" 400 154 "-" "ELB-HealthChecker/2.0" "-" 172.31.34.136 - - [28/Mar/2024:17:01:02 +0000] "GET / HTTP/1.1" 400 154 "-" "ELB-HealthChecker/2.0" "-" 172.31.2.9 - - [28/Mar/2024:17:01:12 +0000] "GET / HTTP/1.1" 400 154 "-" "ELB-HealthChecker/2.0" "-" However, I go to the site URL it just hangs and then stops. Could this be because the allowed host url is http and not https, which is not working with Firefox? The loading page issues state: The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer’s network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web. I am quite new to web app development, so some pointers in the right direction would be appreciated. Happy to provide more info on request. -
Taking field from another model in serializers
Now Im doing a pet project about sports, and I have a TrainZone and TrainZoneImage model, and in serializers I need to display the image field from the TrainZoneImage model in TrainZoneSerializer field images should be []where circled in black `models.py from django.db import models from ckeditor.fields import RichTextField class TrainZone(models.Model): title = models.CharField(max_length=100, verbose_name='Название') description = RichTextField(verbose_name='Описание') def __str__(self): return self.title class Meta: verbose_name = 'Тренировочная зона', verbose_name_plural = 'Тренировочные зоны' class TrainZoneImage(models.Model): trainzone= models.ForeignKey(TrainZone, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to='media/') def __str__(self): return self.trainzone.title` ` serializers.py from rest_framework import serializers from .models import TrainZone, TrainZoneImage class TrainZoneImageSerializer(serializers.ModelSerializer): class Meta: model = TrainZoneImage fields = ('id', 'images') # Измените поля по необходимости class TrainZoneSerializer(serializers.ModelSerializer): images = TrainZoneImageSerializer(many=True, read_only=True) class Meta: model = TrainZone fields = ('id', 'title', 'description', 'images') class TrainZoneValidatorSerializer(serializers.ModelSerializer): class Meta: model = TrainZone fields = '__all__' ` I tried to take images from TrainZoneImage by making TrainZoneImageSerializer and taking field images in TrainZone Serializer -
Django admin csrf token not set
I have a Django project working locally with login to the admin portal working. Once the project has been deployed to our development environment the pages that do not require CSRF authentication are viewable, but the admin portal returns a CSRF token error when attempting to login. Error received: CSRF cookie not set The project is meant to be deployed to a subdomain (ie https://project.myapp.com) with the development/staging version deployed to a different subdomain (https://project.dev.myapp.com). Subset of the settings.py: ALLOWED_HOSTS = ['*'] CSRF_COOKIE_SECURE = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_object_actions', ] MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Originally I assumed that the issue was due to the project being deployed on a subdomain and followed the documentation for csrf and added the CSRF_TRUSTED_ORIGINS = ['https://*.myapp.com'] to the settings but the issue persists. I also tried setting the CSRF_COOKIE_DOMAIN setting to either .myapp.com or to .dev.myapp.com but continue to see the same issue. I had also seen people mention the django.template.context_processors.csrf option to add to the TEMPLATES context_processors and tried that, but this also had no effect. When looking at the request to the /admin/login view, a csrfmiddlewaretoken is included, … -
Get json field value in sqlite model from view django
I'm trying to get a value from correct_answer key in a JSON field inside a model that is previously fetched from an external API. That value is used in a conditional to redirect (right answer) or render a new question (wrong answer). When I tried to access the value as a dictionary from a mocked version of the model my test complains with a 'DefferedAttribute' object is not subscriptable. We could say that data isn't fetched from the external API but I checked that the mocked model was working. This is my code: from django.shortcuts import redirect, render, HttpResponse from django.template import loader from .forms import QuestionForm, QuestionLevelForm from urllib.request import urlopen, URLError from .models import Log def process_question(request): form={}; if 'level' in request.POST: url = 'http://opentb.com/api.php?amount=1&category=9&difficulty='+request.POST['level']+'&type="multiple"' try: response = urlopen(url) except URLError as e: if hasattr(e, 'reason'): HttpResponse('Reaching server failed: ', e.reason) elif hasattr(e, 'code'): HttpResponse('Couldn\'t fufill request', e.code) else: question = response["results"][0] form = QuestionForm(question) Log.question = question #How to test this works? Log.save(update_fields=['question']) return render(request, "log/question.html", {"question": question, "form": form}) elif 'answer' in request.POST: if request.POST["correct_answer"] == Log.question['correct_answer']: #This is the conditional I need return redirect('/log/reward') else: notification = "Wrong answer" level = QuestionLevelForm return render(request, "log/question.html", … -
why group_send() not publishing messages
I am working with django channels. I had a consumer class , connection to it also established . but group_send() messages are not received . here is consumer class EchoConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() logger.info(f" echo echo.. ") self.channel_layer.group_add("ks", self.channel_name) async def disconnect(self, close_code): self.channel_layer.group_discard("ks", self.channel_name) logger.info(f"ti ti tiiin") self.close() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] logger.info(message) await self.channel_layer.group_send( "ks", { "type": "group.message", "message": message, }, ) async def group_message(self, event): logger.info(event["message"]) message = event["message"] await self.send(text_data=json.dumps({"message": message})) here is channel layer configuration CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["redis://" + REDIS_HOST + ":" + REDIS_PORT + "/1"], }, }, } # chaches CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}/3", # Use a different database (e.g., 1) "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, }, } I also checked if there a problem in my channel layer or not . There are no problems too . (env) komal@phoenix:~/Documents/gle/server$ python manage.py shell Python 3.11.4 (main, Dec 7 2023, 15:43:41) [GCC 12.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from channels.layers import get_channel_layer >>> channel_layer = get_channel_layer() >>> channel_layer.group_send("ks" , {"message":"I am working"}) <coroutine object RedisChannelLayer.group_send at … -
Want to retrieve a Foreign Key value instead of the whole object with django-rest-framework serializers
I'm using the Django rest framework to create an API. I have the following models: (https://i.stack.imgur.com/oasDY.png)](https://i.stack.imgur.com/oasDY.png) models.py class Faculty(models.Model): name = models.CharField(max_length=25, unique=False, null=False, blank=False) email = models.EmailField(max_length=25, unique=True, null=False, blank=False) class Course(models.Model): name = models.CharField(max_length=25, unique=True, null=False, blank=False) faculty_name = models.ForeignKey(Faculty, on_delete=models.CASCADE, related_name='faculty_name') end_date = models.DateField() def __str__(self): return self.faculty_name # @property # def faculty_name(self): # return self.faculty.name To create a serializer serializers.py class FacultySerializer(serializers.ModelSerializer): class Meta: model = Faculty fields = '__all__' class CourseSerializer(serializers.ModelSerializer): # faculty_name = serializers.SlugRelatedField(slug_field='name', read_only=True) # faculty_name = serializers.ReadOnlyField(source='faculty.name') print(Faculty.objects.all().values('name')) class Meta: model = Course fields = ('name', 'faculty_name', 'end_date') To create rest services using the following views: views.py class Course(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = CourseSerializer queryset = Course.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class Faculty(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = FacultySerializer queryset = Faculty.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Getting the Faculty object while accessing the /course/ endpoint as shown in the image. want to get the faculty name instead of the Faculty object in the post method's form fields(dropdown) I have tried the below codes: 1)faculty_name = … -
multipart/form-data not setting in MultipartEncoder (python)
I am trying to upload a file to a server and it only accepts the file in multipart/form-data format so when i try to send it by encoding like: m = MultipartEncoder( fields={'document': json.dumps(metadata), 'files': (file_name, open(file_path,'rb'),'multipart/form-data')} ) headers = {'content-type': m.content_type} response = requests.post(url, headers=headers, data=m) It still shows the error: '{"success":false,"errorMsg":"Content type 'application/octet-stream' not supported"}' How do i resolve this when i have explicitly set the content-type to multipart/form-data? -
request.FILES in Django
I need the following code to work as written: testo = request.POST.get('testo') lang = request.POST.get('lang') audio = request.FILES['audio'] fs = FileSystemStorage() filename = fs.save(audio.name, audio) uploaded_file_url = fs.url(filename) The problem is that for request.FILES the form is required to be - enctype="multipart/form-data" - My form instead is like this: <form action="{% url 'app' %}" method="post"> {% csrf_token %} <textarea name="testo" id="" cols="30" rows="10"></textarea> <label for="lang">Scegli lingua:</label> <select name="lang" id=""> <option value="it">Italiano</option> <option value="en">Inglese</option> <option value="es">Spagnolo</option> </select> <input type="file" name="audio" id=""> <button type="submit">INVIA</button> </form> With my form I can get the text to work, but I can't get request.FILES to work!!! Any solution? Unfortunately I can't with my form. I need it as is, but I need something that allows me to make text and files work in Django -
Why does Django add 1 second to the lifetime of a cookie?
I'm trying to implement JWT authentication using django-graphql-jwt on the backend, and nuxt3 for the frontend. My token and refresh_token are stored in cookies, and I wrapped the GraphQLView in a jwt_cookie decorator that automatically checks for the existence of the jwt token in the cookie, as well as its validity. In general, everything works great. When I send an authorization request, the backend returns me the "Set-Cookie" headers for JWT and JWT_REFRESH_TOKEN with an expiration date that automatically deletes them as soon as they become invalid, which saves me a lot of code/logic on the frontend. However, there is one very unpleasant thing - Django adds 1 second to the cookie lifetime for some reason in the set_cookie function, and it ruins everything. Here is the Django code: def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_naive(expires): expires = timezone.make_aware(expires, datetime.timezone.utc) delta = expires - datetime.datetime.now(tz=datetime.timezone.utc) # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). # Here's what I mean ↓↓↓ delta += datetime.timedelta(seconds=1) … -
Django using Subquery in annotate: How to fetch all rows that match the condition of filtering
I have two models with M2M field. Because there wont be any update or deletion (just need to read data from db) I'm looking to have single db hit to retrieve all the required data. I used prefetch_related with Prefetch to be able to filter data and also have filtered objects in a cached list using to_attr. I tried to achieve the same result using annotate along with Subquery. but here I can't understand why the annotated filed contains only one value instead of a list of values. let's review the code I have: some Routes may have more than one special point (Point instances with is_special=True). models.py class Route(models.Model): indicator = models.CharField() class Point(models.Model): indicator = models.CharField() route = models.ManyToManyField(to=Route, related_name="points") is_special=models.BooleanField(default=False) views.py routes = Route.objects.filter(...).prefetch_related( Prefetch( "points", queryset=Point.objects.filter(is_special=True), to_attr="special_points", ) ) this will work as expected but it will result in a separate database querying to fetch the points data. in the following code I tried to use Subquery instead to have a single database hit. routes = Route.objects.filter(...).annotate( special_points=Subquery( Point.objects.filter(route=OuterRef("pk"), is_special=True).values("indicator") ) the problem is in the second approach will have either one or none special-point indicator when printing route_instance.special_points even if when using prefetch the printed … -
Why does the ImageGalleryBlock in wagtail-crx/coderedcms return no images?
Wagtail-CRX installs with a pre-defined StreamField ImageGalleryBlock that allow a user to select a Collection of images that are then output to the page along with a modal pop-up structure. In models.py of my app I have created the image_gallery variable like this image_gallery = StreamField([ ('image_gallery', ImageGalleryBlock()), ], verbose_name="Choose images for the gallery", null=True, blank=True, default="", use_json_field=True ) FieldPanel("image_gallery"), This worls fine. The FieldPanel adds the Collection choice block to the page edit form. However, the images in the chosen Collection never appear on the page using any of the possible methods for calling the block into the page template e.g. {% for block in page.image_gallery %} <section>{% include_block block %}</section> {% endfor %} The include here calls in the block using the template image_gallery_block.html - the structure for the modal pop-up is rendered on the page but there no images appear to populate it with. Inside the image_gallery_block.html template the first line is {% get_pictures self.collection.id as pictures %} where get_pictures is a function that should pass the data from the Collection objects into the variable pictures and they should be iterated over in the subsequent template html thus {% if pictures %} {% for picture in pictures … -
Getting 404 error when trying to use slugs in Django
I'm new one in Django and trying to develop website. What I need is to use slugs in URLs in Django. When I use id's everything works well. I have done the following steps: I have a model Posts with . class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, default='') content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) photo = models.ImageField(upload_to='post_photos/', blank=True) # ImageField для хранения изображений created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=False) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.photo: # Если поле photo пустое, генерируем случайный путь к изображению random_image_path = get_random_image_path() self.photo = random_image_path # Привязываем случайное изображение к объекту Post super().save(*args, **kwargs) def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) I have written the following in my urls.py and views.py path('fitness/<slug:post_slug>/', views.show_post, name='post'), def show_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug) return render(request, 'show_post.html', {'post': post}) and this works well. But then I try to make some amendmens to use slugs. The following ones: def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) def show_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug, category__slug='fitness') return render(request, 'show_post.html', {'post': post}) And I get the following error Page not found (404) “/home/tkzeujpw/blog/fitness/fitness-post-1” does not exist Request Method: GET Request … -
How to supress naive datetime warning in django
In django whenever i use Datetime.datetime.now() a runtime warning : enter code here received a naive datetime (2024-03-28 16:18:54.096253) while time zone support is active is displayed , i want to supress this warning or basically tell django to ignore this warning, is there a change i can make in the settings file to tell django to ignore the naive datetime field warning eg: b = User.objects.create() b.start = datetime.datetime.now() b.save() runtime warning : received a naive datetime (2024-03-28 16:18:54.096253) while time zone support is active tried : setting USE_TZ = False in settings.py -
How to configure django 5.0.3 to be able to use private/public media files on AWS - s3
today I feel very frustrated , after 3 days trying to implement django using amazon s3 with media file in private mode. In the past my apps has been configured using the following link bellow and always work fine: https://unfoldadmin.com/blog/configuring-django-storages-s3/ From now for some reasson is not possible to reach the goald (some media files need to be private) I undestand that from django 4.2 exist new way to configure storages but still you are able to continue with old option, To be honest I do not sure if this will be the cause of the problem: https://docs.djangoproject.com/en/5.0/ref/settings/ { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } versions: Phyhon: 3.12.2 asgiref==3.8.1 boto3==1.34.72 botocore==1.34.72 Django==5.0.3 django-storages==1.14.2 jmespath==1.0.1 python-dateutil==2.9.0.post0 s3transfer==0.10.1 six==1.16.0 sqlparse==0.4.4 tzdata==2024.1 urllib3==2.2.1 Configuration on AWS: Object Ownsership:ACls enabled Block all public access: off Bucket policy: { "Version": "2012-10-17", "Id": "Policy_id", "Statement": [ { "Sid": "my_sid", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::mybucket_name/*" } ] } Note: I have to say that appear the ACLs is working because after uploading a private file if you try to retrieve the URL of the content , the API will generate a long URL that expire after a few minutes, … -
How notification works [closed]
Need an notification when a registration is complete or a new user is created on user side.This notification is shown in admin side.This is a REACT project and the backend is provided through django REST Api. I created a seperate db for notifications ,it is not working automatically when a registration is completed. -
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response, nginx, django, waitress
I'm using nginx server to serve static React js files and waitress server for django rest framework with 0.0.0.0:8000 as address to serve api's. I'm using nginx as a reverse proxy for django. Even though i have modified django setting to allow all origins and modified nginx conf file to include cross origin headers and pre-flight headers. I'm still getting an error saying "Access to XMLHttpRequest at 'http://15.295.156.60:8000/core/profile/profile/' from origin 'http://15.295.156.60' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response." I tried modifying the nginx conf file to include cross origin headers and pre-flight headers for the django reverse proxy. Modified the django settings to allow all origins. I want to handle this error "Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response." these are my django settings " CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://192.168.56.1:80', 'http://localhost:3000', 'http://*', # Add any other origins that you want to allow here ]" , This is my frontend request " const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, });" , This is how i'm configuring … -
migrate error : ...No migrations to apply
I made some changes in the models from my apps and then entered makemigrations and migrate in the terminal. PS C:\Users\USER 1\frist project\website> python manage.py makemigrations home No changes detected in app 'home' PS C:\Users\USER 1\frist project\website> python manage.py migrate ?[36;1mOperations to perform:?[0m ?[1m Apply all migrations: ?[0maccounts, admin, auth, cart, contenttypes, home, order, sessions, taggit, thumbnail ?[36;1mRunning migrations:?[0m No migrations to apply. -
Edit Form in Modal Window Django
I am trying to do an Edit form in the modal window. The problem is that I cannot pass the form into the modal window and show the modal. I tried to do it with HTMX but it is not what I am looking for. forms.py class SettingsForm(forms.ModelForm): code = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) value = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = KrnListValue fields = ['code', 'value', 'description'] views.py def edit_setting(request, pk): entry = get_object_or_404(KrnListValue, pk=pk) if request.method == 'POST': form = SettingsForm(request.POST, instance=entry) if form.is_valid(): form.save() else: form = SettingsForm(instance=entry) settings.html <button hx-get="{% url 'edit_setting' pk=setting.pk %}" hx-target="#dialog" class="btn btn-primary" style="margin-right:5px;"> save </button> <div id="modal" class="modal fade"> <div id="dialog" class="modal-dialog" hx-target="this"> # PASS IT HERE </div> </div> I was doing something like this. But still it didnt work. I suppose in edit_setting I can return HttpResponce. But didnt figure out how to do that.