Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS error during API call for React/DRF app on Heroku
I have my react front end and my django rest api as two separate apps on heroku. I'm having the issue of the following error: The request options I use for the fetch request on the frontend: const credentials = btoa(`${data.get('username')}:${data.get('password')}`); const requestOptionsSignIn = { method: "POST", credentials: 'include', headers: { 'Accept': 'application/json, text/plain', 'Content-Type': 'application/json', "Authorization": `Basic ${credentials}` }, body: JSON.stringify({}) } And my Django/django-cors-headers settings: CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['https://_____frontend.herokuapp.com'] CORS_ALLOW_HEADERS = ("x-requested-with", "content-type", "accept", "origin", "authorization", "x-csrftoken") I've tried playing around with the settings but I can't get it to work. -
Return fields in a custom format in serializer Django Rest Framework
I am very new to Django rest framework and I am looking to return a the model field serializer in a custom format. This is the serializer: class SubjectSkillLevelSerializer(serializers.ModelSerializer): class Meta: model = SubjectSkillLevel fields = ["subject", "level"] It currently returns this: [ { "subject": 1, "level": 1 }, { "subject": 2, "level": 1 } ] How can I make the serializer return a custom format like this { 1 : 1, 2 : 1 } What I tried: def to_representation(self, value): return "%s : %s" % ("subject", "level") But it obviously didn't work and just returned the strings. -
Set django form value from javascript variable
I created a registration form in a django template. I have a variable in javascript which is get a value(which character choiced by the user) and I want to pass that variable to the form value. How I can make it work? <form method="POST" action=""> {%csrf_token%} <div class="input-group mb-2"> {{form.username}} </div> <div class="input-group mb-2"> {{form.email}} </div> <div class="input-group mb-2"> {{form.password1}} </div> <div class="input-group mb-2"> {{form.password2}} </div> <div class="input-group mb-2"> {{form.character_type}} </div> <input type="submit" value="Register Account"> </form> -
Django get the value of a field in the __init__ of forms
I need to have the value of a field before doing an update. forms.py class Form_Rol(forms.ModelForm): class Model: model = My_Model fields = "__all__" def __init__(self, *args, **kwargs): '''I want to do this''' value_coming_from_update = self.fields['name'] print(value_coming_from_update) Output.... <django.forms.fields.CharField object at 0x0000026649558DC0> How do I print the actual value in init? I can't use self.cleaned_data.get('name') in init. It gives me an error (AttributeError: 'Form_Rol' object has no attribute 'cleaned_data') -
session list is not updated after the from is submitted in Django
from django.shortcuts import render from django import forms from django.urls import reverse from django.http import HttpResponseRedirect # Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label="New Task") def index(request): if "tasks" not in request.session: request.session["tasks"] = [] return render(request,"tasks/index.html",{ "tasks":request.session["tasks"] }) def add(request): if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): newtask = form.cleaned_data["task"] request.session["tasks"] += [newtask] return HttpResponseRedirect(reverse("index")) else: return render(request,"tasks/add.html",{ "form" : form }) return render(request,"tasks/add.html",{ "form" : NewTaskForm() }) I Add the newtask to our list of tasks If the form is invalid, re-render the page with existing information. -
Checking the type of an argument in Django Python views
I have more experience with C (intermediary expertise) and now working on something in Django Python. I have a url function which directs a REST call to a views function. Now, I am trying to make a single url for passing an argument for both an ID (int) and an email (str/EmailField) to land on the same views function and I can then unpack the type of the arg sent and do something different. I want the url to be argument type agnostic and then do the conditional check in the views function. But it looks like each time, the argument is sent as a str (even when the id is sent). I believe there may be 2 things here I do not fully understand: perhaps the argument will always be sent to the view function as a str all the time? Or there may be an issue with my type checking (as you can see I am trying to cast the type of the arg and check if true. Seems more like a C method of doing stuff? Thank you! urls.py looks like path('<arg>/', views.getUpdateDeleteAccount), ->> this is what I am trying to do #path('<int:pk>/', views.getUpdateDeleteAccount), ->>> works in … -
For Django file upload can I set the models.FileField directly without using any Form or web input
Every example of uploading I can find for Django uses a web input to get the file. But I am getting the files from an array of REST api end points and I receive the files as byte strings. I am using a Model class with boto3 backend storage to upload to S3. I can upload files using the django admin but fail to do it manually. The actual code is too long but here is some pseudo code. My question is what is the data type I need for x in this line: zipf.zipfile = x Here is the pseudo code: class UploadedZip(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='zipfiles') name = models.CharField(max_length=102) zipfile = models.FileField(upload_to="zipfile") def getfiles(request): files = apicall() # Returns include a list of links for f in files: # the return can be a byte string of data or I could save it to a tmp file if I need to x = callapi_inline(request, f.apiurl) if x and len(x) > 0: zipf = UploadedZip() zipf.zipfile = x zipf.name = f[0]['name'] zipf.user = request.user zipf.save() -
I want to migrate the changes of models.py but it says the object has no attribute 'urls', i have to write urls.py first?
I have registered the models in admin.py the whole things I've changed in this app are in admin.py and models.py I didn't created the urls.py this is my models.py: from django.db import models class Clients(models.Model): name = models.CharField(max_length=300) company = models.CharField(max_length=300) def __str__(self) -> str: return self.company class Manufacturers(models.Model): name = models.CharField(max_length=300) location = models.TextField("address") def __str__(self) -> str: return self.name class Products(models.Model): cost_per_item = models.PositiveBigIntegerField("Cost") name_of_product = models.CharField("name") manufacturer = models.ForeignKey(Manufacturers, on_delete=models.CASCADE) def __str__(self) -> str: return self.name class ClientOrders(models.Model): fulfill_date = models.PositiveIntegerField("Fulfill Month") order_number = models.PositiveIntegerField(primary_key=True) client = models.ForeignKey(Clients, on_delete=models.CASCADE) products = models.ManyToManyField(Products) def __str__(self) -> str: return self.client and this is the error: AttributeError: 'ClientOrders' object has no attribute 'urls' -
404 error when getting file in static, django
I tried several attempts through googling, but it didn't work. I don't think it was like this when I was working on another Jango project, but I don't know why. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.HomeView.as_view(), name = 'home'), #to home.html path("blog/", include('blog.urls')), ] # urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "static/" STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static") home.html <img src="{% static 'assets/img/navbar-logo.svg' %}" alt="..." /> directory Project-folder | |__config | |__settings.py | |__urls.py | |__app | |__template | |__app | | |__bla.html | |__home.html | | #bootstrap |__static |__assets |__img ... -
How to create Date from year and month (IntergerFields in Django Form)
I have a selection in Django Form based on year and month (as integer fields) and I would like to create and save also Date value (first day of particular month and year) to link it to another table. My function in forms.py: def date_creation(year, month): if year and month: y = str(year) m = str(month) if len(m) == 1: m = "0"+ m entry = f"{y}-{m}-01 00:00:01" date1 = datetime.strptime(entry, '%Y-%m-%d %H:%M:%S') date2 = date1.strftime('%Y-%m-%d') return date2 else: return 0 models.py class MonthlyCosts(models.Model): y = int(date.today().year) y1 = y - 1 y2 = y - 2 year_selection = ( (y, y), (y1, y1), (y2, y2), ) months_selection = ( (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ) year = models.IntegerField("Year", choices=year_selection) month = models.IntegerField("Month", choices=months_selection) date = models.DateField("Date", null=True, blank=True) When I tried function above in my form, so I got following error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data '<django.forms.fields.IntegerField object at 0x102c521c0>-<django.forms.fields.IntegerField object at 0x102c52280>-01 00:00:01' does not match format '%Y-%m-%d %H:%M:%S Thanks a lot for help, L. -
Passing hardcoded template select field value to django model in parallel with modelform fields
I have a contact model class and its respective modelForm: # models.py class Contact(models.Model): name = models.CharField(max_length=32, blank=False) email = models.EmailField() subject = models.CharField(max_length=32, blank=False) message = models.TextField(max_length=256, blank=False) def __str__(self): return self.email # forms.py class ContactForm(forms.modelForm): class Meta: model = Contact fields = ('name', 'email', 'message',) I have a respective views.py and template from where I am successfully submitting and saving the form data in my Contact model. # views.py def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() email_subject = f'New contact {form.cleaned_data["email_address"]}: {form.cleaned_data["name"]}' email_message = form.cleaned_data['message'] send_mail(email_subject, email_message, settings.CONTACT_EMAIL, settings.ADMIN_EMAIL) return redirect('home') form = ContactForm() context = {'form': form} return render(request, 'web_page/contact_page.html', context) However, as my subject field is hardcoded and consists of many values from html select tag with name="subject" and few dozens of options, I want to post it together with my modelForm fileds and save respective value in my Contact table. Is this possible anyway? I just want to avoid bringing all this existing records in forms.py as a CHOICE of my subject field. I am on learning curve so forgive me if I am asking something stupid on top of I know already should work... -
ModuleNotFound backend.wsgi
I am trying to deploy my django application to Heroku and I ran into this problem and it's really annoying me. The deploy process went well, I had my project on GitHub, proceeded to connect it to Heroku and everything. First I ran into a problem with gunicorn not being compatible with Windows, so I decided to give Waitress a try and it worked. I pushed my changes and the build succeeded. I tried opening my app and I had the following mistake: 2022-08-10T15:57:50.867340+00:00 app[web.1]: 2022-08-10T15:57:50.867340+00:00 app[web.1]: There was an exception (ModuleNotFoundError) importing your module. 2022-08-10T15:57:50.867341+00:00 app[web.1]: 2022-08-10T15:57:50.867341+00:00 app[web.1]: It had these arguments: 2022-08-10T15:57:50.867341+00:00 app[web.1]: 1. No module named 'backend.wsgi' 2022-08-10T15:57:50.867341+00:00 app[web.1]: 2022-08-10T15:57:51.005980+00:00 heroku[web.1]: Process exited with status 1 2022-08-10T15:57:51.467637+00:00 heroku[web.1]: State changed from starting to crashed 2022-08-10T15:58:13.398128+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=itpartsstore-azhdan.herokuapp.com request_id=912e8c5a-2482-4851-b31f-8bdf03472e92 fwd="85.187.39.220" dyno= connect= service= status=503 bytes= protocol=https 2022-08-10T15:58:13.618890+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=itpartsstore-azhdan.herokuapp.com request_id=89daee3f-8122-4892-86d5-c683f77d4990 fwd="85.187.39.220" dyno= connect= service= status=503 bytes= protocol=https This is my Procfile: web: waitress-serve --port=$PORT backend.wsgi:application My requirements: asgiref==3.5.2 autopep8==1.6.0 certifi==2022.6.15 charset-normalizer==2.1.0 Django==4.0.6 django-cors-headers==3.13.0 djangorestframework==3.13.1 djangorestframework-simplejwt==5.2.0 docopt==0.6.2 gunicorn==20.1.0 idna==3.3 Pillow==9.2.0 pipreqs==0.4.11 psycopg2==2.9.3 psycopg2-binary==2.9.3 pycodestyle==2.8.0 PyJWT==2.4.0 pytz==2022.1 requests==2.28.1 sqlparse==0.4.2 toml==0.10.2 tzdata==2022.1 urllib3==1.26.11 waitress==2.1.2 yarg==0.1.9 I tried having my … -
Javascript only passing first value from for loop
I am trying to sum the values in a for loop from my django database. Whenever I pass the loop through javascript, it only returns the first value in the array. I was wondering if someone could help me figure out how to get all the values in the loop to pass through the script. {% for loans in d1_companies %} <div id="security-value">{{loans.market_value}}</div> {% endfor %} <div id="test"></div> <script> for(let i = 0; i < 1000; i++) { let sum = document.querySelectorAll(`[id^="test"]`)[i]; let values = [document.getElementById("security-value").innerText]; const summed_value = values.reduce((accumulator, currentValue) => accumulator + currentValue); sum.innerText = summed_value; } </script> -
Serverless Framework + Django: Unable to import XYZ.wsgi.application
I'm trying to set up Django with serverless framework with the help of serverless-wsgi plugin. This is my serverless.yml file provider: name: aws runtime: python3.8 plugins: - serverless-wsgi - serverless-python-requirements functions: api: handler: wsgi_handler.handler events: - http: ANY / - http: ANY /{proxy+} custom: pythonRequirements: fileName: requirements.txt usePipenv: false dockerizePip: non-linux wsgi: app: sls_django_minimal.wsgi.application packRequirements: false When I try to access the API/site after deploying, I'm getting the following error Stacktrace /var/task/wsgi_handler.py 48 raise Exception("Unable to import {}".format(config["app"])) ^ Exception Unable to import sls_django_minimal.wsgi.application /var/task/wsgi_handler.py 115 wsgi_app = import_app(config) <frozen importlib._bootstrap> 219 <frozen importlib._bootstrap_external> 843 <frozen importlib._bootstrap> 671 <frozen importlib._bootstrap> 975 <frozen importlib._bootstrap> 991 <frozen importlib._bootstrap> 1014 /var/lang/lib/python3.8/importlib/__init__.py 127 return _bootstrap._gcd_import(name[level:], package, level) /var/task/serverless_sdk/__init__.py 56 user_module = import_module(user_module_name) /var/task/s_api.py 20 user_handler = serverless_sdk.get_user_handler('wsgi_handler.handler') /var/task/s_api.py 25 raise e /var/task/serverless_sdk/__init__.py 144 return user_handler(event, context) /var/runtime/bootstrap.py 127 response = request_handler(event, lambda_context) /var/task/s_api.py 25 raise e /var/task/serverless_sdk/__init__.py 144 return user_handler(event, context) /var/runtime/bootstrap.py 127 response = request_handler(event, lambda_context) /var/task/s_api.py 25 raise e /var/task/serverless_sdk/__init__.py 144 return user_handler(event, context) /var/runtime/bootstrap.py 127 response = request_handler(event, lambda_context) /var/task/s_api.py 25 raise e /var/task/serverless_sdk/__init__.py 144 return user_handler(event, context) /var/runtime/bootstrap.py 127 response = request_handler(event, lambda_context) /var/task/s_api.py 25 raise e /var/task/serverless_sdk/__init__.py 144 return user_handler(event, context) /var/runtime/bootstrap.py 127 response = request_handler(event, lambda_context) /var/task/s_api.py 25 … -
Django Test - django.urls.exceptions.NoReverseMatch
I got errors when running tests django.urls.exceptions.NoReverseMatch Here is the urls.py urlpatterns = [ re_path(r'interfacegraph/(?P<device>[A-Z0-9.]{12,15})/(?P<interface>\d+)/(?P<graph>\d+)/graph', InterfaceGraphViewSet.as_view({'get': 'graph'}), name='interfacegraph'), ] And heres the line of code in tests where the test throws errors response = self.client.get( reverse('interfacegraph'), {'device': 'device', 'interface': 'interface', 'graph': 'traffic'}, content_type='application/json') The viewset is extending generics viewset class InterfaceGraphViewSet(viewsets.GenericViewSet): Any idea how to test this? -
Add attribute in model classes by user in Django
On my store site, in the product features section, the user must add these features himself. Even new categories can be added to it. And the important thing is that each product has its own unique features. For example, a mobile phone has a feature of camera information, a dress has a feature of the material used, etc. It would be useless if I write these myself and make a separate class for each class. That's why I want my user to do this in a personalized way. It means adding more fields and attributes to the class by the user through his user panel. What is the solution? -
Get Django boolean field even if is not selected
I had a Django form with only one BooleanField field (in forms.py). In my html file I put this form field more than one times, and to get them value I use this: checkboxes = request.POST.getlist('print') --> ['on', 'on'] this is the result, but only if the checkbox are clicked. ('print' is the name of the BooleanField in forms.py). But using this method I retrieve only the BooleanField that are True and not also the False. How can I do to retrieve both BooleanField value? -
Extract Objects from a Model using Filter on the 2nd Model Class
I have the following few Classes in my models.py class Account(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) class Challenge(models.Model): match_time = models.DateTimeField(null=True) totalPlayers = models.IntegerField(default=1) status = models.CharField(max_length=100, default="pending") created_by = models.ForeignKey(Account, on_delete=models.CASCADE) expiry_time = models.DateTimeField(null=True) class Challenge_Participant(models.Model): player = models.ForeignKey(Account, on_delete=models.CASCADE) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) status = models.CharField(max_length=100, default="pending") What I am trying to do is actually access all the Challenge objects in which the logged in user is participating (so in Challenge_Participant, player will be equal to request.user.account and challenge will be equal to the challenge being searched) and exclude those challenges which are created by the User itself (because the challenges in which user is participating himself, there is an object of Challenge_Participant for this case as well) I am unable to make a query to extract all the Challenges in which request.user is part of. I am trying to do something like this, challenges = Challenge.objects.filter().exclude(created_by = request.user.account) I want to Filter Out those challenges in which the Challenge_Participant objects have user equal to the logged in user and challenge equal to the challenge being searched. I can't seem to figure out what I can write in the Filter comamnd in such a … -
How would I get all Id of all items from the Django template by JavaScript?
django template: I want to fetch all item id from request.user.UserShoppingCartRelatedName.all. Here problem is, I'm just getting the first index's id of request.user.UserShoppingCartRelatedName.all instead of all index's id. How can I get all item's id? Please help me.. {% for ShoppingCart in request.user.UserShoppingCartRelatedName.all %} Product Id: <label class="GetId"></label> <script> document.querySelector(".GetId").innerHTML = "{{ShoppingCart.Product.id}}"; </script> {% endfor %} -
In a Django project, is it a good idea to completely replace Gunicorn by Daphne?
We currently have a complex website that runs in Django 4. We also use : PostgreSQL for the DB Celery for background tasks Django Channels for WebSockets Redis as a message broker (for Celery and Channels) Gunicorn for non-ws requests Daphne for ws requests Nginx which, among other things, redirect to the Daphne server the ws requests and to Gunicorn the non-ws requests This works just fine. But theoretically, Gunicorn is not needed in this configuration, we could tell Daphne to handle everything. However, would this be a good idea ? Since Gunicorn is perhaps more bulletproof, better tested, more used and documented (but on the other hand, it would allow us to remove a non-necessary technology to a pretty heavy stack). Thank you for your inputs. -
How do I implement snap chat streak like feature?
I am failing to build logic regarding streak feature similar to Snapchat. Here is how streak gets counted in snapchat problem is. if the user adds a new data record once every 24 hours streak is one irrespective of how many records he/she adds and streak is 0 if he/she fails to add with in next time period and adds by +1 in next 24 hours timeframe from last record added. I tried this code in django but any help in any language will be valuable class ModelAnswer(BaseModel): questions = models.ForeignKey( to=Questions, on_delete=models.CASCADE ) answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) current_streak = models.PositiveIntegerField( null=True, blank=True, default=0, editable=False ) here is my main logic part this is not working as per required def save(self, *args, **kwargs): today = timezone.now() yesterday = today - timedelta(days=1) print(today,yesterday) # get the categories created yesterday to maintain the streak answers_created_yesterday = ModelAnswer.objects.filter( Q(created_at__gte=yesterday), Q(created_at__lt=today), user=self.user ).order_by('-id').last() if answers_created_yesterday is not None: self.current_streak = answers_created_yesterday.current_streak + 1 else: self.current_streak = 1 print(self.current_streak) super(ModelAnswer, self).save(args, kwargs) -
How to read barcode using Webcam in django?
I'm doing a project where I'm trying to open a webcam in django as code reader. I followed this tutorial: "https://www.youtube.com/watch?v=xz9MvyKGYio&list=WL&index=24&t=12s" where it's istruction how to open camera in django. I would like the webcam read barcode and redirect this code to another function. But i don't know how to break webcam and redirect when code is exist. So it's my views.py: from django.shortcuts import render import cv2 import threading from django.http import StreamingHttpResponse, HttpResponse from django.views.decorators import gzip from pyzbar.pyzbar import decode import time from django.shortcuts import redirect def index(request): return render(request, 'webcam/home.html') # Create your views here. @gzip.gzip_page def home(request): #https://www.youtube.com/watch?v=xz9MvyKGYio&list=WL&index=23&t=12s try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, 'app1.html') def helloView(request, code): http = f"Hello {code}" return HttpResponse(http) #to capture video class class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame ) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) ################################ # capture code /simple example / n_1 = '9788366384088' for code in decode(image): n = str(code.data.decode('utf-8')) if n_1 == n: print(n) time.sleep(5) # how to redirect to helloView? ########################### return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame … -
CSRF token not set: Cause & Solution
I am using the Cookiecutter Django template. I made a custom user model extending from AbstractUser. In the user app, I made a view to list and register new users and used the rest_framework_simplejwt.views.TokenObtainPairView. views.py class UsersListCreateAPIView(ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] filter_backends = [DjangoFilterBackend, SearchFilter] search_fields = ["name"] settings/base.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CSRF_COOKIE_SECURE = False urls.py app_name = "users" urlpatterns = [ path("", UsersListCreateAPIView.as_view(), name="users"), path("token", TokenObtainPairView.as_view(), name="log in"), ] Now when trying to login user via Post request to "/api/users/token/" I get CSRF token not set. One thing I tried was to swap the views with the endpoints ie edited urls.py app_name = "users" urlpatterns = [ # path("", UsersListCreateAPIView.as_view(), name="users"), # path("token", TokenObtainPairView.as_view(), name="log in"), path("", view=TokenObtainPairView.as_view(), name="users"), path("token", UsersListCreateAPIView.as_view(), name="log in"), the login now works at "api/users/", but the post request of "api/users/token/" returns CSRF token not set. Basically any Post request from "api/users/anypathname" returns 403. the get requests work fine. What seems to be the issue here? -
Save Django generated file in AWS S3
I have an app which generates a .png file. With de function below (generateFile()) two images are pasted together and saved in the corresponding location. All this works locally at the moment. However, I want to use AWS S3 to host my files. My app is set up in the way such that the images uploaded in my model imgUpload(models.Model) are saved to AWS S3. This works aswell. Now I want to save my 'img1' not as shown below locally, but on the server. The idea was to pass it into the model. This does unfortunately not work. The error message which I get is: _committed This problem arises many question I don't know how to answer: Is there a way to save the file with .save() and specifying an AWS S3 path directly without using a model? What kind of object is the img1 file before saving it? Does it already exist, or will it only be created when the .save() function is executed? view.py def generateFile(key): img1 = Image.open(f'{current_path}/media/file.png') img2 = Image.open(f'{current_path}/media/watermark.png') img1.paste(img2, (150, 250), img2) img1.save(f'{current_path}/media/file-{key}.png') try: imgUploader = imgUpload(image=img1) imgUploader.save() except Exception as e: print(e) models.py class imgUpload(models.Model): image = models.ImageField(null=True, blank=True, upload_to="images/") -
What do Django's technologies use to communicate data throught my server
I just begin to work on a complicated project with django and I need help to choose communication technology because I'm a newbie. The problem is the following : I have a django server which received data from different deveice with PUT/PUSH request. The server store the data. And I need to send the data to another server when the actual data are update on my django server. For now, the other server send GET request each second but it's not the good way because in the future, I will have many other server which make this GET requests. And if I don't find a solution, my django server will be saturated. So I need to find a technologies to send a signal (or data) to the other server only when the data are updated on my django server. I guess that I can use Websocket to do it but I'm not sure that is the only way. Do you have any clue on how I can solve my problem ? and if websocket is the good technology to solve it Thanks