Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku H13 desc="Connection closed without response" for file (pdf) upload
I have a use case where the user can upload a pdf book and I process a summary for that book. For a 250-page book, for example, the summary process takes around 2-3 minutes and it works great on local. However, in Heroku, for that 250-page book, I get the error below. When I try the 20-page book, it's okay. I run Heroku using professional dynos. I have 3 dynos. I have also shared my views on how files are processed. There you will see libraries that I use as well. I read a bit that Heroku has a hard cap of 30 seconds, ie if 30 seconds passed and the summary is not done, boom, error. Is that true? How can I avoid that? Thank you in advance for your help. error: error in server: 2023-08-15T09:12:55.850512+00:00 app[web.1]: [2023-08-15 09:12:55 +0000] [98] [INFO] Worker exiting (pid: 98) 2023-08-15T09:12:55.848850+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/file_processing/upload/" host=someendpoint request_id=b8045e24-a33f-4446-869e-e22a27fbef32 fwd="109.245.202.232,141.101.96.16" dyno=web.1 connect=0ms service=30471ms status=503 bytes=0 protocol=https Procfile web: gunicorn backend.wsgi views.py from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from .serializers import DocumentSerializer from docx import Document as DocxDocument from pdfminer.high_level import extract_text import pytesseract … -
Trying to send HTML form field value in JSON POST call to API but getting syntax err showing that whole HTML page code is being sent as JSON
I am building a Single Page App using Django and JavaScript. In Django app in the views.py I have the following function acting as add-post API endpoint: def post_add(request): ''' API endpoint for creating a new post ''' # save data submitted by the user if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) else: form = PostForm(request.POST) # check if form is valid server-side if form.is_valid(): post = form.save(commit=False) # save without commit as we have to associate some variables that were not in the form post.author = request.user post.save() return JsonResponse({"message": "Post added successfully."}, status=201) else: # return JsonResponse({"message": "Errors in the form."}, status=400) In JavaScript I have added event listener after the whole document has been loaded and within it an event listener on the submit button that removes the default submit action and triggers my add_post() function: document.addEventListener('DOMContentLoaded', function() { // add function call on add post form submission document.querySelector("#create-post").addEventListener('submit', function(event) { event.preventDefault(); // cancels default form submission action on clicking the submit button in the form add_post(); }); }); And here is the add_post() function in JavaScript that sends data for the new post (1 field in the form) and calls the API endpoint: … -
How can I see the body of the request that Django's test client makes
I am writing automated tests in Django and started writing tests for an API endpoint that supports the put method. I am making my put request like so: response = self.client.put(path, data=json.dumps({"key": "value"}) print(response.request) As you see, I'm trying to see the details of the request that is being sent. I am particularly interested in seeing what goes into the body of the request. But the object returned by response.request is a dictionary that does not contain the "body" key or anything similar. I think this is a weird feature for the testing framework not to have, seeing as how it could come in handy in many different scenarios. Is there any way I can access the body of the request that I have not yet discovered? Or does the feature really not exist? -
Performance issues with gunicorn + gevent Django
I'm encountering performance issues with gunicorn+genevent that is consuming a significant amount of RAM after conducting a high-load test. Even when I return an empty view with just a "hello world" message, the RAM usage continues to remain high, causing other requests to get stuck. I suspect that there might be a cache-related issue causing this behavior. Is there a way for gunicorn to clean up its cache automatically to return resources to normal levels after a high-load situation? I've configured gunicorn to use the formula NUM_WORKERS = NUM_CORES * 2 and performed tests with both 1 worker and more workers, but the results were the same. Here's the command I'm using to run gunicorn: gunicorn config.wsgi:application \ --workers $NUM_WORKERS \ --timeout $TIMEOUT \ --keep-alive 2 \ --bind 0.0.0.0:8000 \ --log-level=debug \ --log-file=- \ -k gevent Could this issue possibly be unrelated to gunicorn? If so, how can I go about testing for memory leaks? Your assistance is greatly appreciated. -
Why are emails sent successfully from my Django project using the Gmail SMTP server on localhost but not on AWS?
I use the Gmail SMTP server for my Django project, which I have deployed on AWS. The emails are sent and work locally on localhost, but they are not working from AWS. I have 2 step verification enabled on gmail and generated app password wich i use in two different .env files, one locally and one in the cloud. I use the same password (if that matters). Additionally, I have added port 587 to the inbound rules of the Security Groups but still not working. enter image description here -
dj-rest-auth TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I'm using dj_rest_auth for authentication and when I click on the verify email link, this error comes out How do I fix this error? -
Dockerise django app for production, failed to solve: process "/bin/sh -c pip install
I try to dockerise a django container for production. So I have my dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app COPY ./Welzijn /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] and the docker-compose file: version: "3.9" services: app: build: context: . ports: - "8000:8000" volumes: - ./Welzijn:/app command: > sh -c "python ./manage.py migrate && python ./manage.py runserver 0:8000" environment: - DEBUG=1 env_file: - ./.env and requirements.txt file: Django>=4.0.4 uWSGI>=2.0.18,<2.1 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-dotenv But when I execute docker-compose up --build I get this errors: If you prefer to avoid building psycopg2 from source, please install the PyPI 3.686 'psycopg2-binary' package instead. 3.686 3.686 For further information please check the 'doc/src/install.rst' file (also at 3.686 <https://www.psycopg.org/docs/install.html>). 3.686 3.686 [end of output] 3.686 3.686 note: This error originates from a subprocess, and is likely not a problem with pip. 3.690 error: metadata-generation-failed 3.690 3.690 × Encountered error … -
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_profile.user_id
I'm having issues with registering a user in my project. I have a custom serializer that inherits from the RegisterView of dj_rest_auth. My code is: views.py class ProfileDetail(APIView): def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 def get(self, request, pk, format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data) class CustomRegisterView(RegisterView): serializer_class = CustomRegisterSerializer serializer.py class CustomRegisterSerializer(RegisterSerializer): user_type = serializers.ChoiceField(choices=[('seeker', 'Seeker'), ('recruiter', 'Recruiter')]) class Meta: model = User fields = "__all__" def get_cleaned_data(self): data = super().get_cleaned_data() data['user_type'] = self.validated_data.get('user_type', '') return data def save(self, request): user = super().save(request) user_type = self.validated_data.get('user_type') Profile.objects.create(user=user, user_type=user_type) return user models.py class Profile(models.Model): class Type(models.TextChoices): seeker = "Seeker" recruiter = "Recruiter" base_type = Type.seeker user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(choices=Type.choices, default=base_type, max_length=20) I expect the code to return a 200 after I perform a POST request. -
Protection from cross-site-scripting Django Rest Framework
I am creating API for forum web-site with DRF and want to protect it from XSS. For example if someone sends a request with a text included in html tags(button, form, script etc.) it is saved in database. I wan't to protect it somehow. I heard that I can do it through serailizer escape method or I can solve the problem on the middleware level by checking if there are any prohibited tags and if so, raise an error or just parse the row text from html and save it. Also in some ednpoints I do really need to save data (including html) in the TextField , as I want my frontend client to be allowed to format text with HTML (basic markup), but in these case the idea of special middleware does not seem appropriate because it won't allow to send request with HTML text. Or I just should create a middleware to check if there are for example form or button tags and in this way raise error (if it is something like HTML lists, headlines, span tags don't raise error). What solution works better? Or are there any other ways? Maybe it is up to frontend developer … -
Use threading.Event() to send SSE event in Django project after receiving message from RabbitMQ
I have a Django map application that displays real-time markers with either red or green color based on the marker's state, which is updated when a new message arrives. Currently, I'm periodically updating the page every 3 seconds, but I want to achieve a more efficient approach by updating the page only after a change in the database. I have this sse function in my views.py: from threading import Event marker_update_event = Event() marker_update_event_list = {0: marker_update_event} #print("Marker update event created", marker_update_event_list[0]) def sse(request): def event_stream(): while True: marker_data = [] all_markers = Marker.objects.all() for marker in all_markers: latest_message = marker.get_latest_message() marker_data.append({ 'name': marker.get_name(), 'latitude': marker.get_latitude(), 'longitude': marker.get_longitude(), 'error_type': latest_message.get_error_type() if latest_message else 'No error type', 'message': latest_message.get_message() if latest_message else 'No messages', 'state': marker.get_state(), 'id': marker.id, }) if marker_update_event_list[0].is_set(): print('marker_update_event is set') yield 'event: marker_data\ndata: %s\n\n' % json.dumps(marker_data) marker_update_event_list[0].clear() marker_update_event_list[0].wait() return StreamingHttpResponse(event_stream(), content_type="text/event-stream") I'm also consuming messages from RabbitMQ using a consumer.py script at the root directory: import json import pika import django # Django environment setup from markers.models import Message from markers.views import marker_update_event_list connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='messages') def callback(ch, method, properties, body): data = json.loads(body) if properties.content_type == 'message_created': message = Message.objects.create(error_type=data['error_type'], message=data['message'], date=data['date'], … -
When load the data error rise Object of type Item is not JSON serializable
Model.py class Item(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) code = models.CharField(max_length=100, null=True, blank=True, unique=True) name = models.CharField(max_length=100) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name class PriceMaster(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) items = models.ForeignKey(Item, on_delete=models.CASCADE) gst = models.ForeignKey(Gst, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return str(self.items) @property def cgst_unround(self): if not hasattr(self,'_cgst'): self._cgst = self.price * self.gst.gst / 100 return round(self._cgst,2) @property def per_gst(self): self.per = self.gst.gst / 2 return self.per @property def cgst(self): return round((self.cgst_unround / 2),2) class TempCalculate(models.Model): quantity = models.IntegerField() items_price = models.ForeignKey(PriceMaster,on_delete=models.CASCADE) create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) @property def item_price(self): self.price = self.items_price.price return self.price ** I'm trying to access item name ** @property def item_name(self): self.name = self.items_price.items return self.name Serializer.py I'm trying access item_name field class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' class TempCalSerializer(serializers.ModelSerializer): class Meta: model = TempCalculate fields = ['id','item_name','quantity','item_price'] api/view.py @api_view(['GET']) def TempItem(request): queryset = TempCalculate.objects.all() serializer_class = TempCalSerializer(queryset, many=True) return Response(serializer_class.data) I'm trying access the item name but can't because when … -
disable default Django models and migrations
I created a Django project which is supposed to be a small service and it has nothing to do with User and other Django default models. How can I remove them completely? (I need Django admin) When I comment django.contrib.auth in INSTALEDD_APPS I recieve this error: RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. -
cannot import name 'UserSerializer' from 'serializers'
I want to wright api whith django.I installed serializers : pip install serializers and I import UserSerializer in view.py: from serializers import UserSerializer from rest_framework import serializers but When I want to use serializer , I give an error: cannot import name 'UserSerializer' from 'serializers' -
Extra field in custom registration in DRF won't save
I created a custom serializer that extends dj_rest_auth's RegisterSerializer, added the extra user_type field, overrode the get_cleaned_data method to include the user_type in the cleaned data then configured the custom registration serializer used for registration. Here's my code: class CustomRegisterSerializer(RegisterSerializer): user_type = serializers.ChoiceField(choices=[('seeker', 'Seeker'), ('recruiter', 'Recruiter')]) class Meta: model = User fields = "__all__" def get_cleaned_data(self): data = super().get_cleaned_data() data['user_type'] = self.validated_data.get('user_type', '') return data class Profile(models.Model): class Type(models.TextChoices): seeker = "Seeker" recruiter = "Recruiter" base_type = Type.seeker user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(choices=Type.choices, default=base_type, max_length=20) class Meta: verbose_name = "Profile" verbose_name_plural = "Profiles" def __str__(self): return self.user.username class CustomRegisterView(RegisterView): serializer_class = CustomRegisterSerializer -
Pytest tests only one case with @pytest.mark.parametrize
I defined UserFactory class in tests/factories.py as shown below following the doc. *I use pytest-django and pytest-factoryboy in Django: # "tests/factories.py" import factory from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User And, I defined test_user_instance() with @pytest.mark.parametrize() to test 4 users as shown below: # "tests/test_ex1.py" import pytest from django.contrib.auth.models import User @pytest.mark.parametrize( "username, email", { ("John", "test@test.com"), # Here ("John", "test@test.com"), # Here ("John", "test@test.com"), # Here ("John", "test@test.com") # Here } ) def test_user_instance( db, user_factory, username, email ): user_factory( username=username, email=email ) item = User.objects.all().count() assert item == True But, only one user was tested as shown below: $ pytest -q . [100%] 1 passed in 0.65s So, how can I test 4 tests? -
Profile not creating when creating a User with Django
I'm using DRF for my project and I need help in automatically creating a Profile instance for a User model when a User is created. My signals is: from django.db.models.signals import post_save from django.conf import settings from django.contrib.auth import get_user_model from .models import Profile User = get_user_model() def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) -
Django With Clean Architecture
I'm trying to build a python application using Clean Architecture principles. I already have the following structure: app/ ├── src │ ├── dependencies │ │ ├── dependencies.py │ │ └── __init__.py │ ├── infrastructure │ │ └── ui │ │ ├── __init__.py │ │ ├── interfaces │ │ │ ├── __init__.py │ │ │ └── ui.py │ │ ├── desktop │ │ │ ├── __init__.py │ │ │ └── tkinter_ui.py │ │ └── web │ │ ├── flask_ui │ │ │ ├── constants │ │ │ │ ├── constants.py │ │ │ │ └── __init__.py │ │ │ ├── endpoints │ │ │ │ ├── endpoints.py │ │ │ │ └── __init__.py │ │ │ ├── flask_ui.py │ │ │ └── __init__.py │ │ └── __init__.py │ ├── __init__.py │ └── main.py Makefile And it works fine for both Tkinter and Flask. Now I'm considering adding django to my project, so I thought my structure would be something like this: app/ ├── src │ ├── dependencies │ │ ├── dependencies.py │ │ └── __init__.py │ ├── infrastructure │ │ └── ui │ │ ├── __init__.py │ │ ├── interfaces │ │ │ ├── __init__.py │ │ │ └── ui.py │ … -
Django: Create and Update seperate objects
In Django models, I aim to ensure that when I create an object from one class, the corresponding object is created in another class. Furthermore, certain fields should be automatically inherited. Here's an example: `class Model1(models.Model): Malfunction = models.CharField(max_length=255, null=True) def __str__(self): return self.Malfunction class Model2(models.Model): sit_id = models.AutoField(primary_key=True) given_Malfunctions = models.ManyToManyField(Model1, blank=True) dynamik_2 = models.CharField(max_length=255, default=None, blank=True) def __str__(self): return f"[{self.sit_id:02d}]" class Model3(models.Model): connection_to_model2 = models.ForeignKey(Model2, on_delete=models.CASCADE, default=None) dynamik_3 = models.CharField(max_length=255, default=None, blank=True) ` Model3 object should be created every time a Model2 object got created. And the fields from dynamik_2 should be automatically updated to dynamik_3. Should i define the signals or functions in model 3? I encountered an issue with "post_save" since I couldn't establish the connection between related objects. -
User Validation Errors in XML File Uploading: Python/Django
When trying to create functionality in a full stack Django/React project that allows a user to upload (specifically XML) files, I ran into an issue in my User validation where it's throwing errors that the userId is not being grabbed. Here are the following relevant files: [ { "model": "easapi.user", "pk": 1, "fields": { "uid": "123456", "name": "Hayley", "email": "anemail@g.com" } } ] [ { "model": "easapi.log", "pk": 1, "fields": { "user": 1, "dateStart": "2022-11-22", "dateEnd": "2022-11-22", "dateGenerated": "2022-11-22" } } class User(models.Model): uid = models.CharField(max_length=50) name = models.CharField(max_length=50) email = models.EmailField(max_length=75) def __str__(self): return self.name class Log(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) dateStart = models.DateTimeField(max_length=20) dateEnd = models.DateTimeField(max_length=20) dateGenerated = models.DateTimeField(max_length=20) log_hash = models.CharField(max_length=255) def __str__(self): return self.name class LogView(ViewSet): def retrieve(self, request, pk): log = Log.objects.get(pk=pk) serializer = LogSerializer(log) return Response(serializer.data) def list(self, request): logs = Log.objects.all() uid_query = request.query_params.get('uid', None) if uid_query is not None: logs = logs.filter(user=uid_query) serializer = LogSerializer(logs, many = True) return Response(serializer.data) @staticmethod def generate_unique_log_hash(user_uid): while True: # Combine user UID, current timestamp, and random seed unique_string = f"{user_uid}_{int(time.time())}" # Generate a hash using SHA-256 hash_object = hashlib.sha256(unique_string.encode()) unique_hash = hash_object.hexdigest() try: # Attempt to retrieve a log with this hash Log.objects.get(log_hash=unique_hash) except Log.DoesNotExist: … -
App TemplateDoesNotExist in Django Project
I am struggling to figure out why I am receiving the TemplateDoesNotExist error in my project. This is my initial project layout. The project name is localassets, the initial app name is assetlist. I have registered the app in my settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', 'crispy_forms', 'crispy_bootstrap4', ] 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 = 'localassets.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', ], }, }, ] I have successfully created views and templates within this app and it displays all templates without issues. I now want to add another app to this project. This app is named workorders. I created the app the folder structure is shown below: I have also registered this app in the project settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', 'crispy_forms', 'crispy_bootstrap4', 'workorders.apps.WorkordersConfig', ] 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 = 'localassets.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', … -
Django: How to autocomplete user-creator field of a model in admin-panel
class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) text = models.TextField() approved = models.BooleanField(default=False) total_media_count = models.PositiveIntegerField(default=0) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) I log in in admin-panel (as a superuser, as a staff. Doesn't matter) and I want user field to be autocompleted with user who made this POST model instance in admin-panel. How can I do that? I've tried save() method, but it doesn't work for me. Also save_model method in admin.py P.S. Function of making posts in the project can only be made from admin-panel -
Celery: No result backend is configured
I am trying to use Celery to asynchronously webscrape course registration info from a school university website. Ultimately, I want to build something where users are notified if a seat opens up in a specific course. RabbitMQ is my message broker. I am using Django, when running my server I am met with an error. I don't know what I am missing but this is my first project using something like celery to query data asynchronously. If someone could be show me what i'm missing that would be greatly appreciated. Below is a screenshot of my RabbitMQ dashboard which I believe is running and configured with my project. Below is my code settings CELERY_BROKER_URL = 'amqp://localhost:5672' # RabbitMQ broker URL CELERY_RESULT_BACKEND = 'amqp://localhost:5672' views.py from django.shortcuts import render from bs4 import BeautifulSoup import requests from .forms import CourseRegistrationForm from .tasks import scrape_course_data def main(request): form = CourseRegistrationForm() if request.method == 'POST': form = CourseRegistrationForm(request.POST) if form.is_valid(): term = form.cleaned_data['semester'] subj = form.cleaned_data['subject'] crse = form.cleaned_data['course_number'] classes_result = scrape_course_data.delay(term, subj, crse) classes = classes_result.get() # Get the actual result print(classes) context = { 'form': form, 'classes':classes } return render(request, 'classes.html', context) else: form = CourseRegistrationForm() context = { 'form': form, } … -
Submitting jobs (to a postgre database) through django webpage, using slurm
I'm looking for advice on how to proceed, assuming at all this could be a viable course of action. I have coded a web-based interface (Django) to access some data stored on (an external) database. The role of the webpage is to serve as GUI to show the user what data can be downloaded, and where they are on a map. To avoid overwhelming the machine hosting the database, I am thinking in putting an intermediate layer between Django and the database, to manage submission of request to extract data. That would be slurm (or torque). It needs to be able to communicate through some python API. In essence, what I want to achieve is to allow the user to download data via either gui (Django amd plotly), OR by submitting a job file to slurm. The manager will, in turn, queue all the jobs and extract them one at the time. As an expected result, each registered user on the Django page, could access a dashboard (plugged to slurm) showing which jobs are running/pending, how long to completion, and possibly purge the ones that have already completed (or are no longer wanted). Note: I have only a few months … -
dotenv can not load read.dotenv
I have a django application. And I have dockerized the app. But I have a problem with the django-dotenv package. I have installed the django-dotenv package and not the python-dotenv. But if I try on my local machine: dotenv.read_dotenv() I get this error: Module 'dotenv' has no 'read_dotenv' member So I checked with pip freeze in my virtual environment if I have installed the correct package: (env) PS C:\repos\DWL_backend> pip freeze asgiref==3.6.0 attrs==23.1.0 certifi==2022.12.7 cffi==1.15.1 charset-normalizer==3.0.1 cryptography==39.0.0 defusedxml==0.7.1 Django==4.1.6 django-allauth==0.52.0 django-cors-headers==3.13.0 django-dotenv==1.4.2 djangorestframework==3.14.0 drf-spectacular==0.26.2 idna==3.4 inflection==0.5.1 jsonschema==4.17.3 oauthlib==3.2.2 Pillow==9.4.0 psycopg2==2.9.6 pycparser==2.21 PyJWT==2.6.0 pyrsistent==0.19.3 python3-openid==3.2.0 pytz==2022.7.1 PyYAML==6.0 requests==2.28.2 requests-oauthlib==1.3.1 sqlparse==0.4.3 tzdata==2022.7 uritemplate==4.1.1 urllib3==1.26.14 And now the funny part. I can run docker with: dotenv.read_dotenv() And the requirements.txt looks like: Django>=4.0.4 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-dotenv So the package name django-dotenv are the same. oke. when I do a uninstall. I see this two packages: Found existing installation: django-dotenv 1.4.2 Uninstalling django-dotenv-1.4.2: Would remove: c:\repos\dierenwelzijn_backend\env\lib\site-packages\django_dotenv-1.4.2.dist-info\* c:\repos\dierenwelzijn_backend\env\lib\site-packages\dotenv.py what is dotenv.py? And I have read the official documentation: https://github.com/jpadilla/django-dotenv Question: how to run dotenv.read_dotenv on my localhost? -
How can we use Django property decorator in Django rest framework?
Hello I trying to use Django property decorator in Django rest framework here my code Model.py class TempCalculate(models.Model): items = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) @property def Price(self): self.price = (PriceMaster.objects.get(items = self.items)) * self.quantity Serializer.py from rest_framework import serializers from base.models import TempCalculate class TempCalSerializer(serializers.ModelSerializer): class Meta: model = TempCalculate fields = "__all__" api/view.py @api_view(['GET']) def TempItem(request): queryset = TempCalculate.objects.all() serializer_class = TempCalSerializer(queryset, many=True) return Response(serializer_class.data) **I trying to access self.price (which I have make property decorator in models.py) in rest api **