Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djangos data cannot be imported into the database, is my code wrong?
I am new to Django, and I'd like to ask some questions I used the model layer to create the model with fields in it,it can create user_id,movie_id field in the database. class Rating(models.Model): user_id = models.CharField(max_length=16) movie_id = models.CharField(max_length=16) rating = models.DecimalField(decimal_places=2, max_digits=4) rating_timestamp = models.DateTimeField() type = models.CharField(max_length=8, default='explicit') def __str__(self): return "user_id: {}, movie_id: {}, rating: {}, type: {}"\ .format(self.user_id, self.movie_id, self.rating, self.type) class Cluster(models.Model): cluster_id = models.IntegerField() user_id = models.IntegerField() def __str__(self): return "{} in {}".format(self.user_id, self.cluster_id) Execute this statement using Python xxx.py,I want to populate the database but it doesn't work import os import urllib.request import django import datetime import decimal from tqdm import tqdm os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() from analytics.models import Rating def create_rating(user_id, content_id, rating, timestamp): rating = Rating(user_id=user_id, movie_id=content_id, rating=decimal.Decimal(rating), rating_timestamp=datetime.datetime.fromtimestamp(float(timestamp))) rating.save() return rating def download_ratings(): URL = 'https://gitee.com/zhangyoushang/wokkk/blob/master/latest/ratings.dat' response = urllib.request.urlopen(URL) data = response.read() print('download finished') return data.decode('utf-8') def delete_db(): print('truncate db') Rating.objects.all().delete() print('finished truncate db') def populate(): delete_db() ratings = download_ratings() for rating in tqdm(ratings.split(sep="\n")): r = rating.split(sep="::") if len(r) == 4: create_rating(r[0], r[1], r[2], r[3]) if __name__ == '__main__': print("Starting MovieGeeks Population script..." ) populate() But I found that my database was empty and there was no data in it. … -
How to fix using raw function MAX in queryset API not getting maximum marks?
views.py class MaxMarks(generics.ListAPIView): queryset = Marks.objects.raw('select student_id, subject_id, sem_marks, id, internal_marks, MAX(total_marks) from collegedetails.college_marks ') serializer_class = MarksSerializers I'm trying to figure out max marks using raw funtion in views.py after mapping to URL pattern and start run server but it getting only one record but still there more records which haveing max marks, Can any one suggest me what to do? -
request.POST data not in forms' cleaned_data
When creating a new instance of my model I fail to transfer the data from request.POST into the forms clean method on is_valid(): class cView(TemplateView): template_name = "store/new_product.html" def post(self, request, *args, **kwargs): print(request.POST) # correctly prints <QueryDict: {'number': ['8'], 'name': ['myproduCT'], 'price': ['2']}> obj = Product.objects.create(number = request.POST["number"], data = {}) form = ProductForm(request.POST, product = obj) form.is_valid() # validates to True The form looks like: class ProductForm(forms.Form): class Meta: model = Product fields = ["id", "number", "data"] def __init__(self, *args, **kwargs): product = kwargs.pop("product") super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) for key in product.data.keys(): self.fields[key] = forms.Charfield(requiered = False) def clean(self): cleaned_data = super().clean() print(cleaned_data) # only prints {'number': 8} ... Why is the rest of the request.POST data not in cleaned_data? Is this happening because the forms __init__() method gets an empty product.data attribute? How would I avoid this, when the Product is just now created and not filled with (validated) data? Product looks like this: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() -
Django download the right file from model
I created a web app that allows users to extract geometrical and other data from a 3D model in ifc format. So the user uploads the 3D model, the app gives him some basic info about the model and lets the user decide which data he wants to download in which format (xlsx or csv) For the uploaded file I have an upload form from the model. And then when the user decides what he wants to download I retrieve the uploaded file using the objects.latest query. But that can lead to problems, right? If multiple users are uploading files at the same time it can lead to a mismatch. What would a better practice of solving this problem be? How do I associate the page visitor withe the file he uploaded? -
Should I use Django or Flask for a microservice? I want to convert or generate any website into apk through microservices in python
Sir, I want to convert any website in apk through microservices in python, could you suggest to me which platform I'll used? and any suggention about microservices, please advice me cos I'm beginner in microservices..! -
how to check username exit or not two different table in djnago rest framework
while register new user in Tempdriver table need to varify username already exist or not in tempdriver table and appuser table, if check tempdriver table username its working but if i check appuser table getting error, pls someone help me out. models.py- add models Tempdriver and Appuser class Tempdriver(BaseModel): name = models.CharField(max_length=255) username = models.CharField(max_length=20,unique=True,null=True, blank=True) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) password = models.CharField(max_length=100) class AppUser(BaseModel): username = models.CharField(max_length=50) seriliazers.py class TempDriverUserSerializer(serializers.ModelSerializer): class Meta: model=Tempdriver fields=('username','mobile') def validate(self,username): user=Tempdriver.objects.filter(username=username) user_exists = AppUser.objects.filter(username=username) if user.exists() and user_exists.exists(): raise serializers.ValidationError("UserName already exists") def validate_mobile(self, mobile): mobile=Tempdriver.objects.filter(mobile=mobile) if mobile.exists(): raise serializers.ValidationError("Mobile Number already exists") views.py class Tempuserapi(APIView): parser_classes=(MultiPartParser,FormParser) def post(self, request, format=None): serializer = TempDriverUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_200_OK) else: return Response(serializer.errors, status= HTTP_200_OK) trace report ERROR Internal Server Error: /api/tempusercheck/ Traceback (most recent call last): File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File … -
How to apply other bootstrap and html properties to Django form fields
{{ form.firstname|as_crispy_field}} I want to know how further I can add bootstrap classes to this Django form field and also I want to add a placeholder thank you -
Django CheckConstraints to check start_date greater than or equal today
from django.db.models.functions import Now, TruncDay class Foo(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() class Meta: constraints = [ name="start_date must be greater than or equal today", check=CheckConstraints(start_date__gte=TruncDay(Now())) ] like above code, I want to add CheckConstraint to check whether start_date is greater than or equal with today. but, after makemigration and migrate, error happened. functions or expression 'CURRENT_TIME' cannot be userd in check clause How can I check start_date with today? -
How to group data in Django serializer?
I have two models one for Collection and the other for Services and what I want is to return each collection with its services. Here is my code: class Collection(models.Model): name = models.CharField(max_length=50, verbose_name=_('Name')) enabled = models.BooleanField(default=True, verbose_name=_('Enabled')) def __str__(self): return self.name class Meta: verbose_name_plural = _('Collection') class MoreWorks(models.Model): collection = models.ForeignKey(Collection, on_delete=models.PROTECT) title = models.CharField(max_length=50, verbose_name=_( "Title"), blank=True, null=True) description = models.TextField( verbose_name=_('Description'), validators=[MaxLengthValidator(1000)], blank=True, null=True ) image = models.ImageField( verbose_name=_("Image"), upload_to='more_works/' ) enabled = models.BooleanField(default=True, verbose_name=_("Enabled")) class Meta: verbose_name_plural = _('More Works') I want to return each collection with its services using DRF. -
Stripe: 'payment_intent.succeeded' is also triggered when subscription gets renewed
I have two APIs for Stripe webhooks in my backend (Django). "Subscription" webhook: /api/subscriptions/webhook/ "Add Balance to Wallet" webhook: /api/wallet/webhook/ In the subscription webhook, I listen for invoice.paid and invoice.payment_failed events and in the wallet webhook I listen for payment_intent.succeeded event. The problem is whenever the subscription webhook gets called, the payment_intent.succeeded event is also triggered for the wallet webhook. I think that's because payment intents are also created for subscription as well. I need a way to differentiate these two (one-time payment [aka add balance to wallet] and subscription) so I don't end up with extra credit in user's wallet whenever their subscription get renewed. -
How do you return a complete url with get_success_url(self) in django?
How do you return a url using get_success_url(self) in django without using reverse for a generic view? Basically, I want to have something as below. def get_success_url(self): url = self.object.url # This is a charfield with "https://stackoverflow.com/questions/ask" return url I know that people often use reverse when returning a url, but I would like do it like above. Thank you, and please write any questions you have. By the way, I never tested the above code, but I don't know if it will work properly. -
Can we check whether a user is part of an Organizational Units instead of Groups in Django LDAP?
In my LDAP directory, Users are added to Organizational Units instead of groups. How can I check whether a user is a part of an Organizational Unit using Django LDAP ? My settings.py file: AUTH_LDAP_SERVER_URI = 'ldap://qwery' AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_BIND_DN = 'dndndn' AUTH_LDAP_BIND_PASSWORD = 'pwdpwd' AUTH_LDAP_USER_SEARCH = LDAPSearchUnion( LDAPSearch('ou=abbb,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=ammmm,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=addddd,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=ahhhhh,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), ) AUTH_LDAP_CACHE_TIMEOUT = 0 AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "name": "cn", "username": "sAMAccountName", "department":"distinguishedName" } AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=addddd,DC=xxx,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=*)") AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_USER_MODEL = 'login.Account' AUTH_LDAP_USER_FLAGS_BY_GROUP= { "is_it": "OU=IT,OU=ahhhh,DC=xxx,DC=net", } Thank you -
ResfFrameWork Invalid username/password error when no auth setting is set
I made rest-frame-work API server, I didn't set any auth setting. It works well on local, but on server, it shows below. HTTP 403 Forbidden Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } My server setting is like this below. application is on Nginx-unit and proxy is on Nginx When I access Nginx-unit directly, it doesn't show this error. However accessing Nginx, it shows the error. http://myserver.com:8888/api/balls Nginx url # it works http://myserver.com:8010/api/balls Nginx-unit url # it shows the error. Why does this happens or where should I fix?? My setting.py is here. from pathlib import Path from decouple import config import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o9nbo46qbraxo1qw$gauk!uznxhzy4pmt^9w2p1pu*h943(wpr' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'defapp.apps.DefappConfig', 'django_extensions', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': … -
How to upload a json file in Django REST API
I am new in backend stuffs. I am trying to learn DJANGO rest api. I have to upload a json(from local) file to DJANGO REST API which contains all training prediction log. I tried to create app and did setting part, but I am kind of stuck here. It would be easier if I get some hints for my question. How can I make django model and django view which pulls json file from json file from trainng folder and visualize the prediction result? Thank you. my json file format: [{ "datetimeAt":"2021-12-24 21:00:00", "loss":0.2538179466, "rolling_mean":0.3990683079, "total":0.0 }, .............. ] -
how can we download all images as zip file in my model Django
how can we download all images as zip file in my model Django class Player(TimeStampedModel): name = models.CharField(max_length=200) email = models.CharField(max_length=200) team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING) def __str__(self): return self.name -
Gunicorn cannot release cpu usage after response
I use Gunicorn to start my Django project, here is the command. command=gunicorn myproject.asgi:application --workers 4 --threads 3 --timeout 1200 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:778 However, I found my CPU load is around 100% one or two minutes after responding a GET request. As a compare, I changed to python manage.py to start my project, the same request reponsed, the CPU load is not higher than 10%. I have a total of 16 CPUs in my system. Anyone knows the reason? Thanks in advance. -
How to get a value of particular field inside loop Django
I want to print values of 'sm' inside loop alist = [ {'price': '700', 'sizes': {'sm': True, 'md': False, 'lg': True, 'xl': True} }, {'price': '900', 'sizes': {'sm': False, 'md': True, 'lg': True, 'xl': True} } ] for i in alist : print(i.get('sizes'['sm'])) -
How to make a query using multiple foreign key fields of Django models?
Hi all! New in Django, and confused, help is appreciated! I'm trying to create table, like: | Organization | Appeal Form | Amount of appeals in this form | | -------- | -------------- | -------------- | | Organization 1 | In written form | 5 | | Organization 2 | In oral form | 17 | Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) Objects of Organization model: | organization_name | | -------- | | Organization 1 | | Organization 2 | Objects of AppealForm model: | form_name | | -------- | | In written form | | In oral form | Objects of Appeal model: | organization | appeal_form | applicant_name | | -------- | -------- | -------- | | Organization 1 | In written form | Mary Elizabeth Smith | | Organization 2 | In oral form | Ada María Guerrero | Just rendered Appeal model to index.html, but confused how to filter objects, count and place into the table... I have been trying to make a query, but no luck till now :( -
Upload File in Django
In this upload file, I want to save my uploaded files along with machine name and operation number. it is working but giving error in template. when I click save button it is not showing on the template. Please help to solve this. views.py: def index(request): if request.method == 'POST': form = MachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file1','file2','file3','file4','file5','file6','file7']) model_instance = form.save(commit=False) model_instance.save() obj=form.instance return render(request,'usermaster/upload_file.html',{'obj':obj}) else: form = MachineForm() machine = Machine.objects.all() return render(request,'usermaster/upload_file.html',{'form':form,'machine':machine}) def handle_uploaded_file(f): with open('usermaster/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() def __str__(self): return self.machine_name file1 = models.FileField(upload_to='documents/',default="") file2 = models.FileField(upload_to='documents/',default="") file3 = models.FileField(upload_to='documents/',default="") file4 = models.FileField(upload_to='documents/',default="") file5 = models.FileField(upload_to='documents/',default="") file6 = models.FileField(upload_to='documents/',default="") file7 = models.FileField(upload_to='documents/',default="") forms.py: class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' admin.py: admin.site.register(Machine) upload_file.html: <html> <head> <title>Django File Upload</title> </head> <body> <p><h1>Django File Upload</h1></p> <form method="post" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> <br><br> <table border="1"> <tr> <th>Machine Name</th> <th>Operation Number</th> <th>Files</th> </tr> {% for file in machine %} <tr> <td>{{ file.machine_name }}</td> <td>{{ file.operation_no }}</td> <td> <a href="/media/{{file.upload_file}}">view file</a></td> </tr> {% endfor %} </table> </form> … -
How to have two arguments in a django custom filter
I am trying to manipulate two objects for a calculation, however I am getting the error:"Invalid filter" In the html frontend I have a nested loop with objects: units and person as following: {{units|myFilter:person}} where units has several objects and person only has one. my filter is defined by: def myFilter(units,person): n = 0 for i in units: if i.name == person.name: n = n + 1 return n But is it not working, any ideas or suggestions please? -
How do I change the default schema to custom_schema in postgres from djnago setting file?
Please help me to change the default schema from public to custom_schema. -
I am trying to redirect to PK URL while already using a PK inside a class based view
Basicaly after the message is edited i want to redirect user to the room where message is The closest i got with is when i manually passed PK of the room. And as far as i am reading passing two pk's inside a function is not allowed in Django. Could you helpt me solve this as for know i am limited in my knowledge and can't find a good answer. (I used <a href="{{request.META.HTTP_REFERER}}">Go Back</a></button> for going back functionality in template but i wish to change this aswell because from what i've read it's not the best practice) Thanks for patience url.py urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>/', views.userProfile, name="user-profile"), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>/', views.updateRoom, name="update-room"), path('delete-room/<str:pk>/', views.deleteRoom, name="delete-room"), path('delete-message/<str:pk>/', views.deleteMessage, name="delete-message"), path('update-message/<str:pk>/', views.updateMessage, name="update-message"), ] Views from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from .models import Message, Room, Topic, Message from .forms import RoomForm, MessageForm def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('created') participants = room.participants.all() if … -
How to render error or validation messages to ModelForm in 2022
I've spent several hours researching on the internet, especially the official Django documentation, but still it is not clear to me which is the best option in 2022 (since almost all questions I read on SO are > 6 yo) and there are diverse opinions on whether crispy forms is better or not. Is still crispy forms a recommended option? How can I (and what is the most recommended way to) get the typical validation error messages? Like: "this field is mandatory" or "this input accepts numbers only"? I've seen some Django pages using those default messages but I don't know how to show them in my ModelForm fields. Lets say I have the following model: class Project(models.Model): project_name = models.CharField(max_length=250, null=False, blank=False) status = models.CharField( max_length=250, null=True, blank=True, default=PROJECT_STATUS_DEFAULT, choices=PROJECT_STATUS, ) creation_date = models.DateField(max_length=250, null=False, blank=False) project_code = models.IntegerField(null=True, blank=True) notes = models.CharField(max_length=250, null=True, blank=True) And for the Project model I have the following ModelForm: class CreateNewProjectForm(ModelForm): creation_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS) #UK Date format class Meta: model = Project fields = '__all__' The view, when I try to create a new object Project: def add_new_project(request): context = {} if request.method == 'POST': form = CreateNewProjectForm(request.POST) if form.is_valid(): … -
Django 3.2.6 | Admin | get_form() | Modify Form Field | Error: 'NoneType' object has no attribute 'base_fields'
I am customizing my Django Admin forms to modify a form field queryset. The below code works on some of my Models but not others. The only differences between the models is the name as they all have the same fields: Club = models.ForeignKey('configuration.Club', on_delete=models.SET_NULL, null = True, blank=True) Title = models.CharField(max_length=30, blank=False) Description = models.CharField(max_length=120, blank=True) Code that throughs an exception (Trophy) Model: class Trophy(models.Model): Club = models.ForeignKey('configuration.Club', on_delete=models.SET_NULL, null = True, blank=True) Title = models.CharField(max_length=120, blank=False, unique=True) Description = models.CharField(max_length=360, blank=False, unique=True) class Meta: ordering = ['Title', 'Club'] unique_together = ['Title', 'Club'] def __str__(self): return self.Title Admin: class TrophyView(admin.ModelAdmin): list_display = ('id', 'Club', 'Title', 'Description') #Modify Form def get_form(self, request, obj=None, **kwargs): #Get User's Profile >> Club user = request.user profile = vMemberDetails.objects.get(username=user.username) club = profile.Club_pk clubID = Club.objects.filter(id=club) #Super form = super(TrophyView, self).get_form(request, obj, **kwargs) form.base_fields['Club'].queryset = clubID #Modify View def get_queryset(self, request): qs = super(admin.ModelAdmin, self).get_queryset(request) user = request.user profile = vMemberDetails.objects.get(username=user.username) club = profile.Club_pk clubID = Club.objects.get(id=club) profiles = vMemberDetails.objects.filter(Club_pk=clubID.pk) if request.user.is_superuser: return qs else: return qs.filter(Club=clubID.pk) | qs.filter(Club__isnull=True) admin.site.register(Trophy,TrophyView) When I print(form.base_fields): {'Club': django.forms.models.ModelChoiceField object at 0x000001E3895D6AF0, 'Title': django.forms.fields.CharField object at 0x000001E3895D6A60, 'Description':django.forms.fields.CharField object at 0x000001E3895D6D30} When I print(form.base_fields['Club'].queryset): QuerySet [Club: Test_001 Club, Club: … -
Having Error after deploying Django in Heroku. LookupError
I just deployed my sentiment analysis django app to heroku. The deployment was successful and I can access the features like login register etc. But I am unable to analyze the text because apparently, nltk cannot be found. But I have installed and imported it in my local host and it already worked before. This is my first time deploying in heroku so I am unfamiliar with everything. This is how it looks in my local host: This is the error in the herokuapp live webapp when I try to analyze the sentiment. LookupError at /sentiment/type/ ********************************************************************** Resource e[93mpunkte[0m not found. Please use the NLTK Downloader to obtain the resource: e[31m>>> import nltk >>> nltk.download('punkt') e[0m For more information see: https://www.nltk.org/data.html Attempted to load e[93mtokenizers/punkt/PY3/english.picklee[0m Searched in: - '/app/nltk_data' - '/app/.heroku/python/nltk_data' - '/app/.heroku/python/share/nltk_data' - '/app/.heroku/python/lib/nltk_data' - '/usr/share/nltk_data' - '/usr/local/share/nltk_data' - '/usr/lib/nltk_data' - '/usr/local/lib/nltk_data' - '' ********************************************************************** Request Method: POST Request URL: https://sentymeter.herokuapp.com/sentiment/type/ Django Version: 4.0 Exception Type: LookupError Exception Value: ********************************************************************** Resource e[93mpunkte[0m not found. Please use the NLTK Downloader to obtain the resource: e[31m>>> import nltk >>> nltk.download('punkt') e[0m For more information see: https://www.nltk.org/data.html Attempted to load e[93mtokenizers/punkt/PY3/english.picklee[0m Searched in: - '/app/nltk_data' - '/app/.heroku/python/nltk_data' - '/app/.heroku/python/share/nltk_data' - '/app/.heroku/python/lib/nltk_data' - …