Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send pdf files with cyrillic text in django?
I'm trying to generate pdf files in django and upload them. To do this, I use the reportlab library. django v4.2.7 reportlab v 4.0.7 Here is a fragment of my code def patients_report_view(request): title = f'Отчет Выгрузка карт {datetime.now().strftime("%d.%m.%Y")}' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename="{title}.pdf"' font_path = settings.STATICFILES_DIRS[0] + '\\fonts\\DejaVuSerif.ttf' pdfmetrics.registerFont(TTFont('DejaVuSerif', font_path, 'UTF-8')) p = canvas.Canvas(response) p.setFont('DejaVuSerif', 12) p.drawString(100, 100, "Привет мир.") p.showPage() p.save() return response I also installed some fonts for the Russian language, but still incomprehensible characters are displayed in the file. -
How to `annotate` in Django without using `LEFT OUTER JOIN`
Having models like Company, NotificationGroup and Notification I'm trying to sort by max notification importance Company.objects.annotate(max_importance="notification__importance").order_by("max_importance") By default djange generate LEFT OUTER JOIN for the annotate. MAX("grow_userrulenotification"."importance") AS "max_importance", MAX("grow_userrulenotificationgroup"."latest_timestamp") AS "max_timestamp" FROM "core_company_info_ukcompany" LEFT OUTER JOIN "grow_userrulenotificationgroup" ON ("core_company_info_ukcompany"."id" = "grow_userrulenotificationgroup"."uk_company_id") LEFT OUTER JOIN "grow_userrulenotification" ON ("grow_userrulenotificationgroup"."id" = "grow_userrulenotification"."notification_group_id") INNER JOIN "grow_userrulenotificationgroup" T4 ON ("core_company_info_ukcompany"."id" = T4."uk_company_id") INNER JOIN "grow_userrulenotification" T5 ON (T4."id" = T5."notification_group_id") how to force django to use existing INNER JOINS for aggregation functions? MAX(T5."importance") AS "max_importance", MAX(T4."latest_timestamp") AS "max_timestamp" FROM "core_company_info_ukcompany" INNER JOIN "grow_userrulenotificationgroup" T4 ON ("core_company_info_ukcompany"."id" = T4."uk_company_id") INNER JOIN "grow_userrulenotification" T5 ON (T4."id" = T5."notification_group_id") -
why is my chatbot is not sending responses when it does not have an error?
@csrf_exempt def home(request): if request.method == 'POST': data = request.body.decode("utf-8") try: data_json = json.loads(data) response = JsonResponse({'status': 'success'}, status=200) Thread(target=process_data, args=(data_json,)).start() return response except json.JSONDecodeError as e: return JsonResponse({'status': 'error', 'message': str(e)}, status=400) else: return JsonResponse({'status': 'invalid request'}, status=400) def process_data(data): chatID = data.get('waId') msg = data.get('text') if chatID and msg: try: track_obj, created = Track.objects.get_or_create(id=chatID) handle_message(track_obj, created, chatID, msg) except Exception as e: print(f"Error processing data: {str(e)}") def handle_message(track_obj, created, chatID, msg): if created: track_obj.status = "welcome" welcome_message = 'Welcome to AFC Insurance! I am here to assist you with any insurance-related queries or concerns. Whether you are looking for policy information, claims assistance, or need guidance, feel free to ask. Your peace of mind is our priority! How can I help you today?' sendMessage(chatID, welcome_message) options_message = "Choose an option:\n1. Register Vehicle\n2. Make a Claim\n3. Lodge a Complaint" sendMessage(chatID, options_message) track_obj.status = "home" track_obj.save() elif track_obj.status == "home": # Handle other cases for track_obj.status == "home" pass i tried everything i know in the book but its not showing any errors but its not sending any resonse. -
Paginate items after filtering by ajax
guys! I have a page with brands and two checkboxes list, category and country. I realized filter logic by jsonresponse, and ajax: its my filter view its my checkbox template its my js its a part of my page template my filter view work for and finally, all my page template looks like this its all work correctly. now I need add pagination, but I have a problem - my checkboxes filtering rendered by filter_data view, and my main page template rendered by another view, this: my main view so, when I try add paginate to my filter_date view, calculations my objects by paginator works good, but when i submit to the second page, logic stop working. I have no idea, how to realize this, please, help me ;) -
how can i save local file in django models
i want to save a local file in django model. and i am using this codes: with open('data.json', 'w') as file: file.write('somethings') myModel.objects.create(file=file, name='name') this codes save data.json in root path: root image but when i want to create model this codes raised following error: AttributeError: '_io.TextIOWrapper' object has no attribute 'field' how can i save data.json in myModel??? -
Celery progress bar isn`t being updated
i am developing some Django app, which generates reports. I am using celery to enable progress bar after hitting 'submit' button. The problem is that I cant figure out what i am missing and why ProgressRecorder isnt being set properly, so it stays at 0 always, although the task is being executed and i can get results of it. It is my celery task: @shared_task(bind=True) def regular_report(self, year: int, month: str, device_groups: list, prom_url: str): global speed, full_alias, short_alias, interfaces wb = Workbook() ws = wb.active progress_recorder = ProgressRecorder(self) # Define the column headers for the worksheet column_headers = ['Device Name', 'Interface', 'Description', 'ACDR Group (NIE only)', 'Port (G/Sec)', 'Speed (G/Sec)', f"Hyperlink to interface {month}-{year}", f'95th Util {month}-{year}',f'95th In {month}-{year}', f'95th Out {month}-{year}', f'Avg Util In {month}-{year}',f'Avg Util Out {month}-{year}', f'Max Util In {month}-{year}', f'Max Util Out {month}-{year}'] ws.append(column_headers) total_devices = [] for group in device_groups: total_devices += devices(group) done = 0 # Iterate through device groups for group in device_groups: device_list = devices(group) # Iterate through devices in the group for device in device_list: # Determine interfaces based on the group if group == "SOB": interfaces = info(queries(group, device, year, month, 'WAN')[4], 0, prom_url)[0] # getting all interfaces of … -
DJANGO-choicefield not appearing in website
views.py def remark_proof_api(request, room_id, bills_slug): submission_form = SubmissionForm() try: room = Room.objects.get(join_code=room_id) room_bills = bills.objects.get(room=room, slug=bills_slug) if request.method == "POST": data = json.loads(request.body.decode("utf-8")) submission_id = data.get("subId") status = data.get("status") if submission_id is not None and status in dict(Submission.STATUS_CHOICES).keys(): sub = Submission.objects.get(id=int(submission_id)) sub.status = status sub.save() return JsonResponse({"success": True}) except (Room.DoesNotExist, bills.DoesNotExist, Submission.DoesNotExist, json.JSONDecodeError, ValueError) as e: return JsonResponse({"success": False, "error": str(e)}) return JsonResponse({"success": False, "error": "Invalid request"}) models.py class Submission(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bills = models.ForeignKey(bills, on_delete=models.CASCADE) proof = models.FileField(null=True) STATUS_CHOICES = (('P', 'Pending'), ('A', 'Accepted'), ('R', 'Rejected')) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='P') html {% extends "base/room_home.html" %} {% block content %} <div class="container d-flex align-items-center justify-content-center" style="min-height: 100vh;"> <div class="text-center"> <h1>{{ room_bills.title }}</h1> <p>Due: {{ room_bills.due }}</p> <div class="col-3"> <h3>Paid Members: </h3> <ul> {% for submission in submissions %} <li> <a href="proof/{{ submission.user.id }}" target="_blank">{{ submission.user.username }}</a> {% if submission %} <form class="statusForm" data-subid="{{ submission.id }}"> {% csrf_token %} {{ submission_form.as_p }} <button type="submit" class="btn btn-primary">Update</button> </form> {% endif %} </li> {% endfor %} </ul> </div> <div class="col-3"> <h3>Did not pay members: </h3> <ul> {% for user in did_not_submit %} <li>{{ user.username }}</li> {% endfor %} </ul> </div> </div> </div> <script> document.querySelectorAll('.statusForm').forEach(form => { form.addEventListener('submit', e => { … -
Malloc: double free error on M3 Macbook pro
I am working on a Django python project with a postgres db hosted with render.com. The code works fine on server and my imac. I recently got a Macbook Pro M3 (running sonoma). I have replicated the exact same setup and environment however when I try to run the code locally, I get Python(40505,0x1704f7000) malloc: double free for ptr 0x1368be800 Python(40505,0x1704f7000) malloc: *** set a breakpoint in malloc_error_break to debug The setup is the exact same on the other device and it works fine there. Here is the link to repo https://github.com/moreshk/django-postgres Any assistance would be useful. Setup https://github.com/moreshk/django-postgres on my new device. Setup virtual environment, any dependencies and installed requirements and .env file. Would have expected it to run fine locally. Other Django Python projects seem to work fine, except this one which has a postgres db with render.com When I try to run the code locally, I get the below error: python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Python(40505,0x1704f7000) malloc: double free for ptr 0x1368be800 Python(40505,0x1704f7000) malloc: *** set a breakpoint in malloc_error_break to debug -
How to convert a geodataframe in Django to json file and save it to MEDIA_ROOT?
I have two geodataframes and I want to clip them and save them as a json file in the local memory. I used the following codes for this: def clip_feature(request): gdf1 = gpd.read_file(firstJson.path, driver='GeoJSON') gdf2 = gpd.read_file(secondJson.path, driver='GeoJSON') clip = gpd.clip(gdf1, gdf2) save = clip.to_json() return JsonResponse({'somethings': True}) now i want to save 'clip' as json file in local memory. and to_json cant do this. How can I do this? -
I Want To Create AN API Of Notifcation App
I Created AN Notification App By Using The Django Channels, Websockt and Successfully Sending Notification To The Webscoketking.com, Now I Want To Create The API of This App For Sending The Notifications Of the Website, I Want To Create AN Api For Send The Notifications On Frontend But It Successfullly Sending Notification on Websocketking models.py from django.db import models from django.contrib.auth.models import AbstractUser from channels.layers import get_channel_layer from asgiref.sync import async_to_sync import json # Create your models here. class CustomUser(AbstractUser): """Model class for users""" USER_CHOICES = [ ('expert', 'Expert'), ('business', 'Business'), ('admin', 'Admin'), ] username = models.CharField(max_length=40, null=True, blank=True) full_name = models.CharField(max_length=40) email = models.EmailField(unique=True) password = models.CharField(max_length=40, null=False, blank=False) confirm_password = models.CharField(max_length=40, null=False, blank=False) user_choices = models.CharField(max_length=30, choices=USER_CHOICES, default='expert') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self) -> str: return f"{self.email}" class Notification(models.Model): account_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) message = models.TextField() is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): print('saving notification') channel_layer = get_channel_layer() notification_objs = Notification.objects.filter(is_read=False).count() data = {'count': notification_objs, 'current_notification': self.message} async_to_sync(channel_layer.group_send)( "test_group", { "type": "send_notification", "value": json.dumps(data) } ) super(Notification, self).save(*args, **kwargs) class AccountApproval(models.Model): account_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) approved = models.BooleanField(default=False) approval_message = models.TextField(blank=True, null=True) COnsumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import … -
Is there an easy way to suppress ResourceWarning when running tests -Wd
Is there a way on the Python or Django command line to suppress ResourceWarning when running tests with python -Wd i.e. python -Wd ./manage.py test ... A bunch of my tests don't close files, which is no problem because the test class instance which opened them goes away and that closes the file. I don't want to spend time editing all the tests. But fishing through the ResourceWarnings for the DeprecationWarnings is rather painful. -
Total worktime calculation displaying problem , Python, Django
[views.py 2 Html page |Django, where it is displaying the data ](https://i.stack.imgur.com/ahx95.png) Views.py 1 i am a beginner and i am building a project in python where you have a clock in clock out and break in break out for employees, so we can calculate the total worktime and i am getting the total calculated time but there is a problem when again calculating the same email(employee) the previous days date is also updating when its displaying on the html page(Django), only the date is being changed, is there something wrong with the way i am passing the data to the html page or is the problem how i print it ? i need the data of each employees worktime of every day in the table -
convert image to resp(<class 'urllib3.response.HTTPResponse'>) type in Django
previous code : resp = requests.get(IMAGE_API, params={'empid': employee_id}, stream=True).raw return resp resp type is <class 'urllib3.response.HTTPResponse'> now i want to resize this image and return in 'resp form'. How to do it? image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) imageResized = cv2.resize(image, (0,0) , fx = ratio, fy = ratio ) imageResized type is <class 'numpy.ndarray'> how can i convert imageResized to 'resp' type ? -
How to save recorded video file to my filesystem with Javascript and Django?
I'm working on a site where users can make a video from themselves. I'm using Django but I'm not so familiar with advanced JavaScript. I'm using JavasScript code to record the video which is not my code I found it. It works well and downloads the recorded video but I like to save the video to my filesystem instead of download and upload manually or send it to a fileinput with the /documents/videointerview path to save. html <div id="container mx-auto"> <video id="gum" class="mx-auto w-50 d-flex justify-content-center" autoplay muted></video> <video id="recorded" class="mx-auto w-50 d-flex justify-content-center" playsinline loop></video> <div class="my-5"> <button class="btn btn-primary" id="start">Start camera</button> <button class="btn btn-success" id="record" disabled>Record</button> <button class="btn btn-warning" id="play" disabled>Play</button> <button class="btn btn-secondary" id="download" disabled>Download</button> </div> <div class="m-3"> <h4 class="text-info">Video Stream Options</h4> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="echoCancellation"> <label class="form-check-label text-center" for="flexSwitchCheckDefault">Echo Cancellation</label> </div> </div> <div> <span id="errorMsg"></span> </div> </div> js let mediaRecorder; let recordedBlobs; const errorMsgElement = document.querySelector('span#errorMsg'); const recordedVideo = document.querySelector('video#recorded'); const recordButton = document.querySelector('button#record'); const playButton = document.querySelector('button#play'); const downloadButton = document.querySelector('button#download'); recordButton.addEventListener('click', () => { if (recordButton.textContent === 'Record') { startRecording(); } else { stopRecording(); recordButton.textContent = 'Record'; playButton.disabled = false; downloadButton.disabled = false; } }); playButton.addEventListener('click', () => { const superBuffer … -
Django 3.2/Django-cms 3.11: LookupError: Model 'accounts.CustomUser' not registered
I am encountering an issue when trying to add PlaceholderField from cms.models.fields in my events.models module to the EventVenue model. from cms.models.fields import PlaceholderField class EventVenue(models.Model): name = models.CharField(_('name'), max_length=255) slider = PlaceholderField('room_slider') the settings: INSTALLED_APPS = [ 'modeltranslation', 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.forms', 'haystack', 'accounts', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'simple_history', 'crispy_forms', 'crispy_bootstrap5', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_forms', 'django_flatpickr', 'phonenumber_field', 'bgv_cms', 'ddz_cms', 'events', 'mail_list', ] AUTH_USER_MODEL = 'accounts.CustomUser' the custom user class: class CustomUser(AbstractUser): organization = models.ForeignKey(Organization, on_delete=models.SET_NULL,blank=True, null=True, related_name='employee') mailing_list = models.ManyToManyField(to='MailList', related_name='mail_list', blank=True, verbose_name=_('Mailing lists')) room = models.CharField(_('Room Mailing Lists'), max_length=100, choices=FLOOR, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('username',) objects = CustomUserManager() def __str__(self): return self.get_full_name() or self.username Here's the relevant part of the traceback: from events.models import EventVenue File "C:\Users\SAIF\Desktop\projects\bgv\bgv\events\models.py", line 17, in <module> from cms.models.fields import PlaceholderField File "C:\Users\SAIF\Anaconda3\envs\bgv\lib\site-packages\cms\models\__init__.py", line 3, in <module> from .permissionmodels import * # nopyflakes File "C:\Users\SAIF\Anaconda3\envs\bgv\lib\site-packages\cms\models\permissionmodels.py", line 19, in <module> User = apps.get_registered_model(user_app_name, user_model_name) File "C:\Users\SAIF\Anaconda3\envs\bgv\lib\site-packages\django\apps\registry.py", line 273, in get_registered_model raise LookupError( LookupError: Model 'accounts.CustomUser' not registered. i have tried to change the app order in the INSTALLED_APPS and inherit from the `PermissionsMixin` in … -
Multithreaded Script Does not Increment Order Number Properly for a Django Database Entry
I have an images endpoint like this: /api/properties/image/ and I can post an image to the endpoint, and that saves an image link to the Postgres database. This line of code handles the logic: def create(self, validated_data): property_id = self.context['property_ad_id'] # This line handles the update order = PropertyImage.objects.filter(ad_id=property_id).count() + 1 return PropertyImage.objects.create(ad_id=property_id, order=order, **validated_data) From the above, it counts how many images are currently in the database, stores it in memory then increments it by one, and finally, it creates a new image with that incremented value as its order. The operation works as intended until I use a multithreaded script as the one below to mass-populate the images: def single_property_upload(image_file, property_id): BASE_URL_PROPERTY = base(property_id=property_id) with image_file.open(mode="rb") as f: image_data = f.read() files_data = {"image": ("image.jpg", image_data, "image/jpeg")} response = requests.post(BASE_URL_PROPERTY, files=files_data) def post_images(image_files, id): threads = [] for image_file in image_files: # Create a new thread for each image upload t = threading.Thread(target=single_property_upload, args=(image_file, id)) t.start() threads.append(t) # Wait for all threads to complete for t in threads: t.join() def populate_images(): for i in range(1, 1001): image_files = [ Path.cwd() / "house_images2" / f"{str(randint(1, 160))}.jpg" for i in range(4) ] post_images(image_files, str(i)) print(f"Property {i} populated successfully") print("Done") populate_images() … -
Solving the Django Testing Puzzle: Incorporating JWT Tokens in Authorization for POST
I'm encountering an issue while testing a Django REST Framework endpoint that requires authentication and authorization using the IsAdminUser permission class. The endpoint is designed to handle POST requests, and it checks if the authenticated user has the is_admin attribute set to True. Here's a simplified version of the endpoint code: class MyView(APIView): permission_classes = (IsAdminUser,) def post(self, request): master = request.user if master.is_admin: name = request.data['name'] I have written a test case to simulate a POST request to this endpoint, and I'm encountering the error 'AnonymousUser' object has no attribute 'is_admin' when I run the test case with the following code: class MyViewTestCase(TestCase): def setUp(self): self.client = APIClient() token = '{jwt_token}' client.credentials(HTTP_AUTHORIZATION="token " + token) self.valid_data = {"name": "A", "at": "11", "d": "11"} def test_valid_request(self): client = APIClient() response = client.post('/endpoint', self.valid_data, format='json') I have confirmed that the endpoint works correctly when tested with an authorization token in Postman. How can I properly authenticate the user in my test case to avoid this error and successfully test the authenticated endpoint? Any insights or examples on how to structure the test case for a token-authenticated POST request with the IsAdminUser permission would be greatly appreciated! -
Error Encountered When Pushing Code with Azure AD (MSAL) Integration to Azure Web App Using GitHub
I have a Django project with a built-in authentication system that works fine in both development (dev), system integration testing (SIT), and production (PROD) environments. After implementing Azure AD integration and starting the server with "sslserver," everything works fine because Django runs on HTTPS. However, when I push the code to the production environment, I encounter an error: "Application error." I encountered multiple issues during the implementation: When running the Django server using "runserver," I encountered an error: AADSTS50011: The redirect URI 'http://domain.azurewebsites.net/auth/redirect' specified in the request does not match the redirect URIs configured for the application. I identified this problem when using the sign-in feature, as it failed to authenticate and pick up the correct redirect URI. After changing the redirect URI from HTTP to HTTPS, the sign-in authentication was successful. However, when Azure AD sent a response to the Django app, another error occurred: You are trying to access "http://domain.azurewebsites.net/auth/redirect," but the return URI is "http://domain.azurewebsites.net/auth/redirect." [30/Nov/2023 11:46:33] Code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x02\x1a\x01\x00\x02\x16\x03\x03M\x12Â;Fþæw') [30/Nov/2023 11:46:33] You're accessing the development server over HTTPS, but it only supports HTTP. This issue arises when the Django project runs on HTTP. Switching to HTTPS might resolve the problem. So, … -
dropdown select showing up in views.py but not in the clean method in forms.py
I have a django template as follows <div class="container-fluid lineitem_form_container"> <div class="inner_holder"> <h2>Add Line Item</h2> <form method="post" action="{% url 'Dashboard:lineitems' %}" class="col-md-6"> {% csrf_token %} {{ form.non_field_errors }} <div class="mb-3"> <label for="{{ form.name.id_for_label }}" class="form-label">Line Item Name:</label> {{ form.name }} </div> <div class="mb-3"> <label for="{{ form.category.id_for_label }}" class="form-label">Category:</label> {{ form.category }} {{ form.new_category }} </div> <div class="mb-3"> <label for="{{ form.segment.id_for_label }}" class="form-label">Segment:</label> {{ form.segment }} {{ form.new_segment }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script> // JavaScript code to toggle visibility of new category/segment fields document.addEventListener('DOMContentLoaded', function () { var categoryDropdown = document.querySelector('#id_category'); var newCategoryField = document.querySelector('#id_new_category'); var segmentDropdown = document.querySelector('#id_segment'); var newSegmentField = document.querySelector('#id_new_segment'); // Initial state newCategoryField.style.display = 'none'; newSegmentField.style.display = 'none'; categoryDropdown.addEventListener('change', function () { newCategoryField.style.display = categoryDropdown.value === 'new_category' ? 'block' : 'none'; }); segmentDropdown.addEventListener('change', function () { newSegmentField.style.display = segmentDropdown.value === 'new_segment' ? 'block' : 'none'; }); }); </script> </div> This is my forms.py class CustomTextInput(TextInput): def __init__(self, *args, **kwargs): kwargs['attrs'] = {'class': 'form-control'} super().__init__(*args, **kwargs) class LineItemForm(forms.ModelForm): new_category = forms.CharField( max_length=255, required=False, label='New Category', widget=CustomTextInput(attrs={'class': 'form-control', 'placeholder': 'Enter new category'}), ) new_segment = forms.CharField( max_length=255, required=False, label='New Segment', widget=CustomTextInput(attrs={'class': 'form-control', 'placeholder': 'Enter new segment'}), ) class Meta: model = LineItem fields = ['name', … -
Encryption in react and Decryption in django
i'm building a authentication system using react and django, Now i have a problem i want to encrypt password in UI then send it to backend, but i don't know how to decrypt it back in django I used crypto js in frontend. const VITE_PASSWORD_KEY = import.meta.env.VITE_PASSWORD_KEY; export function EncryptString(data){ var enc_string= CryptoAES.encrypt(data,VITE_PASSWORD_KEY ).toString(); return enc_string; } so now i encrypted like this and send it to server/backend now how can i handle it in backend?? -
I have django app and also have a function for arrange data of excel file i create in this want to pick file path from url
views.py def upload_file(request): if request.method == 'POST': try: excel_file = request.FILES.get('file') file_data = excel_file.cleaned_data['file'].read() file_name = excel_file.cleaned_data['file'].name file = default_storage.save(file_name, ContentFile(file_data)) xlxs = process_file(file, process_type='json', db_type='default') if xlxs: return HttpResponse(f'File path: {xlxs}') else: return HttpResponse("There was an error during the process.") except Exception as e: # Print the exception for debugging print(f"Error in process_file: {e}") return HttpResponse("An unexpected error occurred during the process.") i want to resolve this from a library -
Django migrations does not apply in production
I'm running a django rest api inside a docker container on my local machine. I modified a model, commited the migrations and rebuild the container with docker-compose. The changes are applied correctly. Therefore, I pulled the repository on the deployement server, and proceed to rebuild the containers. However, the migrations are not reflected inside the database. Do you have any idea why, and how I could apply my changes ? Here is my entrypoint for my django container. #!/bin/bash ### WAITING POSTGRES START ### RETRIES=7docker exec -it <your_backend_container_name> python manage.py showmigrations host="postgis" while [ "$RETRIES" -gt 0 ]; do echo "Waiting for postgres server, $((RETRIES--)) remaining attempts..." PG_STATUS="$(pg_isready -h $host -U postgres)" PG_EXIT=$(echo $?) echo "Postgres Status: $PG_EXIT - $PG_STATUS" if [ "$PG_EXIT" = "0" ]; then RETRIES=0 else sleep 5 # timeout for new loop fi done # run command from CMD python manage.py makemigrations python manage.py migrate exec "$@" I tried to log into the psql container, and look manually if the modification were present. They are not. I also tried to log in into the django container and to reapply the mgirations, and it does not change anything. -
python subprocess getting error when trying to install requirements.txt
I am trying to develop an automate python scripts using python subprocess. I am using fastapi uvicorn server for build automatically djago project but got internal 500 server error fast api while installing requirements.txt for django project. I am using python 3.11 my code @app.post("/webhook") async def webhook(request: Request): try: repo_directory = 'D:/web development/ScratchFb' python_directory = 'D:/web development/ScratchFb/fbscratch/backendfb' nextjs_directory = 'D:/web development/ScratchFb/fbscratch/fontendfb' #clone git repo clone_command = subprocess.run(['git', 'clone', 'https://github_url'], cwd=repo_directory,check=True) # create virtual environment python vertual_venv = subprocess.run(['python', '-m', 'venv', 'venv'], cwd=python_directory ,check=True) # Activate the virtual environment based on the platform if sys.platform == 'win32': activate_venv = subprocess.run(['venv\\Scripts\\activate'], cwd=python_directory , shell=True, check=True) else: activate_venv = subprocess.run(['source', 'venv/bin/activate'], cwd=python_directory, shell=True, check=True) #installing requirements.txt install_req_txt = subprocess.run(['pip', 'install', '-r', 'requirements.txt'], cwd=python_directory,check=True) #install npm npm_i = subprocess.run(['npm', 'i'], cwd=nextjs_directory,check=True) # Check the exit code of npm_i before proceeding to npm_build if npm_i.returncode == 0: # Run build command if npm install was successful npm_build = subprocess.run(['npm', 'run', 'build'], cwd=nextjs_directory, check=True) else: print("Error: npm install failed.") here error { "error": "Command '['pip', 'install', '-r', 'requirements.txt']' returned non-zero exit status 1." } -
Passenger error #3 when installing django application in DirectAdmin host
When i was installed django app in DirectAdmin, i found error like this in when i go to my domain enter image description here, how to fix that? i've tried finding solution, but there is just solution to fixing to root file -
Pass variable through HttpResponse | Django
I have the following code working properly to download a file @ Django: def download_file(request): response = HttpResponse(Document2.file, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename="sigma.xlsx"' return response My goal: after the user has downloaded the file, in other words, the def download_file has been runned, I need to show the form in the template page. <h2><i class="fa fa-cog"></i></h2> <h1>Upload base de dados</h1> <p>Antes de realizar o upload da nova base de dados, realize, por medidas de segurança, <span class="detail-color">o download</span> do atual banco de dados.</p> <br> <a href="{% url 'auditoria_app:download_file' %}" class="" style="color: red">Clique aqui para baixar o arquivo atual.</a> **{% if variable = 'yes' %}** <form id="" action="{% url 'auditoria_app:upload' %}" method="POST" class="" enctype="multipart/form-data"> {% csrf_token %} <label for="test"> <section><i class="fas fa-cloud-upload-alt fa-3x"></i> Clique aqui ou arraste a base de dados para essa área!</section> {{ form.as_p }} </label> <p id="filename"></p> <button type="submit" class="button-section-1" onclick="disable()" value="Save"> Iniciar upload </button> </form> **{% endif %}** As a precautionary measure, I would like the user to download the file before uploading a new one. Hence the reason for rendering the page only after the download has been completed. How can I solve this? Tks!