Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting "Failed to create meeting error 401 Client Error: Unauthorized for url: https://api.zoom.us/v2/users/me/meetings"
I have added the client id and secrete key and if i am autharizing the app from postman its working but as soon as i tried to ping the api with my app it giving 401 error. how can i authorize my app into zoom app and can create meeting with dynamic token authrization_url = 'https://zoom.us/oauth/authorize' authrization_params = { 'client_id': zoom_client_key, 'response_type': 'code', 'redirect_uri': 'https://gensproject.supporthives.com/zoom', } auth_response = requests.post(authrization_url, data=authrization_params) if auth_response: # Obtain a new access token access_token_url = 'https://zoom.us/oauth/token' access_token_params = { 'grant_type': 'client_credentials', 'client_id': zoom_client_key, 'client_secret': zoom_client_secret, } try: response = requests.post(access_token_url, data=access_token_params) response.raise_for_status() access_token = response.json().get('access_token', '') except requests.RequestException as e: return Response({'message': 'Failed to obtain access token', 'error': str(e)}, status=500) # Create a Zoom meeting # user_id = "ops@supporthives.com" # create_meeting_url = f"https://api.zoom.us/v2/users/{user_id}/meetings" "https://zoom.us/oauth/authorize?client_id=MeGkVnUrQGG15c7ESPP1ZA&response_type=code&redirect_uri=https%3A%2F%2Fgensproject.supporthives.com%2Fzoom" create_meeting_url = 'https://api.zoom.us/v2/users/me/meetings' create_meeting_headers = { 'Authorization': f'Bearer {access_token}', # 'Authorization': f'Bearer eyJzdiI6IjAwMDAwMSIsImFsZyI6IkhTNTEyIiwidiI6IjIuMCIsImtpZCI6IjQ0NTYzNTg5LTA0YzAtNDY1ZC05NjBhLTljM2Y4YmI1ZjRmMyJ9.eyJ2ZXIiOjksImF1aWQiOiJiOTg4ZGQ4ZGNiYmQ0NTcyMjM0OWU4ZWE1ZGQ5NTVkMCIsImNvZGUiOiJ6V0tvUWhBREtuQWRHdVVuRkt5Uk15WXF2TjBYaXpDa0EiLCJpc3MiOiJ6bTpjaWQ6TWVHa1ZuVXJRR0cxNWM3RVNQUDFaQSIsImdubyI6MCwidHlwZSI6MCwidGlkIjowLCJhdWQiOiJodHRwczovL29hdXRoLnpvb20udXMiLCJ1aWQiOiI3RkRIdW16TFNMZW5xUVk0cDRFNDRnIiwibmJmIjoxNzExNDUyMTk0LCJleHAiOjE3MTE0NTU3OTQsImlhdCI6MTcxMTQ1MjE5NCwiYWlkIjoiMVpmNnBDYkRROHF2emU1RFB0VnQ0USJ9.2oTMkSwL0OrnOAswTJoscy8zOSJhVmplTHsE6gh3H5-z_7sznAanBF2XyL3wO9FLGpggsFSqWxB04MXQof7YDw', 'Content-Type': 'application/json', } event_datetime = datetime.combine(event.event_date, datetime.min.time()) start_time_utc = mktime(event_datetime.utctimetuple()) create_meeting_params = { 'topic': event.event_title, 'type': 2, # Scheduled meeting 'start_time': f'{start_time_utc}000', 'duration': 60, 'timezone': 'UTC', 'description': event.event_description, 'settings': { 'host_video': True, 'participant_video': True, 'waiting_room': False, 'join_before_host': True, 'mute_upon_entry': False, 'auto_recording': 'none', }, } try: create_meeting_response = requests.post(create_meeting_url, headers=create_meeting_headers, json=create_meeting_params) create_meeting_response.raise_for_status() meeting_link = create_meeting_response.json().get('join_url', '') event.event_link = meeting_link … -
My image show not found error but the link in terminal is able to locate the file
My image can't be load on page, the feedback shows Not Found: /auctions/static/auctions/images/Artboard_1_copy.png "GET /auctions/static/auctions/images/Artboard_1_copy.png HTTP/1.1" 404 3417 but when I ctrl and click on the link in feedback, I was able to open my image in my workspace. This is my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'auctions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'commerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'commerce.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_USER_MODEL = 'auctions.User' # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # … -
Python: how to handle uploading and zipping large files into Minio
I have a Django GraphQL API. I'm trying to implement an endpoint that would download files from external urls, upload them to Minio bucket, create a Zip-file from the files and return the Zip-file to the user for download. All this is done in the backend. It works with relative small files but the problem is that some of the files I need to handle are pretty large, e.g. ~4GB and uploading files this big seems to fail pretty often and adding them to Zip-file usually freezes the whole server. This is how I download and upload the files: def download_and_upload_file(url: str, prefix: str, file_name: str) -> str: with requests.get(url, stream=True) as response: response.raise_for_status() with io.BytesIO() as file_buffer: for chunk in response.iter_content(chunk_size=8192): if chunk: file_buffer.write(chunk) file_buffer.seek(0) upload_url = upload_object_to_minio(file_buffer, prefix, file_name) return upload_url def upload_object_to_minio(stream: io.BytesIO, prefix: str, object_name: str): try: _ = MINIO_CLIENT.put_object( bucket_name=xxx, object_name=f"/{prefix}/{object_name}", data=stream, length=stream.getbuffer().nbytes, ) except Exception as e: print(e) return "minio-object-url" And this is how I zip the file: def create_zip_file(prefix: str, uploaded_urls: list[str]) -> str: try: zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w") as zip_file: for uploaded_url in uploaded_urls: file_name = uploaded_url.split("/")[-1] # Retrieve the Minio object and its name minio_object, object_name = get_object_from_minio(uploaded_url) # … -
While using django-template the code is not automatically generated and even while pressing the enter key the code is not coming in the new line
{% extends "base.html" %} {% block title %}Home{% endblock title %} this is the sample code {% extends "base.html" %} {% block title %}About{% endblock title %} i want each line in the new next line even code suggestion is not shown -
Forbidden (CSRF cookie not set.): for django login from javascript
I am trying to access django server login from javascript axios.get('http://localhost:8010/get_csrf_token/').then((res)=>{ console.log(res.data['csrf_token']); var data = {username:'admin@test.com',password:'testtest', } axios.defaults.headers.common['X-CSRF-TOKEN'] = res.data['csrf_token'];// set csrf_token in header. axios.post('http://localhost:8010/login/',data).then(() =>{ console.log("test"); }) }) However this code shows the error below. I set the X-CSRF-TOKEN header but it requires cookie? This django server is not third-party but under my controle, so I can change the setting of djang server. How can I solve this? Forbidden (CSRF cookie not set.): /login/ [WARNING][240326 200329] Forbidden (CSRF cookie not set.): /login/ [26/Mar/2024 20:03:29] "POST /login/ HTTP/1.1" 403 2882 -
Celery worker shut down
My worker in celery automatically gets shut down and logs this message worker: Warm shutdown (MainProcess), and doesn't do anything, I'm running a long running AI/ML tasks in celery my celery config is something like this: **app.conf.update( result_expires=None, # Disable result expiration worker_max_tasks_per_child=500, # Disable limiting the number of tasks each worker can execute before it's replaced worker_prefetch_multiplier=0, # Disable prefetching tasks worker_concurrency=1, # Use all available CPU cores for concurrency worker_disable_rate_limits=True, # Disable rate limits for tasks task_track_started=True, # Track started tasks task_soft_time_limit=None, # Disable soft time limit for tasks task_time_limit=None, # Disable hard time limit for tasks worker_max_memory_per_child=None, # Disable memory limit for worker processes task_acks_late=True, broker_connection_retry_on_startup=True, # Enable broker connection retries on startup )** sometimes it shuts down and sometimes it does'nt can anyone say something -
Django admin page doesn't open, when I use Kong gateway
I use Kong gateway to make Django project accessible at localhost/python. I can see Django start page, but when I try to open localhost/python/admin it redirects to localhost/admin/login/?next=/admin/, so that isn't Django project anymore. What can I do to fix that? Thanks This is how Kong service and route looks like: { "enabled": true, "tls_verify": null, "tls_verify_depth": null, "port": 3000, "protocol": "http", "path": null, "client_certificate": null, "write_timeout": 60000, "connect_timeout": 60000, "retries": 5, "read_timeout": 60000, "id": "8da72803-ffea-4424-a568-31faa3782a6d", "name": "python-service", "host": "python-service", "updated_at": 1711390446, "created_at": 1711390446, "tags": null, "ca_certificates": null } route: { "next": null, "data": [ { "strip_path": true, "regex_priority": 0, "methods": null, "request_buffering": true, "response_buffering": true, "protocols": [ "http", "https" ], "service": { "id": "8da72803-ffea-4424-a568-31faa3782a6d" }, "https_redirect_status_code": 426, "tags": null, "paths": [ "/python" ], "headers": null, "id": "2c1fb24a-21dd-42f5-9784-a3bf95c6f7dc", "path_handling": "v0", "created_at": 1711390464, "updated_at": 1711390464, "name": null, "snis": null, "sources": null, "hosts": null, "preserve_host": false, "destinations": null } ] } -
Django signals debounce
In a project using Django's signal, when a series of UPDATEs of a particular model are executed, the processing of one SIGNAL is too heavy and causes discomfort to the user. The process fired by SIGNAL does not need to be executed for each update when multiple UPDATEs are executed. For example, if UPDATE of model A is executed 20 times in one minute, there is no need to fire signal 20 times. In light of the above, I think it would be better to implement something like debounce, where signal is fired only once even if multiple UPDATEs are executed in one minute. (We have already taken steps to reduce the number of signal firing conditions.) Is it possible to run a debounce-like process in Django? Or is there a library that can accomplish this? Thanks in advance. signal.py @receiver(post_save, sender=ModelA) def heavy_function1( sender: ModelA, instance: ModelA, *args, **kwargs ) -> None: result = calculate1(instance.attribute) update_modelB(result) @receiver(post_save, sender=ModelA) def heavy_function2( sender: ModelA, instance: ModelA, *args, **kwargs ) -> None: result = calculate2(instance.attribute) update_modelB(result) @receiver(post_save, sender=ModelA) def heavy_function3( sender: ModelA, instance: ModelA, *args, **kwargs ) -> None: result = calculate3(instance.attribute) update_modelB(result) We already use django-model-util's FilldTracker to perform heavy processing … -
how connect to models.py? Some Django views.py are not working
i am new with django/python. i have project in Django for calculate paper price. class Calculate(View): def get(self, request): if not request.user.is_authenticated: return redirect('signIn') user = request.user projects = Project.objects.all() p_info_list = [] u_info = UserInfo(user) user_in_projects = [] k_info_list = [] for p in projects: tasks = p.task_set.all() print(f"Project: {p.name}, Tasks: {tasks}") print(f"p object: {p}") for task in tasks: print(f"Task object: {task_object}") # Check the value before object creation if p.owner == user or user.id in p.get_members(): p_info = ProjectInfo(p) u_info.analyze_project(p) p_info_list.append(p_info) user_in_projects.append(UserInProject(user, p)) print(f"P Info object: {p_info}") for task in p.task_set.all(): print(f"Task object: {task}") # Print the entire task object print(f"Task: {task.name}, tipe_kertas: {task.tipe_kertas}") k_info_obj = KalkulatorInfo(task) # Or pass relevant data containing paper properties print(f"KalkulatorInfo object: {k_info_obj}") price = k_info_obj.calculate_price(task.tipe_kertas, task.gramatur_kertas, task.ukuran_kertas) k_info_obj.price = price # Assuming KalkulatorInfo has a price attribute k_info_list.append(k_info_obj) why task_object not working when i debugging from print() the entire for task in p.task_set.all() are not working. here is the models.py: class KalkulatorInfo: def __init__(self, task_object): self.tipe_kertas = task_object.tipe_kertas # Assuming task object has these attributes self.gramatur_kertas = task_object.gramatur_kertas self.ukuran_kertas = task_object.ukuran_kertas self.price = self.calculate_price() # Calculate price upon initialization def calculate_price(self): price_dict = { ("ap", "80", "a4"): 10000, ("bp", "100", "a4"): 12000, … -
Request in test APIClient fails after authenticating twice
After upgrading to django 5, our test suite started showing odd behavior. We are using DRF's APIClient and authentication does not work as expected anymore. Certain API requests return rest_framework.exceptions.NotAuthenticated with status code 403 (by the way, if someone could explain why this status is 403 and not 401, I'd appreciate). This is seemingly arbitrary. Among 2 requests to views which are implemented identically in terms of user permissions etc, one returns 403 during testing only. Executing the same calls in Postman does not reproduce the error. Thus, some of the exact same test cases which used to pass under django 4 do not pass anymore under django 5 due to above error. I did not manage to reproduce these cases in a minimal example. What I did reproduce however, is the following: client.force_authenticate(user) client.get(url) # the user does not have permissions. response is 403, as expected client.force_authenticate(None) # "log out" user.user_permissions.add(permission) client.force_authenticate(user) response = client.get(url) # the now has permissions. response 200 is expected assert response.status_code == 200 # response status is 403 Package versions are django==5.0.3 djangorestframework==3.15.0 pytest==7.4.3 pytest-django==4.7.0 I have made a minimal project where this can be observed. As far as I managed to test it, … -
Uncaught TypeError: $.ajax is not a function in jQuery
I'm encountering an issue with jQuery's $.ajax function in my web application. When I try to make an AJAX request using $.ajax, I'm getting the error "Uncaught TypeError: $.ajax is not a function" in the browser console. Here's the relevant code snippet: $.ajax({ url: "/add-to-wishlist", data: {"id": product_id}, dataType: "json", beforeSend: function(){ console.log("Adding to wishlist"); }, success: function(response){ this_val.html("👍🏼"); if (response.bool === true) { console.log("Added to wishlist"); } }, error: function(xhr, errmsg, err){ console.log(xhr.status + ": " + xhr.responseText); console.log(errmsg); } }); I've ensured that jQuery is properly included in my HTML file before including my JavaScript file. However, I'm still encountering this error. Could anyone help me understand why I'm getting this error and how to resolve it? Any insights or suggestions would be greatly appreciated. Thank you! I'm facing a problem with adding products to the wishlist feature in my Django web application. Here's the relevant: View (add_to_wishlist): def add_to_wishlist(request): product_id = request.GET['id'] product = Product.objects.get(id=product_id) context = {} wishlist_count = wishlist.objects.filter(product=product, user=request.user).count() print(wishlist_count) if wishlist_count > 0: context = { "bool": True } else: new_wishlist = wishlist.objects.create( product=product, user=request.user ) context = { "bool": True } return JsonResponse(context) HTML Button: <button class="btn-action" data-product-item="{{ p.id }}"> <ion-icon name="heart-outline"></ion-icon> … -
How to optimize and implement infinite comments through prefetch with django orm?
I'm implementing the comment function and I can leave a big message in the comments. It was easy to implement the function, but it's causing n+1 queries. Please tell me how to solve this problem python Prefetch( 'comments', queryset=PlaceReviewComment.objects.select_related( 'user', ).prefetch_related( Prefetch( '_comments', queryset=PlaceReviewComment.objects.select_related( 'user', 'parent_comment', ).prefetch_related( '_comments', '_comments__user', ).filter( removed_at__isnull=True ), to_attr='child_comments' ), ).filter(parent_comment=None, removed_at__isnull=True), to_attr='_comments' ), ).filter( id=review_id, If I do this, I'll only get one depth's comment Should I implement a function that does prefetch as much as depth? But I also think to check that there is a _comment and add prefetch, but I don't know how -
No data posted to Django rest api when button is pressed
I have a form with text inputs, and I have created a button as well which when pressed, should post the input field data into a Django Api. But when I press the button, nothing happens and there seems to be no error as well. This is sample from my code: class MyForm extends StatefulWidget { @override _MyFormState createState() => _MyFormState(); } class _MyFormState extends State<MyForm> { final String url = 'http://127.0.0.1:8000/api/?format=json'; final TextEditingController nameController = TextEditingController(); final TextEditingController phoneController = TextEditingController(); final TextEditingController purposeController = TextEditingController(); final TextEditingController addressController = TextEditingController(); final TextEditingController visiteeController = TextEditingController(); final TextEditingController dateController = TextEditingController(); String result = ''; Future<void> _postDataToDjango() async { try { final response = await http.post(Uri.parse(url), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, dynamic> { 'visitor_name': nameController.text, 'visit_date': dateController.text, 'Time_in': (TimeInputField()._selectedTime).toString(), 'Time_out': Null, 'Department': (DropdownMenuExample().dropdownValue).toString(), 'Visitee_name': visiteeController.text, 'Address': addressController.text, 'Phone': phoneController.text, 'Purpose_of_visit': purposeController.text }), ); if (response.statusCode == 201) { final responseData = jsonDecode(response.body); print('Post successful'); setState(() { result = 'id: ${responseData['id']}\nvisitor_name: ${responseData['visitor_name']}\nvisit_date: ${responseData['visit_date']}\nTime_in: ${responseData['Time_in']}\nTime_out: ${responseData['Time_out']}\nDepartment: ${responseData['Department']}\Visitee_name: ${responseData['Visitee_name']}\nAddress: ${responseData['Address']}\nPhone: ${responseData['Phone']}\nPurpose_of_visit: ${responseData['Purpose_of_visit']}'; }); } else { throw Exception('Failed to submit'); } } catch (e) { setState(() { result = 'Error: $e'; }); } } And below is the … -
ImportError for django-simple-history in VS Code: "Import 'simple_history.models' could not be resolvedPylance"
I'm currently working on a Django project and want to use django-simple-history to track changes on my models. However, I'm facing an issue with importing the HistoricalRecord model from simple_history.models. Whenever I try to import it in my code, Visual Studio Code underlines the import statement and shows the error message "Import 'simple_history.models' could not be resolvedPylance". Here are the steps I've taken to troubleshoot the issue: I activated my virtual environment where django-simple-history is installed and then using pip freeze, I confirmed that django-simple-history==3.5.0 is listed. I also used pip show django-simple-history to ensure the package details are correct, and it shows the expected information. I deleted the virtual environment and recreated it, but the problem persists. I checked the location where the virtual environment saves the library-specific data (venv\Lib\site-packages\simple_history), and I can see the HistoricalRecords model there. Despite these efforts, I'm still unable to resolve the import error in VS Code. Could anyone suggest what might be causing this issue and how I can fix it? Any help or guidance would be greatly appreciated. Here is the error: (https://i.stack.imgur.com/mzpZQ.png) Thank you! -
Unable to Resolve jQuery ReferenceError: $ is not defined in JavaScript File
I'm encountering an issue with my JavaScript file where I'm getting the error "Uncaught ReferenceError: $ is not defined" in the browser console. I'm using jQuery in my JavaScript code, but it seems like jQuery is not being recognized. Here's the relevant portion of my JavaScript file (address.js): console.log("Hi"); $(document).ready(function(){ $(document).on("click",".make-default-address",function(){ let id = $(this).attr("data-address-id") let this_val = $(this) console.log("Id is:", id); console.log("Element is:", this_val); $.ajax({ url:"/make-default-address", data: { "id":id }, dataType: "json", success: function(response){ console.log("Address Made default....."); if (response.boolean == True){ $(".check").hide() $(".action_btn").show() $(".check"+id).show() $(".button"+id).hide() } } }) }) }) I've ensured that jQuery is loaded before this script in my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="{% static 'assets/js/address.js' %}"></script> However, I'm still getting the error. Can someone please help me understand what might be causing this issue and how I can resolve it? Any assistance would be greatly appreciated. Thank you! -
Django Channels direct messaging and server sent events
Hello I am building a multiplayer poker game. So far I have built the poker portion where instances of players are created and a table is created then hands are stored in the player object and the board and pot and betting takes place in the table instance. I’d like to create a multiplayer version where instead of taking inputs from the command line, a chat room like interface will take in betting and display hands and the board. Functionality I need: output hand to one specific websocket input bet from one specific websocket and then output that bet to the next websocket and receive a bet and output to the next and so on output pot size and board and player balance to specific websocket So far I have used the channels tutorial to build a basic chat app. The issue I’m facing is that most of the tutorials and content are tailored toward broadcasting messages to everyone. Please help! -
calendar keeps showing the wrong time
I am trying to fix the timezones for the calendar. It sends to the django server the times as an ISO format with the offsets as the timezone that the user selects at the dropdown menu and saves it. It is saved in the server correctly. But upon loading it into the calendar, it seems to interpret it as actually 5 hours ahead (America/Chicago CST time) instead of the time format as 00:00:00 that was input originally. And yes the offset is -5. I've already tried removing the timeZone option in the fullcalendar variable and that didn't do anything. #calendar.html var calendar = $("#calendar").fullCalendar({ // timeZone: $("#id_timezone").val(), timeZone: "UTC", #UTC is just for testing purposes header: { left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay", }, events: "/all_events", selectable: true, selectHelper: true, editable: true, eventLimit: true, eventDurationEditable: true, select: function (start, end, allDay) { var title = prompt("Enter Event Title"); if (title) { var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss"); var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss"); $.ajax({ type: "GET", url: "/add_event", data: { title: title, start: start, end: end, timezone: $("#id_timezone").val(), }, dataType: "json", success: function (data) { calendar.fullCalendar("refetchEvents"); alert("Added Successfully " + start); }, error: function (data) { alert( "There is … -
Django field isn't being migrated
I have a model, for each object I want a random string on creation activation. I'm currently creating the model like so; from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ import string import random def get_random_12_string(): return ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=12)) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer') organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='clients') phone_number = models.CharField(_("Phone Number"), max_length=15) date_of_birth = models.DateField(_("Date of Birth"), blank=True, null=True) # Optional created_at = models.DateTimeField(_("Created At"), auto_now_add=True) updated_at = models.DateTimeField(_("Updated At"), auto_now=True) activation = models.CharField(_("Activation Code"), max_length=14, default=get_random_12_string) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Meta: verbose_name = _("Customer") verbose_name_plural = _("Customers") ordering = ['created_at'] # Orders by creation date by default in queries. However after running python manage.py makemigrations & python manage.py migrate (both saying they are succesful). The field doesn't even get created in the database and when going to the admin panel I am getting an error that the field doesn't exist. Migrations for 'portal': portal\migrations\0005_alter_client_activation.py - Alter field activation on client Operations to perform: Apply all migrations: admin, api, auth, contenttypes, cookie_consent, portal, public, sessions, sites Running migrations: Applying portal.0005_alter_client_activation... OK -
ModuleNotFoundError: No module named 'django_DRF'
I just running the django project for welcome, it come out the issue with No module named 'django_DRF'. python==3.8 django==4.2 I have installed the djangorestframework and add rest_framework in INSTALLED_APPS, but i still have the same issue. Thank you for help!! -
Page 404 when Django project WSGIScriptAlias is not /
I am learning Django. I am on Python 3.12.2, Django 5.0.3, Apache HTTPD 2.4.58, Windows 11. I have just done startproject (no startapp yet). Here is my current directory structure: D:\dev\htdocs # Apache HTTPD DocumentRoot ├───... # Other directories │ └───nutrihub_pyvenv # venv container for Django project ├───.venv # I use pipenv │ └───nutrihub │ db.sqlite3 │ manage.py │ Pipfile │ Pipfile.lock │ └───nutrihub asgi.py settings.py urls.py wsgi.py __init__.py Here is my Apache config: WSGIScriptAlias /nhub "d:/dev/htdocs/nutrihub_pyvenv/nutrihub/nutrihub/wsgi.py" WSGIPythonHome "d:/dev/htdocs/nutrihub_pyvenv/.venv" WSGIPythonPath "d:/dev/htdocs/nutrihub_pyvenv/nutrihub;" WSGIApplicationGroup %{GLOBAL} <Directory "d:/dev/htdocs/nutrihub_pyvenv/nutrihub/"> <Files "wsgi.py"> Require all granted </Files> </Directory> I added the following to D\dev\htdocs\nutrihub_pyvenv\nutrihub\nutrihub\settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] When I run the following command: D:\dev\htdocs\nutrihub_pyvenv\nutrihub (.venv) λ py manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 26, 2024 - 06:56:13 Django version 5.0.3, using settings 'nutrihub.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ... I see the page with The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in … -
Django console giving not found error for api even though its visible in browser
I have a django backend setup. In that I have a few folders, base (app that holds my models), a folder named "api" that has a views.py and urls.py for my apis, and a folder called backend (djangos base folder where settings.py, wsgi.py, etc are). Now, I already have a few APIs in my views.py (in api folder) that are linked and working, and I just tried to create a new one. Although I did the same steps, followed he same linkage, this API is not working when accessed from my frontend, the console says: "Not Found: /api/getmodel/ [25/Mar/2024 22:36:50] "GET /api/getmodel/ HTTP/1.1" 404 3116" When I go to "http://127.0.0.1:8000/api/getmodel/" I'm seeing the default djangorestframework view so I know that the view exists and there is infact something on that link. Here are the relevant files: urls.py (in api folder): from django.urls import path from . import views from rest_framework_simplejwt.views import ( TokenRefreshView, ) from .views import MyTokenObtainPairView urlpatterns = [ path('registeruser/', views.register_user), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('createmodel/', views.create_model), path('getmodel/', views.fetch_model), ] views.py (in api folder): from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from django.contrib.auth.hashers import make_password from base.models import User, HumanModel … -
Make Saleor multitenant
I'm currently working on an E commerce platform like shopify. I found tons of good reviews about saleor open source project , and went for it to speed up the development. The plan i'm going with is to add Multitenancy to SaleOr with Django Tenants package. But I'm pretty new to SaleOr and can't find any proper tutorial about what i'm trying to do. Does anyone here mind helping please ? Reading and following the docs didn't help. Any guidance is appreciated I tried following the docs for installation but it's quite confusing for me. A beginner comprehensive step by step guide or tutorial would be wonderful*. Any form of kind assistance too. -
Connecting Django container to MySQL container in a single AWS ECS Fargate task definition
I have a repository here. I am currently struggling with deploying it to AWS ECS. The repository is configured to use Github Actions to build the two containers and then ship them to ECR, then update an ECS task definition to pull the most recent image commit. Both containers startup, but then they fail. The Django container gives an error saying django.db.utils.OperationalError: (2005, "Unknown server host 'template-db' (-2)") From what I understand, the name of the DB_HOST in the settings.py should be the name of the container when they are in the same task definition. Why does it not work then? Is there some fundamental networking concept here I don't understand? I am using ECS Fargate, and am therefore on awsvpc for the network mode. I also tried changing the hostname to localhost, as that worked in the podman-compose setup on local, which didn't work. I'm not surprised, since these are separate containers in a serverless environment. What I've tried should be visible at the repository here: -
[[Errno 2]] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in Django
I've been moving development of my website over to using Docker. I recently adjusted the location of media files when I was presented with this error: [Errno 2] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in Django. So far I've checked for typos in my file location code in my settings, views and models. The website works by simply storing user uploaded media files in a media folder. Uploaded files are stored in media/human. Here is the relevant code: views.py: ... fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file_type = mimetypes.guess_type(uploaded_file_path) request.session['uploaded_file_path'] = uploaded_file_path user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) files = request.FILES.getlist('file') for file in files: user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) uploaded_file = UploadedFile(input_file=file, requirements_chat=user_doc, chat_id = user_id) uploaded_file.save() user_doc.save() ... The error seems to be caused by the uploaded_file.save() line. models.py: class RequirementsChat(models.Model): id = models.CharField(primary_key=True, max_length=40) alias = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) language = models.CharField(max_length=10, blank=True, null=True) due_date = models.CharField(max_length=10, blank=True, null=True) subtitle_type = models.CharField(max_length=10, blank=True, null=True) transcript_file_type = models.CharField(max_length=10, blank=True, null=True) additional_requirements = models.TextField(max_length=500, blank=True, null=True) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) url = models.CharField(max_length=250, blank=True, null=True) task_completed = models.BooleanField(default=False) class UploadedFile(models.Model): input_file = models.FileField(upload_to='human_upload/')#new chat_id = models.CharField(max_length=40, null= True) requirements_chat = models.ForeignKey(RequirementsChat, on_delete=models.CASCADE, … -
Django Getting a List of Items from one Model and using it to filter another
So, I have 3 tables in my model, house, room, and item. room contains a foreign key to house, and item contains a foreign key to room. I want to be able to query by the house and get all the items in the house. class room(models.Model): house= models.ForeignKey(house, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=60, null=False) def __str__(self): return self.name class house (models.Model): name = models.CharField(max_length=50, unique=True, null=False) #House name, unique houseCode = models.CharField(max_length=5, null=False) # house code class item(models.Model): room= models.ForeignKey(room, on_delete=models.CASCADE, null=False) # ForeignKey to room itemName = models.CharField(max_length=255, null=False) # item So I want to be able to pass in a house ID and get all the associated items in the house, grouped by rooms, so the desired return would be something like. { room:living room, items:[couch, tv] room: bedroom, items:[bed, nightstand] } Not sure what I need in the new serializer/view to be able to do this as all my current serializers/views are just the model and all fields for basic CRUD operations.