Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
rest_framework.request.WrappedAttributeError: 'AccountManager' object has no attribute 'get'
I am working on my Django project, I am getting this error but i don't really know how to fix it exactly, i have created my custom user model and the user manager class AccountManager(BaseManager): def create_user(self, email, fullname=None, birthday=None,zipcode=None, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(Email_Address=self.normalize_email(email), name=self.normalize_email(email), Date_of_Birth=birthday, zipcode=zipcode ) user.set_password(password) user.save(using='self._db') return user def create_superuser(self, Email_Address, username, password): user=self.create_user(Email_Address=self.normalize_email(Email_Address), password=password,) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using='self._db') class User(AbstractUser): Email_Address = models.EmailField(verbose_name='email', unique=True, blank=True, null=True) Date_of_Birth = models.CharField(max_length=30, blank=True, null=True, default=None) name = models.CharField(max_length=30, blank=True, null=True) username= models.CharField(max_length=30,unique=True, blank=True, null=True) zipcode = models.CharField(max_length=30, blank=True, null=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'Email_Address' objects = AccountManager() REQUIRED_FIELDS = ['username'] def __str__(self): return self.username because i am using rest_framework_simplejwt for authentication i am getting this error when i try to log in rest_framework.request.WrappedAttributeError: 'AccountManager' object has no attribute 'get' can anyone please help me with this -
What is index in load static?
please tell me what is the index in {% load static index %}? This came across to me in someone else's code. I didn't find anything like this in the documentation -
Error while trying to integrate keycloak with django
I'm trying to integrate keycloak with my django app using Djanog Keycloak and following the tutorial, but I'm getting the following error: File "/home/enzo/.local/lib/python3.10/site- packages/django_keycloak/admin/__init__.py", line 3, in <module> from django_keycloak.admin.realm import RealmAdmin File "/home/enzo/.local/lib/python3.10/site-packages/django_keycloak/admin/realm.py", line 2, in <module> from keycloak.exceptions import KeycloakClientError ImportError: cannot import name 'KeycloakClientError' from 'keycloak.exceptions' (/home/enzo/.local/lib/python3.10/site-packages/keycloak/exceptions.py) Does someone know how to solve? -
Azure Python SDK - connecting to USGov with CLI Credentials fails?
I've tried using AzureCliCredential() as noted in previous questions/the documentation - this works great in the normal azure cloud. If I'm using the USGov cloud (portal.azure.us), the same code just returns nothing; I've tried http tracing and it looks like it's still pointing at management.azure.com and not management.core.usgovcloudapi.net - but it doesn't say anything. Pretty much all things that require a subscription scope are telling me the subscription doesn't exist, and yet 'az account list' shows all of the subscriptions correctly. I've got all the python modules updated to the latest.. not sure what's wrong at this point, any ideas? just to sum up, procedure is: login with az login --use-device-code go to microsoft.com/deviceloginus (usgov device login) and put in code shell is authenticated az account list shows all of my subscriptions Run test code to list subscriptions - get no results. Trace shows that things still point at management.azure.com - if I force base_url to https://management.usgovcloudapi.net, I get an InvalidAuthenticationTokenAudience exception. Code I'm using: import logging from azure.identity import AzureCliCredential from azure.mgmt.subscription import SubscriptionClient credential = AzureCliCredential() client = SubscriptionClient(credential=credential, logging_enable=True, base_url="https://management.usgovcloudapi.net/") logging.basicConfig(filename='test_sub_debug.log', level=logging.DEBUG) aba_logger = logging.getLogger('azure.mgmt.subscription') aba_logger.setLevel(logging.DEBUG) sub_list = client.subscriptions.list() for subscription in sub_list: print(subscription) # (obviously remove … -
Django i18n does not work with Nginx. Keep redirecting to homepage
Right now I have a django + gunicorn + nginx setup. Everything works: able to switch between the two language set the cookies add the lang prefix in the middle: projurl.com/lang_code/other_dir able to redirect/stay on the page where language switch happened But ... All 1,2,3,4 are working with django dev server (python manage.py runserver) and gunicorn proj.wsgi:application --bind 0.0.0.0:8000 Only 1,2,3 work with nginx. It keeps redirecting to homepage with the right language, but unable to stay on the page where language switch happened. proj/urls.py: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( re_path(r'^admin/', admin.site.urls), re_path(r'', include('app1.urls')), ) In template I have exact example from django i18n translation: link {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> nginx.conf upstream proj { server web:8000; } server { listen 80; location /static/ { alias /static/; … -
How to assign new value to a ModelForm field which form edits user data, to test if the data will be edited Django test TestCase
I'm testing Django forms handling and trying to test a ModelForm, which form edits the user's data. I tried to write the test in several ways, but each one throws different mistakes. And all the mistakes are related to the data, that I try to assign to the form. I create a user and profile because in my app the user model is extended and trying to change profile.first_name from 'Test' to 'Edited'. This is the test: class ProfileEditFormTests(TestCase): def test_if_form__can_change_passed_data__expect_success(self): """ Test ProfileEditForm if can edit a valid data: -Change profile.first_name from 'Test' to 'Edited' """ user, profile = self.__create_valid_user_and_profile() form_data = { 'first_name': profile.first_name, 'last_name': profile.last_name, 'image': profile.image, 'description': profile.description, 'phone_number': profile.phone_number, 'email': profile.email, } updated_form_data = { 'first_name': 'Edited', } form = ProfileEditForm(data=updated_form_data, instance=profile) # Error: # self.assertTrue(form.is_valid()) # AssertionError: False is not true # on debug, the form have only data.first_name = 'Edited' # and the another fields are empty self.assertTrue(form.is_valid()) form.save() self.assertEqual(updated_form_data['first_name'], profile.first_name) This is the error that occurs when I try to assign a form_data to the form instance. form = ProfileEditForm(data=updated_form_data, instance=form_data) # Error # Traceback (most recent call last): # object_data = model_to_dict(instance, opts.fields, opts.exclude) # opts = instance._meta # AttributeError: 'dict' … -
show all user purchased products in django-oscar
I am trying to render all user purchased products on django-oscar and i am having some problems. I can print all orders by user in order.order OrderProduct.objects.filter(user=user) but it doesn't print each product by itself if order include few products (which saved on order.line) I can also print all products in orders.line LineProduct.objects.all() but i can't filter them by user since there is no user field in order.line. I can add user field on order.line and copy from order each time order is placed but I don't think this is the best solution. Anyone have any idea for a solution? Thanks in advance -
how to add Angular + Django app on GitHub?
I have an angular web app. I use the Django rest framework for the backend. I deploy the angular app on Github. Now how can I deploy Django code? Should I create a separate repository for angular and Django? OR Should I Create One repository and push both of them into a single directory? (How to do that?) In my local machine django code and angular code both are in the Project folder. What is the best way to do ..? -
Django failing send email within a view
Hi I am trying the send email within the update view, when I put the view in test.py, and run test.py, it is working import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') from django.core.mail import send_mail send_mail('Notification from covid-tracker application', 'You have a new notifications from the application, please go to dashboard to confirm ', 'covidtracker390@gmail.com', ['zosanivan@gmail.com']) But when I tried to put it in the updateview it doesn't work, how to fix that? class PatientUpdateViewSet(generics.UpdateAPIView): # permission_classes = (permissions.IsAuthenticated,) # queryset = Patient.objects.all() serializer_class = RegisterPatientSerializer def get_object(self): # print("---------------------------------------------------------------") # print(self.request.data) return Patient.objects.get(user_info=self.request.data.get('user_info')) def perform_update(self, serializer): instance = super(PatientUpdateViewSet, self).perform_update(serializer) send_mail('Notification from covid-tracker application', 'You have a new notifications from the application, please go to dashboard to confirm ', 'covidtracker390@gmail.com', ['zosanivan@gmail.com']) return instance I want when I run python manage.py and when I use this view the email is sent, how to fix this problem? -
Issue Defining Functions with python
Am verifying a payment with paystack and I have a model with amount, ref, verify status already. when this view below is passed the staus automatically update as successful. But am having issue defining an action i want immediately this payment is verified. CLARIFICATION I want the amount paid added to the user balance on the website but writting this code seems difficult for me. class PayStack: PAYSTACK_SECRET_KEY = settings.PAYSTACK_SECRET_KEY base_url = 'https://api.paystack.co' def verify_payment(self, ref, amount, *args, **kwargs): path = f'/transaction/verify/{ref}' headers = { "authorization": f"Bearer sk_test_bbvvgfffggg6517d22e20784a85eeeb5f7b4 ", "Content-Type": 'application/json' } url = self.base_url + path response = requests.get(url, headers=headers) user = request.user if response.status_code == 200 : response_data = response.json() with transaction.atomic(): account = Account.objects.select_for_update().get(user=request.user) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) return response_data['status'], response_data['data'] response_data = response.json() return response_data["status"], response_data["message"] i want this to happen immediately the payment is verified with transaction.atomic(): account = Account.objects.select_for_update().get(user=request.user) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) -
Is there any way to store list in database in django?
this is the list I have to insert in the database i get this error while inserting in the database -
How does one write Python code that merges 2 files created using wkhtmltopdf into 1 pdf file using pypdf2
I have an application with the back-end written in Python that converts html files to pdf files. To do this it implements wkhtmltopdf (https://wkhtmltopdf.org/). It currently works perfectly for creating a single PDF file from an html file and outputs that to the user. However, I need to be able to create multiple separate PDF files and then merge the files together into a single PDF. I have been trying to do this using Pypdf2 with the PdfFileMerger() function (https://pythonhosted.org/PyPDF2/PdfFileMerger.html) and haven't been able to do it. I keep getting 'bytes' object has no attribute 'seek' Here is my current code: def multi_test_sheet(request, equipment_id): if not request.user.is_authenticated: return render(request, "jobs/login.html", {"message": None}) from io import BytesIO from PyPDF2 import PdfFileReader, PdfFileMerger if not request.user.is_authenticated: return render(request, "jobs/login.html", {"message": None}) equipment = Equipment.objects.filter(pk=equipment_id).first() if not job: raise Http404("test sheet error. Error code: get job failed") pdf_write = PdfFileWriter() user_properties=UserProperties.objects.get(user=request.user) context = { "equipment": equipment, "job": equipment.equipments, "test_sheet": equipment.sheet_eq, "user_properties": user_properties, "now": datetime.now().strftime("%b-%d-%Y %H:%M"), "now_date": datetime.now().date() } html_sheet = render_to_string('jobs/test_sheet_gear1.html', context) html_sheet2 = render_to_string('jobs/test_sheet_gear2.html', context) pdf_content1 = pdfkit.from_string(html_sheet, None) pdf_content2 = pdfkit.from_string(html_sheet2, None) pdfadder = PdfFileMerger(strict=False) pdfadder.append(pdf_content1) pdfadder.append(pdf_content2) pdf_adder.write("combined_sheets.pdf") response = HttpResponse(pdf_adder, content_type="application/pdf") response["Content-Disposition"] = f"filename={equipment.site_id}.pdf" return response -
How do I create a Django / Ajax redirect POST request on click?
I have a search function in my django app using ajax. It displays all results from a model. I want to limit the number of results the search returns on the page though, so when the queryset is so large the user should click on a 'see all results', rather than having heaps of results in the search box. I'm trying to do this by adding a HTML form below, but when I click on the href it is creating a GET request. I'm not totally sure what I need to fix up here to pass the data to the view and render the new page. resultsBox.innerHTML += ` <a href="${url} ${'results'}" class="item"> <form method="POST" class="post-form" input type="submit" {% csrf_token %} <action="${url} ${'results'}"> </form> <div class="row mt-2 mb-2"> <div class="col-2"> img placeholder </div> <div class="col-10"> <h5>See all results for "${quote}"</h5> </div> </div> </a> ` ` -
SMTPSenderRefused Error using Django and Sendgrid
I've been struggling for days trying to get SendGrid to send an email from a contact page on a website I'm building. First, it was SMTPServerDisconnected errors, and I think I fixed that now it's this SMTPSenderRefused Error. settings.py #Load environment variables from .env file SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') #Email for contact form EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY DEFAULT_FROM_EMAIL = 'some-email@hotmail.com' SENDGRID_SANBOX_MODE_IN_DEBUG = False views.py: def contact(request: HttpRequest) -> HttpResponse: if request.method == "GET": form = ContactForm() elif request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): name = bleach.clean(form.cleaned_data["name"]) email = bleach.clean(form.cleaned_data["email"]) subject = f'Message from {name} about {bleach.clean(form.cleaned_data["subject"])}' message = bleach.clean(form.cleaned_data["message"]) recipients = [settings.DEFAULT_FROM_EMAIL] try: send_mail(subject, message, email, recipients, fail_silently=False) except BadHeaderError: return render(request, "contact.html", {"form": form, "success": False}) form = ContactForm() return render(request, "contact.html", {"form": form, "success": True}) else: raise NotImplementedError return render(request, "contact.html", {"form": form}) I've switched between fail_silently=False and fail_silently=True, but when it's true the email doesn't send through anyways so I've just left it false for now. Lastly, here is the traceback I got: Environment: Request Method: POST Request URL: http://localhost:8000/contact/ Django Version: 4.0 Python Version: 3.9.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
How do you insert a record in an empty Django migration?
I'm using Django 3.2 with a PostGres 14 db. I have the following model ... class Vendor(models.Model): class VendorNames(models.TextChoices): MYCO = 'MyCo', _('MyCo') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, null=False, choices=VendorNames.choices) objects = VendorManager() I have created an empty migration with python manage.py makemigrations --name insert_binance_vendor_record cbapp --empty and now I would like to populate it with an operation to insert a record into my Vendor table. How do I do that? -
Sending data from template to Django views via button
I'm trying to create a delete button in my template: <button type="submit" class="btn btn-danger" value={{ instance.name }}> Delete </button> And I want this button to submit that data in my views.py : instance_client = compute_v1.InstancesClient() if request.method == "POST": instance = request.POST['data'] instance_client.delete(project='xxx', zone='xxx', instance=HERE_I_WANT_THE_DATA) It's a script that will delete an instance from gcloud. But I don't know exactly how to deliver the data from the template to views.py. I'm using Bootstrap 5. -
Generic ManyToMany for multiple inherited models
First of all, the following code is not an example of best practices in DB modelling and I know it, unfortunately, this is already made and it's what it is. Remodelling everything is just not an option. I have the following models: models.py class OtherModel(models.Model): ... class AbstractSite(models.Model): class Meta: abstract = True class Site(AbstractSite): ... class Banner(Site): data = models.ManyToManyField(OtherModel, blank=True) The issue is, this many-to-many is supposed to be present both in the Site and the Banner models. I've tried to specify it in the Abstract Model, and it created a site_data table, but data saved in the Banner model was also populating this table, instead of populating a banner_data as I was expecting. The easiest way is to create a new field in the Site model, named differently from the data field in the Banner model, but this doesn't seem to be correct, since any new child model would need a new table being declared. I was expecting to find a way to dynamically allocate this in the DB. Is there a way to create a dynamic through parameter that follows the class child class name? -
Getting error not found url while making post request to specific url with htmx in Django
I am making like function to my blog without page refreshing. But getting error [06/Apr/2022 20:48:26] "POST /like/post/4/ HTTP/1.1" 404 3945 Here what I do base.html with htmx settings <!-- Load from unpkg --> <script src="https://unpkg.com/htmx.org@1.7.0"></script> <script> document.body.addEventListener('htmx:configRequest', (e) => { e.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) </script> views.py def add_like_post(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(post.get_absolute_url()) urls.py urlpatterns += [ path('like/post/<int:pk>/', add_like_post, name='like-post'), ] post-detail.html {#<form method="post" action="{% url 'like-post post.id %}">{% csrf_token %}#} <button hx-post="{% url 'like-post' post.id %}" hx-target="#likes" id="likes" hx-swap="outerHTML" class="btn btn-block btn-outline-secondary btn-lg mb-2 mx-auto" name="post_id" value="{{ post.id }}"><i class="fa fa-thumbs-up"> L i k e - {{ post.number_of_likes }}</i></button> {# </form>#} It works fine when I remove htmx settings from button and adding type='submit' and also uncommenting form. Is there are anything which I did wrong -
How to get all field details in a django LogEntry()
I have a LogEntry items I'dlike to call one by one to make a table. So far I have managed to get it working partially with this. <table class="layout"> <thead> <th>User</th> <th>Date</th> <th>Log</th> <th>Item Affected</th> <th>Item ID</th> </thead> {% for log in logs %} <tr> <td>{{ log.user}} - {{ log.user_id }}</td> <td>{{ log.action_time|date:"d/m/Y - g:ia" }}</td> <td>{{ log }}</td> <td>{{ log.object_repr }}</td> <td>{{ log.object_id }}</td> <td>{{ log.change_message }}</td> </tr> {% endfor %} </table> <td>{{ log.change_message }}</td> Gives me data in this format. [{"changed": {"fields": ["Borrower id"]}}] When I try {% for log in logs %} {{ log }} {% endfor %} I get data in this format. Changed “Smart Maths:-MAT/1663/21” — Changed Borrower id. What would I call in my template in order to get this last part only???? Changed Borrower id -
Django/Python - overwrite initial loaded values
I'm quiet new to Django, and I've been struggling with the following: I have a view that initially has set1=0(False) and set2=1(True). A user can swap this,so to set set1=1(True) and set2=0(False). The user can do this by pushing the 'Update' button. My problem is, that it does change in the backend, but the frontend/view/html is not updated. And I have no idea why.. I created a small example, which, if this works, I'll also get my Django case working.. I have the following: views.py So first this view is used, and the initial values for set1 and set2 are set: class MainSettingsView(generic.TemplateView): extra_context = {"main_page": "active"} context_object_name = 'main' template_name = 'index.html' set1 = int(model.set1 == True) set2 = int(model.set2 == True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) model = Setting12.objects.get(pk=1) context['set1'] = int(model.set1 == True) context['set2'] = int(model.set2 == True) return context And then, based on the chosen option in the radio buttons, it changes the model/db and therefore also the set1 and set2: class UpdateButton(generic.TemplateView): extra_context = {"main_page": "active"} context_object_name = 'setting12' template_name = 'index.html' def post(self, request, queryset=None, *args, **kwargs): if update_type == "set1": model = Setting12.objects.get(pk=1) model.set1 = True model.set2 = False return redirect(reverse("main")) elif … -
Can there be two celery instances in a django application?
I have a use case of using two celery instances in a same django application. One celery instance is used for incoming events to the app and the other is to publish an event to an external django application. Doing this is making connections to the celery workers timeout and blocking both the instances. -
Problem with adding objects to manytomany fields
I have a User model: class User(AbstractUser): followers_num = models.IntegerField(default=0) followings_num = models.IntegerField(default=0) followers = models.ManyToManyField('self', null=True, blank=True) followings = models.ManyToManyField('self', null=True, blank=True) And there's a view for adding/removing user objects from followers/followings: def follow(request, follow, user): if (request.method == 'PUT'): following_user = User.objects.get(username=user) follower_user = User.objects.get(username=request.user.username) if follow: # Follow following_user.followers.add(follower_user) following_user.followers_num += 1 follower_user.followings.add(following_user) follower_user.followings_num += 1 else: # Unfollow following_user.followers.remove(follower_user) following_user.followers_num -= 1 follower_user.followings.remove(following_user) follower_user.followings_num -= 1 following_user.save() follower_user.save() return HttpResponse(status=204) I want it to add follower_user to the followers of following_user and add following_user to the followings of follower_user. However, instead of doing so, it adds follower_user not only to the followers of following_user, but it also adds it to the followings of following_user. Why does it happen? -
psycopg2.OperationalError after makemigrations
I am trying to python manage.py makemigrations for a django app in postgres, but I am getting the follow error: psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "backend_db" does not exist Before this, I am doing docker compose up with the following docker-compose and .env file: version: '3.2' services: postgres: image: postgres:13.4 environment: POSTGRES_DB: backend_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - postgres volumes: database-data: driver: local networks: postgres: driver: bridge DB_NAME='backend_db' DB_USER='postgres' DB_PASSWORD='postgres' # DB_HOST is localhost or the IP of the machine running postgres DB_HOST='localhost' DB_PORT='5432' The part of the settings.py that I define the postgres is the following: DATABASES = { 'default': get_config( 'DATABASE_URL', 'sqlite:///' + BASE_DIR.child('db.sqlite3'), cast=db_url ), 'postgres': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_config('DB_NAME', 'backend_db'), 'USER': get_config('DB_USER', 'postgres'), 'PASSWORD': get_config('DB_PASSWORD', 'postgres'), 'HOST': get_config('DB_HOST', 'postgres-service'), 'PORT': get_config('DB_PORT', '5432') } } Any idea of what causes the error? -
How to use pillow library to make image from letters in django?
When I try to draw images from the pillow library in django website hosted from pythonanywhere server it shows me an error with : OSError at /confession cannot open resource Request Method: POST Request URL: https://luckyklyist.pythonanywhere.com/confession Django Version: 4.0.3 Exception Type: OSError Exception Value: cannot open resource Exception Location: /home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/PIL/ImageFont.py, line 193, in __init__ Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/home/Luckyklyist/Confess/Confessout', '/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages'] Server time: Wed, 06 Apr 2022 14:58:13 +0000 My code to work : def confession(request): if request.method=="POST": message=request.POST.get('confession-msg') ide=random() # Drawing image img = Image.new('RGB', (1080, 1080), color=(0, 0, 0)) d1 = ImageDraw.Draw(img) myFont = ImageFont.truetype("arial.ttf", size=40) words = message lines = textwrap.wrap(words, width=60) a = 0 for word in lines: d1.text((0, a), word, fill=(255, 255, 255), font=myFont) a += 40 img.save(f'{ide}.jpeg') imgge='{ide}.jpeg' confess=Confession(message=message,image=imgge) confess.save() disctionary={"message":message,"activehome":"active"} return render(request,"confession.html",disctionary) But when i remove this part from the code it dosent show me error(OSError at /confession): # Drawing image img = Image.new('RGB', (1080, 1080), color=(0, 0, 0)) d1 = ImageDraw.Draw(img) myFont = ImageFont.truetype("arial.ttf", size=40) words = message lines = textwrap.wrap(words, width=60) a = 0 for word in lines: d1.text((0, a), word, fill=(255, 255, 255), font=myFont) a += 40 img.save(f'{ide}.jpeg') Models.py files … -
Convert String to datetime.timedelta
I have an input string as hundreds or thousand of hours, such as: 1000:50 (One thousand hours and 50 minutes) I need to convert it into a timedelta object, in order to insert it as a DurationField in a Django Model. So far, what I tried is to use datetime.strptime but, the error is giving me is: time data '1000:50' does not match format '%H:%M' I tried to google any kind of solution but so far I didn't find a solution that could help me. Even though the DurationField will convert the timedelta in number of days, I just need to have the input to be as thousand or hundreds of hours, after that, the calculation will be handled in the backend.