Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS issue when making GET requests to Django server behind Caddy reverse proxy
I'm encountering a CORS (Cross-Origin Resource Sharing) issue when making GET requests to my Django server, which is hosted behind a Caddy reverse proxy. Here's the situation: I have a Django server running, serving an API. The Django server is behind a Caddy reverse proxy. I'm trying to make GET requests to my Django API from a front-end application hosted at a different domain. Using JS And Ajax requests I have already tried the following: Enabled the django-cors-headers package and added it to my INSTALLED_APPS and MIDDLEWARE settings in the correct order. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # Added this app ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # Placed CorsMiddleware here 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Configured CORS settings in my Django project's settings.py. DEBUG = True ALLOWED_HOSTS = ["*"] USE_X_FORWARDED_HOST = True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_METHODS = [ 'GET', 'POST', ] CORS_ALLOWED_ORIGINS = [ "https://www.example.net", "http://localhost:5000", "http://127.0.0.1:5000", "http://127.0.0.1:5501" ] Despite these configurations, I'm still encountering a CORS-related error when making GET requests to my Django API. Here's the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.net/nodeData/?nid=13. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. … -
Django Rest-Framework Token Authentication not working
Hello everyone I am trying to create simple signup, login and logout page. When I enter details of signup in postman it is working I checked on admin page but when logging in it always says Invalid credentials These are all the codes I have written If you want anything more please comment on this I will provide the info ASAP settings.py INSTALLED_APPS = [ .... 'app', 'rest_framework', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} class UserLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(write_only=True) views.py from django.shortcuts import render from rest_framework import generics, permissions, status from rest_framework.response import Response from django.contrib.auth import login, logout from django.contrib.auth.models import User from rest_framework.permissions import AllowAny from .serializers import UserSerializer, UserLoginSerializer from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken class UserRegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] class UserLoginView(generics.CreateAPIView): serializer_class = UserLoginSerializer permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) if serializer.is_valid(): user = serializer.validated_data.get('user') if user: login(request, user) token, created … -
How to add a confirmation popup dialog when saving an object in Django admin?
I have a model with name and email as fields. I want to show a warning popup to the user if there is already an entry with the same name. The user is allowed to create the entry once they acknowledge the warning. I'm looking to implement two specific features in this Django admin interface: Conditional Confirmation Pop-up: I want to display a confirmation pop-up dialog before saving data, but I want it to appear based on a specific condition. This condition is determined by user input. Confirmation for Data Saving: After clicking the 'Save' button, I want to see a confirmation dialog. Data should only be saved if the user confirms the action. I've attempted to use messages to achieve this, but I couldn't find a way to display a warning or error message before saving the data. -
How can I create tables dynamically in Django admin panel
i want to make a table for each event automaticly ,each table contains the participants of this event the result should look like this : models.py: class Student(models.Model): email = models.EmailField(unique=True) phone = models.CharField(max_length=10, blank=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) gender = models.BooleanField(default=1 ) ... class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True,default="events\posters\default.png") description = models.TextField(null=True,blank=True) event_date = models.DateField(null=True,blank=True) ... registrations = models.BooleanField(default=True) is_active = models.BooleanField(default=True) class EventParticipant(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) participant = models.ForeignKey(student, on_delete=models.CASCADE) join_date = models.DateTimeField(blank=True,null=True,default=timezone.now) ... -
Need Help Speeding Up Django and DRF with Celery TaskResult Table
I am currently working on an application that utilizes Django, Django Rest Framework (DRF), and Celery, with React in the frontend. I've been encountering a significant performance issue where loading the task results through the DRF API takes more than 10 seconds, as indicated by the debug toolbar. This issue becomes even more pronounced when multiple users attempt to access and display task results concurrently, leading to an API slowdown. In some cases, after sending around 10-15 such requests, my API becomes unresponsive for up to a minute and that causes error 499 in my nginx container making the app unusable for a minute or two. To provide some context, I am using the get_task_result_info function to update my custom SpiderTaskResult model. I've had to introduce additional fields to the default Celery TaskResult model to support the specific requirements of my Celery tasks. Here are the steps I've taken thus far to address the issue: Actions Taken: Implemented pagination in React to display a limited number of items (10 per page) in the APIView. While this approach has improved performance somewhat, it required some refactoring in the React code. Experimented with using Django's JsonResponse instead of a typical DRF APIView, … -
Should Django enumeration types like TextChoices be compared with `is` or `==`?
The Django Enumeration Types documention says that fields like models.TextChoices ... work similar to enum from Python’s standard library, but with some modifications. It's recommended to compare Enumeration members by identity (with is): >>> Color.RED is Color.RED True But the Django docs don't seem to say anything about comparing TextChoices values. Which of these two options is preferred? from django.db import models class FooChoices(models.TextChoices): FOO = "foo" BAR = "bar" class FooModel(models.Model): type = models.CharField(max_length=50, choices=FooChoices.choices) @property def is_foo(self): # Either... return self.type == DatapointDefinitionType.FOO # ... or return self.type is DatapointDefinitionType.FOO -
Why getting the "CSRF token is missing" when is already plugged in template?
I wanted to post a login form through AJAX Post request using JQuery: Even i sent the csrf token along the others however somehow Django fails to validify with the token inside a cookie. $(function(){ $(document).on('submit', 'form', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: 'login', data: JSON.stringify({ username: $('input[name=username]').val(), password: $('input[name=password]').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }), success: function(response){ console.log(response); } }); }); Here is the view function that url goes to: def login(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) return HttpResponse("Successfully logged in!") else: return HttpResponse("Username or Password is incorrect") else: return render(request, "login.html") 1.I thought that it would be solved if i didn't use {% csrf_token %} and i tried to get token and send to be rendered in the template in view.py: from django.middleware.csrf import get_token csrf_token = get_token(request) return render(request, 'login.html', {'csrf_token':csrf_token} it didn't solve the problem i still got that error. 2.I thought that it might be something related to the csrf cookie value. Everytime i registered a user to the database just the sessionid cookie's value changed and the csrf cookie remained same but i don't know how can i go about that. Any help would … -
Django - zappa issue
"{'message': 'An uncaught exception happened while servicing this request. You can investigate this with the zappa tail command.', 'traceback': ['Traceback (most recent call last):\n', ' File "/var/task/handler.py", line 572, in handler\n with Response.from_app(self.wsgi_app, environ) as response:\n', ' File "/var/task/werkzeug/wrappers/base_response.py", line 287, in from_app\n return cls(*_run_wsgi_app(app, environ, buffered))\n', ' File "/var/task/werkzeug/test.py", line 1119, in run_wsgi_app\n app_rv = app(environ, start_response)\n', "TypeError: 'NoneType' object is not callable\n"]}" I got this error on Django Admin when I deployed Django after updating DB model. I tried to redeploy the project from scratch. sometimes it works but this issue occurs every hour. -
Using Django's Redis settings in the Langchain chat memory
I want to use Langchain inside Django and use Redis for chat memory. But I want Langchain to use the Redis settings I set in Django and not connect to Redis directly. How can I implement something like this? I use Django version 4.1 and Langchain version 0.0.275. -
Django test parallel fails while clone database
I have weird behavior of Django tests in parallel mode: Command to run tests: python manage.py test --parallel Sometimes it works fine but in random moments I got error during cloning DB. Cloning test database for alias 'default'... ERROR 1062 (23000) at line 237: Duplicate entry '0' for key 'auth_permission.PRIMARY' mysqldump: Got errno 32 on write I did it on empty DB (ran python manage.py drop_test_database before running tests) Migrations applied successfully. And after that I got error with cloning, and tests that ran on failed copies raised the next error MySQLdb.ProgrammingError: (1146, "Table 'test_dbname_8.django_content_type' doesn't exist") This is very strange because sometimes I have successful test runs. Maybe the reason is MySQL, which does not support parallel execution well? without --parallel flag tests work fine -
ktor - make a post request with different naming of the keys of the JSON in kotlin and django
I want to make a post request with different naming of the JSON keys in Ktor and django. It is not a big deal but I want to follow the convention of naming the vals in Kotlin and django. This is how my user post request body looks in Kotlin/Ktor: @Serializable data class UserPostRequest( val username: String, val email: String, val password: String, val password_check: String ) The problem with this on is the "password_check" val, which is not named by convention Property name 'password_check' should not contain underscores When I try to change it to passwordCheck, make post request, it returns me an error that the passwords do not match. I assumed this is because django expects 'password_check' as a JSON key. -
Django custom middleware doesn't caches sometime
I am trying to make a multi tenant website. For example a.com and b.com websites runs same home.html but it's values changes by it's domain name. But my middleware doesn't caches sometimes. I added my cache_tenant_mw.py and redis in settings.py MIDDLEWARE = [ ... 'rhsuite.cache_middleware.cache_tenant_mw', ] CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379", } } and added the code which caches tenant values in cache_tenant_mw.py from rhsuite.models import Tenants, Themes, Settings, Metas, Languages from django.shortcuts import get_object_or_404 from django.core.cache import cache from rhsuite.helpers.utils import get_metas def cache_tenant_mw(get_response): def middleware(request): response = get_response(request) def get_hostname(request): host = request.get_host().split('.') popped = host.pop() joined = ".".join(host) return joined def get_tenant(request): hostname = get_hostname(request) tenant_obj = get_object_or_404(Tenants, name=hostname) # get metas and languages tenant_obj.metas = get_metas(Metas.objects.filter(meta_able_type="tenants", meta_able_id=tenant_obj.id)) tenant_obj.languages = Languages.objects.filter(id__in=list(tenant_obj.metas['languages'].values())) # cache tenant cache_key = "tenant" cache.set(cache_key, tenant_obj) cached_tenant = cache.get('tenant') # cache tenant settings settings_obj = Settings.objects.filter(tenant_id=tenant_obj.id) settings_key = "settings" cache.set(settings_key, settings_obj) # cache theme theme_obj = Themes.objects.get(tenant_id=cached_tenant.id) theme_key = "theme" cache.set(theme_key, theme_obj) return True get_tenant(request) return response return middleware How can i make it able to make my middleware cache every page everytime? -
What is the minimal setup for a Django Custom User Model?
I would like to install, as recommended, a custom user model for a new project early in the process, to avoid complications in migrating further down the line. But since the project is under development and acts as a testbed, I don't yet know which additional fields and methods I will require. I therefore want to get a custom user model up and running with the minimal required information so that the default registration (signup, login, etc) functions all work. I used the following code class User(AbstractUser): def __str__(self): return self.email I inherited from AbstractUser in order to obtain the default functionality, which seems to work. However, the (default) signup produces the following error in the browser: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' So it seems to me that I must also define a UserManager for the custom User. Now there is much advice available about how to do this if additional functionality is required (eg make the email the username, supply extra fields, and so on). But at this stage, I don't want any additional functionality. That will come later. At this point I simply want to ensure that users can sign up, login, change passwords, … -
Django: Select a valid choice. [..] is not one of the available choices using TextChoices
as per the title says, here's my error upon the process of validation of a form. Select a valid choice. 1 is not one of the available choices. Here's the different pieces of code I have. models.py: class Cat(models.Model): class Sex(models.TextChoices): M = 1, 'Male' F = 2, 'Female' sex = models.PositiveSmallIntegerField(choices=Sex.choices, blank=False, null=False) forms.py: class CatForm(forms.ModelForm): # Other fields that I think are useless in this error but maybe I'm missing something for the TextChoice of sex to work out here? fur_color = forms.ModelMultipleChoiceField(queryset=FurColor.objects.get_all(), required=False, widget=forms.CheckboxSelectMultiple) birth_date = forms.DateField(widget = forms.SelectDateWidget(years=range(1980, 2023))) class Meta: model = Cat exclude = ('user','registered_on') The sex field in the form appear as a select list, but when I select either of Male or Female, it doesn't seems to be able to make the link back in the model. Do I need do modify my forms.py to make it work. Or my model is flawed to begin with ? I have Django 4.2.5. Thanks in advance. -
Internationalisation across Django, React and Webcomponents [closed]
I am looking for a solution to unify internationalisation across Django, React and Webcomponents. Currently, we are using Django's gettext, Lit's lit/localize and non yet for React. I would like to unify this to use a single solution across rendering options. So far I came across project-fluent which seems to support all of them separately (django-ftl, react) but is also fractured into various projects and i18next whose Django support is outdated. Can anybody recommend a solution? Any help is appreciated. -
Saved object to db doesn't persist across multiple fixtures in pytest
I everyone, I'm testing my django APIs with pytest and I want to test the login endpoint of my apis. Hence, I need first to create a test user object and save it to db and then try to login with that user credentials and finally test if the response I get is how I expected it to be. I want the test user creation and the login user actions to be in two different fixtures, so that I can eventually call them independently if I need to. This is what I've got so far: @pytest.fixture @pytest.mark.django_db def create_test_user(): def _(): test_user = User.objects.create_user( username="test_user", password="test_password", email="test_email@test.com" ) test_user.save() return test_user return _ @pytest.fixture def login_user(client): def _(user): url = reverse('auth-login') body = { "username": user.username, "password": user.password } response = client.post(url, body, content_type='application/json') cookies_dict = dict((k, v.value) for k, v in response.client.cookies.items()) return response, cookies_dict return _ And then in my test I have: @pytest.mark.django_db def test_login(login_user, create_test_user): # Create a test user on DB test_user = create_test_user() response, cookies = login_user(test_user) # assertions .... The problem here is that when I try to log in with the test user, the user is no longer in db and so … -
JSON response is not getting data when used NGROK's static domain
I want to get JSON data so that it can be used in frontend. const authToken = 'e6f13bd9e9b74d540b8fc998b44e25bf2857cb5d'; fetch('https://absolutely-relaxed-koala.ngrok-free.app/api/admin-products/', { method: 'GET', headers: { Authorization: `Token ${authToken}`, }, }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log('API Response:', data); if (Array.isArray(data)) { // Process the data as an array and add product items to the list const productList = document.getElementById('product-list'); data.forEach(product => { const listItem = document.createElement('tr'); listItem.textContent = `${product.name} - Price: $${product.product_image}`; const image = document.createElement('img'); // Create an image element image.src = product.product_image; // Set the image source to the product_image URL listItem.appendChild(image); // Add the image to the list item productList.appendChild(listItem); }); } else { console.error('Invalid data structure. Expected an array.'); } }) .catch(error => { console.error('Error fetching products:', error); }); but I case of 'http://127.0.0.1:3000' works fine with JSON response while debugging a little I found out that the response is Response Data: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="author" content="ngrok"> <meta name="description" content="ngrok is the fastest way to put anything on the internet with a single command."> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link id="style" rel="stylesheet" href="https://cdn.ngrok.com/static/css/error.css"> <noscript>You are … -
RQ Job Terminated Unexpectedly
I have defined the rq task on module task.py as: import django_rq import logging from django.conf import settings import requests log = logging.getLogger(__name__) def req_call(): url = 'https://jsonplaceholder.typicode.com/posts' response = requests.get(url) return response @django_rq.job('default') def test_request_call_on_rq_job(): response = req_call() log.warning(f'REQUEST's RESPONSE {response.json()}') When I've offloaded task in another module as: if __name__ == '__main__': # rq job test log.setLevel(logging.DEBUG) test_post_request_on_rq_job.delay() I am getting error as: [INFO] *** Listening on default... [worker:702] [INFO] default: rq_test_module.tasks.test_request_call_on_rq_job() (676c1945-9e05-4245-aeb2-65100cdb4169) [worker:875] [WARNING] Moving job to FailedJobRegistry (Work-horse terminated unexpectedly; waitpid returned 11 (signal 11); ) [worker:1114] I then started doing debugging, then I saw error encounters as soon as the job task tried executing the request call i.e. requests.get(url) And if I remove the request call from the job, jobs executed gracefully without any errors. Signal 11 suggests a segmentation fault, I suspect something related to memory but not quite sure about it. So anyone here encountered similar issue and workaround for this :) -
deployment on elastic beanstalk
i am trying to deploy my django app on aws using the awsebcli amd i am trying to run the eb init command and i am getting this error DELL@DESKTOP-LOONUF5 MINGW64 ~/Desktop/kennedy_logistics (main) $ eb status ERROR: This directory has not been set up with the EB CLI You must first run "eb init". DELL@DESKTOP-LOONUF5 MINGW64 ~/Desktop/kennedy_logistics (main) $ eb logs ERROR: This directory has not been set up with the EB CLI You must first run "eb init". DELL@DESKTOP-LOONUF5 MINGW64 ~/Desktop/kennedy_logistics (main) $ eb init Select a default region us-east-1 : US East (N. Virginia) us-west-1 : US West (N. California) us-west-2 : US West (Oregon) eu-west-1 : EU (Ireland) eu-central-1 : EU (Frankfurt) ap-south-1 : Asia Pacific (Mumbai) ap-southeast-1 : Asia Pacific (Singapore) ap-southeast-2 : Asia Pacific (Sydney) ap-northeast-1 : Asia Pacific (Tokyo) ap-northeast-2 : Asia Pacific (Seoul) sa-east-1 : South America (Sao Paulo) cn-north-1 : China (Beijing) cn-northwest-1 : China (Ningxia) us-east-2 : US East (Ohio) ca-central-1 : Canada (Central) eu-west-2 : EU (London) eu-west-3 : EU (Paris) eu-north-1 : EU (Stockholm) eu-south-1 : EU (Milano) ap-east-1 : Asia Pacific (Hong Kong) me-south-1 : Middle East (Bahrain) il-central-1 : Middle East (Israel) af-south-1 : Africa (Cape Town) … -
Can I make a part of a finished Django Project CMS
So i finished programming the website for the company Newtive and i while programming i integrated Django because i wanted the projects part in the website to be CMS so that the owner of the website wont ask me to add each project whenever they make a new one but while trying to make it CMS from django's admin panel i faced allot of problems one of them is that i found out that he didn't want the same design pattern for all the project descriptions i could make them all the same pattern(for example making all the pictures inside a slider and under that will be the description) but he didn't want it he wants it the way it is now but i need a way to add this CMS feature because allot of projects are coming on the way. I am still a beginner and i have allot to learn any help is appreciated here is the page i am talking about https://newtivedesign.com/projects/ -
code to collectstatic on localhost static folder
I'm not sure what needs to be fixed, it's probably something on my settings.py, my localhost static folder is empty, but my s3 is working fine, picking up all of the collectstatic files that should also end up in my localhost folder (see image). Here's the relevant code from my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent DATA_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(DATA_DIR, 'media') STATIC_ROOT = os.path.join(DATA_DIR, 'static') STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' # CUSTOM STORAGES STATICFILES_STORAGE = 'custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' AWS_STORAGE_BUCKET_NAME = 'xxxxxxx-xxx' AWS_S3_SIGNATURE_NAME = 's3v4', AWS_S3_REGION_NAME = 'xxxx-xxx-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERITY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME I run python.manage.py collectstatic, and absolutely nothing gets copied to the static folder of my Django project like it's supposed to. -
Is there a django plugin that produces documentation for the template inheritance structure?
The django.contrib.admindocs plugin provides a nice link in the admin view to a variety of documentation around the data models. Is there a similar plugin that provides a diagram or description of how templates inherit from one another and the variables defined? Searched Django plugins https://djangopackages.org/search/?q=template+inheritance -
Summarize Django Queryset where Amount falls into Specific Groups
I'd like to group my transactions by the amount category that they fall into and sum those. I'd love to do this with 1 query, but I can't figure out what this kind of grouping is called. So I'm having a hard time finding any examples. zero_to_twenty = Transactions.objects.filter(amount__lte=0, amount__gt=-20).aggregate(Sum("amount")) twenty_to_fifty = Transactions.objects.filter(amount__lte=-20, amount__gt=-50).aggregate(Sum("amount")) fifty_to_seventy_five = Transactions.objects.filter(amount__lte=-50, amount__gt=-75).aggregate(Sum("amount")) seventy_five_to_one_hundred = Transactions.objects.filter(amount__lte=-75, amount__gt=-100).aggregate( Sum("amount") ) one_hundred_plus = Transactions.objects.filter(amount__lte=-100).aggregate(Sum("amount")) Obviously this is not ideal, but it gets me the correct data. Is it possible to do this with 1 query? -
Expected type 'Sized', got 'TextField' instead
I am working on a small project with Django and i have to validate the size for a text field and then return some data based on the condition. I am using the len() method to check the TextField() size and then return some data. The code is working, but I have an error from the IDE (Pycharm) that says: "Expected type 'Sized', got 'TextField' instead". I spent some time looking in some resources online but i can't find anything related to my issue. Have you deal with this before? Here's the code: ` class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" if len(self.text) < 50: return f"{self.text}" return f"{self.text[:50]}..." ` Thank you! -
Getting Error No Module found after deploying my DRF profject on Vercel
i'm trying to deploy my django rest framework to vercel free tier and during the deployment to show deployed successful witth the ready been ready, but when i open the link it return the following This Serverless Function has crashed. Your connection is working correctly. Vercel is working correctly. 500: INTERNAL_SERVER_ERROR Code: FUNCTION_INVOCATION_FAILED ID: cdg1::525rm-1695080572313-5e091aaaa7b6 If you are a visitor, contact the website owner or try again later. If you are the owner, learn how to fix the error and check the logs. and when i open the logs i see these error message [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' Traceback (most recent call last): please can anyone help out