Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add google domain to Django app hosted in AWS EC2 Ubuntu
Add custom domain name to a Django application that is hosted in AWS EC2 - Ubuntu I deployed the Django application from GitHub to AWS EC2 server which is based on Ubuntu. After deployment, the app is able to run on my local. I also added the custom google domain name into the allowed hosts from Django settings.py and redeployed the changes to the virtual environment but the custom google domain still did not work. Is there anything else that I need to do to successfully launch the custom google domain? Your suggestions and insights are greatly appreciated. Thank you! -
Error on railway with Django projectNixpacks build failed
error nixpacks Error on railway with Django project Nixpacks build failed i made all steps following this video https://www.youtube.com/watch?v=NUqtNglEcCU my files files i tried on Railway and Vercel, yesterday i was having the error ModuleNotFoundError: No module named 'widget_tweaks', so i tried on Vercel and failed, so when i go back to Railway the error changed to Nixpacks build failed requirements.txt -
How safe is setting consumer_timeout to long values like 10years
Im guessing it's there for a reason, but I can't seem to find any answer to this question. In short I have a django app where users get set badges that months or even years down the line need to be auto removed for which I use celery. My question is will setting consumer_timeout to large values pose a risk for those actions to not be performed or performed early/late (mind you a delay of even a few hours shouldn't be a big deal for long duration tasks) -
Django Python Arabic Search
I have fields name and author which are in Arabic and I want to search on them with a keyword keyword = request.POST.get('search', '') books = Book.objects.filter(Q(name__icontains=keyword)).order_by('category', 'code') The problem is that django treats the two letters 'أ' and 'ا' as two different letters while users would expect that they are interchangeable in search and both should give the same output. Is there a way I can treat them as one letter without replacing them in variations of the code? like this keyword_var1 = keyword.replace('أ', 'ا') Also the same problem with the letters 'ى' and 'ي' -
Why is {% load static %} not working in PyCharm for Django?
[HTML file]setting.py file I am trying to add CSS and JavaScript to html file in Django but getting unexpected token error when I entered {% load static %}.so getting web page without applying CSS. I also run the >python manage.py collectstatic -
Django : Forbidden CSRF cookie not set.)
I''m using Django with pyJWT to generate JWT for a simple login. Although it previously worked well now I'm getting Forbidden (CSRF cookie not set.) error there is no CSRF_COOKIE_SECURE in the setting.py url.py in app urlpatterns = [ path('login' , LoginView.as_view()), path('user' , UserView.as_view()) ] main url.py urlpatterns = [ path('', admin.site.urls), path('api/' , include('users.urls')) ] view.py class LoginView(APIView): def post(self,request): username = request.data['username'] password = request.data['password'] user = User.objects.filter(username = username).first() if user is None: raise AuthenticationFailed("User not found") if not user.check_password(password): raise AuthenticationFailed('Incorrect Password') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload , 'secret' , algorithm='HS256' ) response = Response() response.set_cookie(key='jwt' , value=token , httponly=True) response.data = { 'jwt': token } return response settings.py MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", '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', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True for clarification this is the API url I used: http://localhost:8000/api/login when i use postman to call API I'm getting this error : Forbidden (CSRF cookie not set.): /api/login [27/May/2023 18:53:53] "POST /api/login HTTP/1.1" 403 2870 when i use axios post I'm getting this error : Forbidden (Origin checking failed - http://localhost:5173 does not match any trusted origins.): … -
Difference between self.user and self.user_id
I am a beginner of learning Django. When I read the code below, I have a few of questions. from django.db import models from django.contrib.auth.models import User class Friendship(models.Model): from_user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='following_friendship_set', ) to_user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='follower_friendship_set', ) created_at = models.DateTimeField(auto_now_add=True) class Meta: index_together = ( ('from_user_id', 'created_at'), ('to_user_id', 'created_at'), ) unique_together = (('from_user_id', 'to_user_id'), ) def __str__(self): return '{} followed {}'.format(self.from_user_id, self.to_user_id) Why should use self.from_user_id and self.to_user_id not self.from_user and self.to_user in the str function? What is the difference? 2. from django.db import models from django.contrib.auth.models import User from tweets.models import Tweet class NewsFeed(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) tweet = models.ForeignKey(Tweet, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: index_together = (('user', 'created_at'), ) unique_together = (('user', 'tweet'), ) ordering = ('user', '-created_at') def __str__(self): return f'{self.created_at} inbox of {self.user}: {self.tweet}' Why should use self.user and self.tweet not self.user_id and self.tweet_id in the str function above? Why does the author use id but not use id in this part? I am so confused. What is the difference between self.user and self.user_id? -
keyError:'etag' while uploading staticfiles to cloudinary from django
I have uploaded statifiles on cloudinary from django ,but when i am uploading again the samefiles with some changes it just through this error KeyError:'etag' -
Getting Connection reset by peer while debugging django app
I am debugging django app running inside docker container on my laptop. I attached vscode to the docker container and started the django app in debug mode. I have built a rest endpoint and put breakpoint on the first line in the REST endpoint. Now, I accessed that rest end point from postman REST client. It hit the breakpoint. Then, I stepped through the whole rest end point. It returned a desired JSON response, which I obtained in postman window. So the rest endpoint point seem to work fine, following the desired steps and returning the desired response. However after I receive the response in the postman window, a few seconds, vscode prints following in the same terminal window in which debugging is running: Exception happened during processing of request from ('10.0.5.4', 52994) Traceback (most recent call last): File "/usr/local/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/local/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/usr/local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer Above stack trace does not list any … -
Wagtail - Switching from InlinePanel to FieldPanel results in errors
My wagtail blog was based on a now very out of date tutorial, however it wasn't until Wagtail 5.0 that the features I was using/way of doing things have finally been deprecated. For the most part, following the 'Upgrade Considerations' listed in the documentation, I've been able to make changes and everything has gone smoothly. The problem I have encountered is in switching an InlinePanel to a FieldPanel. This is the code from my models.py to define a blog category: class PostPageBlogCategory(models.Model): page = ParentalKey( "myblog.PostPage", on_delete=models.CASCADE, related_name="categories" ) blog_category = models.ForeignKey( "myblog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages" ) panels = [ FieldPanel("blog_category"), ] class Meta: unique_together = ("page", "blog_category") @register_snippet class BlogCategory(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) panels = [ FieldPanel("name"), FieldPanel("slug"), ] def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" And this is the section of my 'Post Page' model which allowed for a user to choose a category when creating a new page: content_panels = Page.content_panels + [ FieldPanel("header_image"), InlinePanel("categories", label="category"), FieldPanel('body'), ] If I leave this as is, it technically works, with the exception that the + icon in the following screenshot no longer works. That + icon, in Wagtail 4.1, would open … -
Account activation with token sent to email failed - Django
I'm making a blog website and I'm at the authentication part. I have programmed the code to send a mail, to the email submitted by the user, (for verification) when an account has been registered. This mail contains the activation token. I was able to do this just a few days ago before I had to tweak parts of my views.py for other reasons. My guess is that the code changed by mistake, and now I'm not sure about what to do. I tested this a few minutes ago and everything worked fine, except for the activation. It sent the activation link to me but when I clicked it, it told me that the activation failed. I'm sure there's a really silly mistake in my code but I'm just not able to find it. views.py def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) myuser = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): myuser = None if myuser is not None and generate_token.check_token(myuser, token): myuser.is_active = True myuser.save() login(request, myuser) return redirect('home') else: return render(request, 'authstuff/activation_failed.html') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self,user,timestamp): return ( text_type(user.pk) + text_type(timestamp) # text_type(user.profile.signup_confirmation) ) generate_token = TokenGenerator() I've made … -
How can I encrypt or hash the true origin source of media files?
I want to do something to encrypt the source of my media files. Now how can I achieve that, for example, could that work if I serve my file locally? or the files should be on a server like AWS S3 in order to have that secure link where you can't use that link to download a video for example. Here is a screenshot of video courses type of website that have something that I'd like to do. I've seen other types of links protected/encrypted... I just want to know if I can do that locally too or if the only way is to upload my videos on a hosting server like AWS and feed the files from there, and also if I serve the video files from a service like AWS do I need to do something else too in order to encrypt that source link, or it will be already done by AWS server? Thank you in advance! -
Can not connect Django to sql server
I follow the steps from ( Microsoft help to connect SQL server to Django) and then I receive this error "django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3'" Python version is 3.10.11 Django version is 3.2.19 **steps: ** Create a Django project $ django-admin startproject mysite E dit setting.py file Go to mysite/mysite/settings.py In DATABASE section, edit accrodingly. Make sure the DATABASE_NAME is exist in your SQL Server instance. settings.py DATABASES = { "default": { "ENGINE": "mssql", "NAME": "DATABASE_NAME", "USER": "USER_NAME", "PASSWORD": "PASSWORD", "HOST": "HOST_ADDRESS", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, }, } Run Django project Windows py manage.py runserver -
Can't open deployed Django web app on Azure container instance
Run the below commands, all were successful, but can't open the web app on browser, how to fix it? virtualenv .venv .venv\Scripts\activate pip install Django django-admin startproject demoproject python manage.py runserver --notes: checked the web app was running at http://127.0.0.1:8000/ pip freeze > requirements.txt --notes: add file "Dockerfile" --notes: add file ".dockerignore" docker build -t demoproject:v1.0 . az login az acr login --name xxtestcr docker tag demoproject:v1.0 xxtestcr.azurecr.io/demoproject:v1.0 docker push xxtestcr.azurecr.io/demoproject:v1.0 az acr update -n xxtestcr --admin-enabled true az container create -g xxtestrg --name test-ci --image xxtestcr.azurecr.io/demoproject:v1.0 --ports 80 443 --cpu 1 --memory 1.5 --dns-name-label xxtest-demoproject Dockerfile: FROM python:3.10.8 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt CMD python manage.py runserver 0.0.0.0:8000 .dockerignore __pycache__ .venv/ Dockerfile The app files: Azure container instance overview: But can't open the web app on browser: 4.147.67.11 xxtest-demoproject.australiaeast.azurecontainer.io -
Can't get csrftoken in Django for ajax recently
I referenced the code provided in the official doc here https://docs.djangoproject.com/en/4.2/howto/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false It worked well until recent. I didn't make any modification to the getCookie method. But it suddenly can't work on both Chrome and Firefox. The document.cookie always return "". And CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False. How sould I debug? I need the csrftoken to be passed to the ajax request. Thanks. Referenced src is here function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue;} const csrftoken = getCookie('csrftoken'); -
Your connection is not private When used tried for https ssl with certbot
i have been deploying my django rest api backend in digitalocean but when the certificate is generated and i tried to call https://domain-name there was an issue from the chrome saying Your connection is not private Attackers might be trying to steal your information from www.tabsulbackendsolutions.in (for example, passwords, messages, or credit cards). Learn more NET::ERR_CERT_COMMON_NAME_INVALID server { server_name domain_name; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/akhil/tabsul/TabsulBackEnd; } location / { include proxy_params; proxy_pass http://unix:/home/akhil/tabsul/TabsulBackEnd.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/tabsulbackendsolutions.in-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/tabsulbackendsolutions.in-0001/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = domain_name) { return 301 https://$host$request_uri; } # managed by Certbot server_name domain_name; listen 80; return 404; # managed by Certbot } can anybody please ? -
please help me in integrating a code that performs facial detection and recognition in this views.py code for django and chnages in urls.py if needed
This is the code for the view as of now, which captures an image of the student at signup and opens up a screen of live video capture when the student starts taking the exam. I wish to integrate facial detection and recognition in this code such that the picture of the user captured during sign up is compared with the video steam during examination and an alert is given if it doesnot match. from django.shortcuts import render,redirect,reverse from . import forms,models from django.db.models import Sum from django.contrib.auth.models import Group from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test from django.conf import settings from datetime import date, timedelta from exam import models as QMODEL from teacher import models as TMODEL import cv2 import os from django.http import StreamingHttpResponse import threading from django.views.decorators import gzip #### Initializing VideoCapture object to access WebCam face_detector = cv2.CascadeClassifier('static/haarcascade_frontalface_default.xml') # cap = cv2.VideoCapture(0) #for showing signup/login button for student def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'student/studentclick.html') def extract_faces(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face_points = face_detector.detectMultiScale(gray, 1.3, 5) return face_points def student_signup_view(request): userForm=forms.StudentUserForm() studentForm=forms.StudentForm() mydict={'userForm':userForm,'studentForm':studentForm} if request.method=='POST': userForm=forms.StudentUserForm(request.POST) studentForm=forms.StudentForm(request.POST,request.FILES) username = request.POST.get('username') userimagefolder= 'static/profile_pic/Student/'+ username if not os.path.isdir(userimagefolder): os.makedirs(userimagefolder) cap = cv2.VideoCapture(0) i,j = 0,0 count=0 … -
How to host django app on ionos's VPS, i get invalid page on my ip:8000
How to host django app on ionos's VPS I have purchased the cheapest VPS plan of ionos and now i want to host my django app, but when i execute 'python manage.py runserver' command and go to my_ip:8000 it shows invalid page on the browser, can anyone help me??? -
Django Pytest Failing In GitHub Workflow - How to mimic production environment?
I'm using GitHub Actions to create a CI/CD pipeline that tests production settings before deploying. The tests pass in my local environment, and all of the code works in production. However, any tests related to views fail in my GitHub workflow. I believe the tests are failing because GitHub's testserver defaults to http protocol, I assume. And I have SECURE_SSL_REDIRECT = True in my production settings. Errors: _________________________ test_register_user_view_get __________________________ client = <django.test.client.Client object at 0x7fa8101e9e10> @pytest.mark.django_db def test_register_user_view_get(client): response = client.get(reverse("accounts:register")) > assert 200 == response.status_code E assert 200 == 301 E + where 301 = <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="https://testserver/account/register/">.status_code accounts/tests/test_views.py:11: AssertionError _________________________ test_register_user_view_post _________________________ client = <django.test.client.Client object at 0x7fa80f8b2650> django_user_model = <class 'accounts.models.User'> @pytest.mark.django_db def test_register_user_view_post(client, django_user_model): response = client.post( reverse("accounts:register"), data={ "username": "PostTest", "first_name": "User", "last_name": "Name", "email": "user@email.com", "password1": "zxceefF1238", "password2": "zxceefF1238", }, follow=True, ) assert 200 == response.status_code > assert django_user_model.objects.count() == 1 E AssertionError: assert 0 == 1 E + where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x7fa810f1b910>>() E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x7fa810f1b910>> = <django.contrib.auth.models.UserManager object at 0x7fa810f1b910>.count E + where <django.contrib.auth.models.UserManager object at 0x7fa810f1b910> = <class 'accounts.models.User'>.objects accounts/tests/test_views.py:30: AssertionError When changing: response … -
How can I add a form to edit Comments to each Instance on a Django DetailView?
I am new to Django and trying to figure out how to build a webapp where I have Assets, attached Instances (of these Assets), and Comments attached to these instances, so basically in terms of simplified models.py models.py class Asset(models.Model) class Instance(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE, related_name='instances') class Comment(models.Model): instance = models.ForeignKey(Instance, on_delete=models.CASCADE, related_name='comments') I know I will have to use forms based on the Instance class so I prepared this: forms.py class InstanceComment(ModelForm): class Meta: model = Instance fields = '__all__' I use the generic list view to display the list of Assets, when I click on one of them, I then display a list of the Instances attached to it using a Detail view. What I would like, is that on this page, have for each of the Instances, a form to edit the comment (there can be only one comment per Instance). I am struggling to see how to pass multiple forms to the view. I guess this is a very standard question with Django but I could not figure it out so far... Could I get any guidance on this? So far, I do not see how to effectively send a list of forms to the … -
Why am I getting a TypeError when passing HTTP method dictionaries to Django REST Framework's as_view() method in ViewSets?
I created a ViewSet, in which I need to use in two URL Patterns, one is for getting the list of items and other is for getting the detail of single item. The problem is, when I pass {"get": "retrieve"} and {"get": list", "post": "create"} dictionaries in as_view() methods of my ViewSets in URL Patterns, I get the following error: TypeError: APIView.as_view() takes 1 positional argument but 2 were given Below is my ViewSet code: class LungerItemViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, generics.GenericAPIView): permission_classes = [permissions.AllowAny,] def get_queryset(self): """Retrieves and returns all Lunger Items""" return LungerItem.objects.all() def get_serializer_class(self): """Returns serializer class""" return LungerItemSerializer and below are my URL Patterns for this ViewSet: urlpatterns = [ path('lungar-items/', views.LungerItemViewSet.as_view({'get': 'list', 'post': 'create'}), name='lunger-item-list'), path('lungar-items/<int:pk>/', views.LungerItemViewSet.as_view({'get': 'retrieve'}), name='lunger-item-detail'), ] I tried to search this issue on ChatGPT, but it did not help much. However, it helped me finding the cause of this error. As per ChatGPT and my own research this error appears, when: We use as_view instead of as_view(). Basicaaly as_view() is a method and we should treat it like that. We pass the HTTP Methods dictionary like {"get": "list"} in an APIView class instead of a ViewSet If there are any custom Middleware used … -
How to define Django model datefield
I am new in python django, i am creating app model and wants to define a field(date of birth) to input date from user form but unable to understand how to define date field in model so that i can capture the date(date of birth) using form. Here is model # Create your models here. class funder(models,Model): user_name = models.CharField(max_length=150) user_mobile = models.CharField(max_length=12) user_dob = models.DateField('none' = true) user_address = models.TextField() user_status = models.PositiveIntegerField(default='1') thanks -
Django date range filtering from url parameters returns empty queryset
I'm currently trying to do date range filtering from url parameters with get_queryset on a generics class based view, however I am receiving an empty array after doing date range filtering. It's a bit weird since I can print the queryset, just not able to return it. url parameter: http://127.0.0.1:8000/budget-filter?budget_date=2023-6-7&budget_end_date=2023-6-13 Below is the views.py @permission_classes([IsAuthenticated]) class BudgetFilter(generics.ListAPIView): serializer_class = BudgetSerializer paginator = None filter_backends = [DjangoFilterBackend] filterset_fields = ['budget_category', 'budget_account', 'budget_date', 'budget_end_date'] def get_queryset(self): user = self.request.user.username budget_date_url = self.request.GET.get('budget_date', None) budget_end_date_url = self.request.GET.get('budget_end_date', None) if budget_date_url is not None: queryset = BudgetModel.objects.filter(current_user = user).filter(budget_date__gte=budget_date_url, budget_date__lte=budget_end_date_url).values() print (queryset) return queryset Below is the serializers.py class BudgetSerializer(serializers.ModelSerializer): class Meta: model = BudgetModel fields = '__all__' models.py class BudgetModel(models.Model): budget_description = models.CharField(max_length=150) budget_price = models.DecimalField(max_digits=35, decimal_places=2) budget_account = models.CharField(max_length=100) budget_category = models.CharField(max_length=100) budget_currency = models.CharField(max_length=150) budget_date = models.DateField(auto_now=False) budget_end_date = models.DateField(auto_now=False, blank=True) budget_display_date = models.CharField(max_length=15) current_user = models.CharField(max_length=200) Response with print (queryset) <QuerySet [{'id': 20, 'budget_description': 'adassd', 'budget_price': Decimal('22.00'), 'budget_account': 'Main', 'budget_category': 'Education', 'budget_currency': 'AED', 'budget_date': datetime.date(2023, 6, 10), 'budget_end_date': datetime.date(2023, 6, 10), 'budget_display_date': '10 Jun 2023', 'current_user': 'myname'}]> I tried using different ways of date range filtering, however __gte and __lte method is the one that seemed to do the trick. … -
How can I make my newsletter form success message consistently display after clicking send?
Newsletter form Console shows this error After clicking send button, success message shows and email gets saved in database but after the message disappears and I click send again, the success message doesn't show but the data gets sent to database Also I have set fadeOut time to 2 seconds and during that 2 seconds, the message shows everytime I click send but the message won't show up after it disappears How can I make the message show even after the message disappears? Help!!! This is my ajax code: $("#newsletter_form").submit(function(e){ e.preventDefault() var serializedData = $(this).serialize(); $.ajax({ type: "POST", url: "{% url 'newsletter' %}", data: serializedData, success: function(response){ $("#newsletter_msg").append( `${response.message}` ).delay(2000).fadeOut('slow') }, error: function(response){ $("#newsletter_msg").append( `${response.responseJSON.message}` ).delay(2000).fadeOut('slow') }, }); }); -
Stop automatic encoding by FileField
I am using the FileField of django model. class Drawing(models.Model): drawing = models.FileField(upload_to='uploads/') For example I try uploading 2byte charactor filename such as 木.pdf, then filename is encoded into , %E6%9C%A8_sBMogAs.pdf automatically. However, I want to keep 2byte characters, so I override the FileField.py. Just copy and paste from here and put some print to check where the filename is changed. I put print in def pre_save(self, model_instance, add):, def generate_filename(self, instance, filename):``def save_form_data(self, instance, data): and def save(self, name, content, save=True): functions to see the filename However in every checkpoint, filename is still 木.pdf or 木_sBMogAs.pdf not %E6%9C%A8_sBMogAs.pdf Where the filename is changed? and how can I surpass the change of filename ? import datetime import posixpath from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import Storage, default_storage from django.core.files.utils import validate_file_name from django.db.models import signals from django.db.models.fields import Field from django.db.models.query_utils import DeferredAttribute from django.db.models.utils import AltersData from django.utils.translation import gettext_lazy as _ class FieldFile(File, AltersData): def __init__(self, instance, field, name): super().__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be …