Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image links in included static CSS file not being signed using S3Boto3Storage with Django-Storages
I'm using django-storages (S3Boto3Storage) to upload my media files and libraries to S3 buckets. On my test page "delete_me.html", I include a CSS page from the datatables library, jquery.dataTables.min.css, which includes a link to an image. Including the CSS file in delete_me.html: <link rel="stylesheet" type="text/css" href="{% static "js/DataTables-1.11.5/css/jquery.dataTables.min.css" %}"> in jquery.dataTables.min.css: thead .sorting_asc{background-image:url("../images/sort_asc.png") !important}. when I look at the network tab of the chrome debugger, the CSS gets loaded using a signed URL. get request with status 200 OK for: https://mybucketname.s3.amazonaws.com/js/DataTables-1.11.5/css/jquery.dataTables.min.css?X-Amz-Algorithm=ALG_REDACTED&X-Amz-Credential=CREDENTIAL_INFO_REDACTED%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20220804T011840Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=SIGNATURE_REDACTED as I should. However, the sort_asc.png image does not get loaded. The request is to an unsigned URL: https://mybucketname.s3.amazonaws.com/js/DataTables-1.11.5/images/sort_both.png and returns a 403. I'm not sure if the Django static library is responsible for this or if it's django-storages issue. Because it's a third-party library, there's no {% load static %} in the CSS file (and I'm not sure if it would be run through the django templating system anyway). How do I get that image to load without making the image file accessible to the public at large? -
Mixed Content: The page at {URL} was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint {ENDPOINT}
I have the following projects https://github.com/codyc4321/dividends_ui and https://github.com/codyc4321/stocks_backend. The deployed app at https://octopus-app-8l8j5.ondigitalocean.app/ is getting error Mixed Content: The page at 'https://octopus-app-8l8j5.ondigitalocean.app/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://67.205.161.47:8000/dividends/wba'. This request has been blocked; the content must be served over HTTPS. this is the error I got last week but now I have gone through and done https://timonweb.com/django/https-django-development-server-ssl-certificate/ and am running the python server with https: root@username:~/stocks_backend# python3 manage.py runserver_plus --cert-file cert.pem --key-file key.pem I do not understand why my app isn't working for the request, although I notice that BEFORE using the cert file I could hit an endpoint from my local machine just fine, and now after it my local machine gets Error: connect ECONNREFUSED 67.205.161.47:8000 Why running the server using cert and key files for https not sufficient to make this api request? Thank you -
Filter many-to-many object with specific value
I have the current filter this filter works, but I also want to filter the objects inside my quotation if the user matches. If I have 2 itens, one is from the user 1 and the other from user 2, when I filter the quotation using user 1, I also want to see only the item that has the specified user. Thus, instead of this I want this -
how to containerize a Django project with Oracle Database
I am trying to containerize my Django project and set up a docker image for the Oracle Database. I am getting an error while I run docker-compose build: service "oracle-db" refers to undefined volume oracle: invalid compose project My docker-compose file is: version: "3" services: django: build: context: . dockerfile: django.Dockerfile image: kanbanboard_django restart: unless-stopped volumes: - "django-static:/app/django-static" - "media:/app/media" - "./backend/settings:/app/settings" env_file: - .env depends_on: - oracle-db certbot: image: certbot/certbot entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" volumes: - "./data/certbot/conf:/etc/letsencrypt" - "./data/certbot/www:/var/www/certbot" oracle-db: image: sath89/oracle-19c volumes: - oracle:/u01/app/oracle/ env_file: - .env volumes: media: django-static: -
How to bulk_update in related fields modified using only one call
I'm working with two tables to change some data in there but I'm wanted to avoid two calls using bulk_update as following: queryset = MyModel.objects.all() submodels_to_upcate = [] for instance in queryset: instance.submodel = process() instance.submodel.sub_property = some_random_data() submodels_to_update.append(instance.submodel) MyModel.objects.bulk_update(queryset, ['submodel']) SubModel.objects.bulk_update(submodels_to_update, ['sub_property']) What I wanted to do is something like the following: MyModel.objects.bulk_update(queryset, ['submodel', 'submodel__sub_property']) My question here is if there is a way to achieve bulk_update in two different tables at the same time. -
Get User Password
Is there any way to get the password of the registered user? My app uses the same password to do other operations, so I need the user's password, but when I put {{request.user.password}} it comes encrypted -
How can i change file directory's name related to an instance's field too after the field get updated in Django's model
good day everyone, i am a self learner and quite new to django and i am facing some questions currently, i created a model which will have images upload to a self-defined directory as like this: class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): self.delete(name) return name class DealerList(models.Model): def user_dir_folder(instance, filename): return 'dealerImg/{0}/{1}'.format(instance.dealerCompanyName, filename) dealerCompanyName = models.CharField(max_length=100) Cert = models.ImageField(storage=OverwriteStorage(), upload_to=user_dir_folder) Img = models.ImageField(storage=OverwriteStorage(), upload_to=user_dir_folder) and i installed ‘django_cleanup.apps.CleanupConfig’ into the settings file to cleanup those related files in case if an instance is deleted (but the empty folder stay existed which i dont know how to deal with yet, but this is second question). now what i am facing is, if an instance’s ‘dealerCompanyName’ field is updated, the folder which created named with the ‘dealerCompanyName’ won’t get updated along (also django will delete those uploaded files that cant match any instance now after ‘dealerCompanyName’ is updated since i installed cleanup, but this is the third question), what i wanna ask is, is there anyway to update that folder’s name too if ‘dealerCompanyName’ field get updated? by the way if there are answer for the second and third questions mentioned above will be very very appreciated since i will face them … -
How to handle request methods in function based views in Django
As I am learning Django I have some questions about the handling of request methods for function based views (FBVs) in Django. What I found for FBVs: The URLconf doesn’t look at the request method. In other words, all request methods – POST, GET, HEAD, etc. – will be routed to the same function for the same URL. from URL-Dispatcher. require_http_methods(request_method_list)¶ Decorator to require that a view only accepts particular request methods from View Decorators Does that mean, I can restrict an URL defined in urls.py to a function which in turn only accepts say PUT-Requests and in case I want to handle DELETE said URL is wasted, since I restricted it to PUT? Or otherwise, I have to "dispatch" myself within the FBV? E.g. with request.method == 'PUT' Alternatively for CBVs Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. from Introduction to class-based views Does that mean, if I want to handle PUT or DELETE in separate functions I have to a) use a class based view with the verbs being implemented like put() and delete() b) use DjangoResteFramework only for having APIViews and @api_view(['Put']) as … -
Django 1.10 or later: base.html override not working
I am creating a site in Django with a custom view, and want to link to that view on the admin page. But even though I've followed the directions to override in Documentation or Youtube, but i won't show the changes in the overide file. {% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">Test</a></h1> {% endblock %} {% block nav-global %}{% endblock %} My base.html in ratonix\templates\admin Map tree: └─ratonix ----└── ratonix ----------└── settings.py ----------└── views.py ----------└── urls.py --- └── templates -----------└── admin - ------------ └── base.html └── manage.py Templates folder in the same folder as manage.py This is my current settings.py: """ Django settings for ratonix project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import pymysql import os pymysql.install_as_MySQLdb() from pathlib import Path # 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/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY … -
I got KeyError at /cart/add/3/ 'quantity' in my django shop application and I am still unable to debug it
I got KeyError at /cart/add/3/ 'quantity' in my django shop application and I am still unable to debug it cart.py from decimal import Decimal from django.conf import settings from shopapp.models import Product class Cart(object): def __init__(self, request): #initialize the cart self.session=request.session cart=self.session.get(settings.CART_SESSION_ID) if not cart: #save an empty cart in the session cart=self.session[settings.CART_SESSION_ID]={} self.cart=cart #Access the related products in the cart through iteration #i.e iterate over the items in the cart and get the products from the database def __iter__(self): product_ids=self.cart.keys() #get the products objects and add them to the cart products=Product.objects.filter(id__in=product_ids) cart=self.cart.copy() for product in products: cart[str(product.id)]['product']=product for item in cart.values(): item['price']=Decimal(item['price']) item['total_price']=item['price'] * item['quantity'] yield item #adding a total price attribute #counting all items in the cart def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product, quantity=1, override_quantity=False): #Add a product to the cart or update its quantity product_id=str(product.id) if product_id not in self.cart: self.cart[product_id]={'quantity':0, 'price':str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): #mark the session as modified to make sure it gets saved self.session.modified=True def remove(self, product): #remove a product from the cart product_id=str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() #Calculate the total cost of items in the cart … -
the attribute 'type' and a xs:complexType local declaration are mutually exclusive
<xs:element maxOccurs="1" name="Field" type="withKey"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Applicants" type="Applicants"/> </xs:sequence> </xs:complexType> </xs:element> I have the following tags in one of my xsd files, while executing the above code, I am getting the error xmlschema.validators.exceptions.XMLSchemaParseError: the attribute 'type' and a xs:complexType local declaration are mutually exclusive Running my code on Python 3.9 and django 4.1. Please help me with the solution, thanks in advance. -
Google Cloud App engine Internal Error 500 when deploying updates
I am using pycharm for deployments on gcloud django python project and getting this in the error log. No errors when deploying but the page won't open to the homepage or any other and only gives an Internal 500 error message: Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.7/site- packages/gunicorn/workers/sync.py", line 134, in handle self.handle_request(listener, req, client, addr) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/urls/resolvers.py", line 601, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
Is there a simple way to update the data of a form rendered with django-forms
i am fairly new to django and im trying to render a django form and update its content with an ajax request to an API. So i got a form like this: from django import forms from models import ExampleModel class ExampleForm(forms.ModelForm): name=forms.CharField() comment=forms.CharField(widget=forms.Textarea()) class Meta: model = ExampleModel fields=("name","comment") got my data from the API like this: from forms import ExampleForm from models import ExampleModel def apiGetExampleData(request,name): data=ExampleModel.objects.filter(name=name).values(*getFormFields(ExampleForm())) #if there is a better way to get the data, would be thankful to know :) JsonResponse(data[0]) def getFormFields(form): output=[] for element in form: output+=[element.name] return output Now i got the form (which renders fine), and a way to get the data. So, is there some predefined way to apply data in json format to a form in Javascript? -
Django DecimalField rejecting all values with 2 and more decimal places
I have a model: class Account(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) with a test: @pytest.mark.django_db class TestAccount: def test_it_accepts_valid_data(self): data = {"profile_id": create_profile().id, "balance": 10.55} account = Account(**data) account.full_clean() account.save() Which fails with the exception: FAILED wallets/tests/test_model.py::TestAccount::test_models - django.core.exceptions.ValidationError: {'balance': ['Ensure that there are no more than 2 decimal places.']} Reducing the test balance to a one decimal place figure e.g 10.5 passes the test. The interesting part is increasing the decimal_places argument to a higher figure e.g 5, still raises the exception on any figure with more than one decimal place Am I missing something or is this a Django bug? I'm on python3.9 and Django 4.0.6 -
Django docker container could not connect to redis server on port 6379
I hav a redis container running on port 6379 but my django application can't connect to that port. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f62c020fec99 sp_ask_dashboard_celery_worker "sh -c 'cd sp_dashbo…" 39 minutes ago Up 39 minutes sp_ask_admin_dashboard-master_celery_worker_1 60089763fd3f ask_webapp "sh -c 'python sp_da…" 39 minutes ago Up 39 minutes 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp ask_dashboard_web 62cde1811827 postgres:14.0-alpine "docker-entrypoint.s…" 39 minutes ago Up 39 minutes 5432/tcp sp_ask_admin_dashboard-master_db_1 24adadf28ba2 redis:6-alpine "docker-entrypoint.s…" 39 minutes ago Up 39 minutes 6379/tcp sp_ask_admin_dashboard-master_redis_1 When I login into my webapp container (ask_webapp). I tried this solution to find if am able to connect to Redis through "python manage.py shell" inside my container. And I am getting this error: "OperationalError: Error -3 connecting to redis:6379. Temporary failure in name resolution." My settings.py includes: CELERY_BROKER_URL = "redis://redis:6379/0" CELERY_RESULT_BACKEND = "redis://redis:6379/0" This info above is also on the .env.dev file My docker-compose.yml look as follow: celery_worker: build: context: . dockerfile: ./sp_dashboard/DockerfileBuild image: sp_ask_dashboard_celery_worker command: > sh -c "cd sp_dashboard ; celery -A settings worker -l INFO" volumes: - .:/usr/src/app/ env_file: - ./.env.dev environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_dev - "POSTGRES_HOST_AUTH_METHOD=trust" depends_on: - redis - db - web -
add field Migrations no working django OneToOneField
I try to migrate a OneToOne model with the corresponding arguments album = models.OneToOneField(Album, on_delete=models.CASCADE)but when I run makemigrations the add field does not appear in my terminal. All other migrations are done except the one why ? Thanks for your help class Album(models.Model): reference = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) title = models.CharField(max_length=200) picture = models.URLField() artists = models.ManyToManyField(Artist, related_name='albums', blank=True) class Booking(models.Model): created_at = models.DateTimeField(auto_now_add=True) contacted = models.BooleanField(default=False) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) album = models.OneToOneField(Album, on_delete=models.CASCADE) Terminal show me Migrations for 'store': store/migrations/0001_initial.py - Create model Album - Create model Artist - Create model Contact - Create model Booking - Add field artists to album -
[python][django]Uploading files in Django
I have a form.py including Floatfield and Charfield. Now I want to add a new Filefield to upload a text file. But I fail. The float var is submitted successfully and I could see they are changed with the change of the input, but I cannot find the file in located folders. And also, how could I check whether file extensions are correct? Shoudl I achieve it in view or model? Could someone help me? I truly struggled with it. model.py file = models.FileField(upload_to='/Folder', null = True) form.py file = forms.FileField(label='data', required=False) view.py is followed the structure in Django official document. def handle_uploaded_file(f): with open('./test_temp_file.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def file_upload(request): if request.method=='POST': form = input_form(request.POST,request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) name = request.FILES['filename'].name time = cleaned_data(timezone.now()) form = { 'name' : name, 'time' : time } return render(request, 'home/results.html',{'form':form}) else: form = input_form() return render(request, 'home/input.html', {'form': form}) Thanks. -
How to send value from HTML form into a general context of Django Project
I need to send a value from a html file into a Django View. I need to get user.id_aadgroup.idcustomer.uuid from permissions.html (which is linked to the view PermissionsListView) passed into the context of a brand new view, ApplicationListView() which has the url name applications when I click on the submit button. Here is the code: permissions.html in the django app permissions <form action="{% url 'applications' user.id_aadgroup.idcustomer.uuid %}" method="get"> <button type="submit" class="btn btn-outline-primary" value="go to manage permissions">Accéder au contrat</button> </form> view.html in the django app applications class ApplicationListView(ListView): model = ViewDevpermissionapplicationuser template_name = 'applications/applications.html' def get_context_data(self, **kwargs): kwargs.update( user= self.request.session.get('user', {'is_authenticated' : False}) ) context = super().get_context_data(**kwargs) return super().get_context_data(**kwargs) Think I can do it with a form but don't know how, any suggestions ? -
Method \"POST\" not allowed
I am getting error as Method \"POST\" not allowed. urls.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.listTutorials), url('create/', views.createTutorial), url('<str:pk>/update/', views.updateTutorial), ] views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import TutorialSerializer from .models import Tutorial @api_view(['POST']) def createTutorial(request): serializer = TutorialSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def updateTutorial(request, pk): tutorial = Tutorial.objects.get(pk=pk) serializer = TutorialSerializer(tutorial, data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def listTutorials(request): tutorials = Tutorial.objects.all() serializer = TutorialSerializer(tutorials, many=True) return Response(serializer.data) serializers.py from rest_framework.serializers import ModelSerializer from .models import Tutorial class TutorialSerializer(ModelSerializer): class Meta: model = Tutorial fields = '__all__' models.py from django.db import models class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) def __str__(self): return self.title project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('tutorials/', include('tutorials.urls')) ] Now I am using POST request as http://localhost:8000/tutorials/create/ with body { "title": "Django framework", "description": "Learning django framework" } But I am getting error { "detail": "Method \"POST\" not allowed." } -
Django: combine ListView and DeleteView to use with HTMX?
I’m using Django with HTMX to manage a CRUD table in which I want to list and delete objects. For this, I have a ListView which displays a table (using django-tables) with pagination, sorting, and text search features. It works as expected with HTMX: for example, if you go to the next page, the whole page is not reloaded: HTMX gets the table and upload a specific part of the DOM. It looks like this: The code of the ListView looks like: class Proposals(SingleTableMixin, SearchableMixin, ListView): table_class = ProposalTable # for django-tables2 ordering = "id" model = Proposal paginate_by = 5 search_filters = ["title__icontains"] # custom text search def get_template_names(self): # Trick to chose between loading the whole page (first time user goes to the page) or just the table via HTMX (when user uses pagination or sorting, it reloads the table only in the DOM) if self.request.htmx: return "fragments/proposals_fragment.html" return "proposals.html" Now, I’m trying to add a delete feature, with the best UX. I have explored multiple ways until now: Just by removing the row from the DOM once the object is actually removed from the DB → bad: while it’s fast, it makes the pagination wrong/inconsistent, and with … -
Django - Easiest way to translate just 1 page
I want to translate only 1 page (1 Django template) to 2 different languages. After reading a bit about Django internationalization, seems quite complex and probably an overkill for my use case (it's just 1 page and not even a public website, just an internal report). It would be great if I could use the same view for different 2 templates (one template for each language), but I don't know how to do that. Currently, I'm using something like this to send the info to the template (the list is actually much longer): context = { 'campaigns' : campaigns, 'data_campaigns' : data_campaigns, 'manual_changes' : manual_changes, 'groups_bad' : groups_bad, } return render(request, 'english.html', context) It would be great if I could create a "spanish.html" template and just translate the text directly in that template. Is it possible? Are there better (and not very complex) solutions? Also, maybe using "context" like this is not a best practice. I'm learning Django, it was the easiest option I found and it works. I'm open to change it. Thanks! -
i have an error when installing django with docker even though it is in accordance with the documentation
how can I get to run django correctly by using docker? i have followed the documentation but have an error like thisPicture of error -
Template input isn't in POST
I added an input field in template to a POST form, but it isn't getting passed in the request. <form method='post' id="data_form"> {% csrf_token %} {{ form.as_p}} ... {% if part_formset %} <p> Parts:</p> <input type="checkbox" name="assigned_only" id="assigned_only" class="filter-button" {% if assigned_only %}checked{% endif %}><label for="assigned_only" class="filter-button">Assigned only</label> {{ part_formset.management_form }} <table> <tbody> {% for form in part_formset %} <tr> <td> {{ form.part }}{{ form.part.errors }} </td> <td> x {{ form.amount }}{{ form.amount.errors }}</td> </tr> {{ form.id }} {{ form.non_field_errors }} {% endfor %} </tbody> </table> {{ part_formset.non_form_errors }} {% endif %} </form> But the POST request returns every other field except this one. What am I missing? -
Django, Do I have to use is_valid() when I get request.FILES?
I wanted to save the images, so I wrote the code like this. def test_form(request): if request.method == "POST": for key in request.FILES.keys(): for img in request.FILES.getlist(key): f = Image() f.image = img f.save Can't I save it after validating it like this? def extension_filter(filename): filter = ['png','jpeg','jpg',...] extenstion = filename.split('.')[-1] if extenstion in filter: return True else : return False ... for key in request.FILES.keys(): for img in request.FILES.getlist(key): if extenstion_filter(img): f = Image() f.image = img f.save else: continue ... -
Send different attachment files such as picture, pdf, audio files, video files and zip files via email in Django
I have a platform (e-commerce website) where I do upload different types of files and then I send them to users based on requests via email. I did try but get the following error: FileNotFoundError at /some-url/[Errno 2] No such file or directory: 'http://127.0.0.1:8000/media/book_file/selfish_gene.jpeg' I got some help regarding sending pdf files via email but that one is not working as well. I do appreciate any guidance and help in advance regarding sending other files such as audio, picture, and video via email in Django. Below I do provide a snippet of the code. Hope it helps. Model: class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) isbn = models.CharField(max_length=255) page = models.IntegerField(null=True, blank=True) class BookFiles(models.Model): book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL) file = models.FileField(upload_to='book_file/', null=True, blank=True) View: def send_book(request): message = 'body of this email' subject= 'the subject of this email' recipient_email = 'customer@example.com' from_email = 'platformemail@example.com' email=EmailMessage(subject,message,from_email,[recipient_email]) email.content_subtype='html' the_domain = request.build_absolute_uri('/')[:-1] book_object = Book.objects.get(title='Selfish Gene').bookfiles_set.all().first().file.url the_file=open(f'{the_domain}{book_object}',"r") email.attach("file_name.pdf", the_file.read(),'application/pdf') email.send()