Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I check if a user is in a group or another group
I'm making an API using django and I want to check whether the user is in a group A or a group B using request.user.groups.filter() method but it does not seem to work. I want to be able to pass more than just one group through the name parameter to check if they are indeed in group A or group B. I've tried the following: if request.user.groups.filter(name="A") or request.user.groups.filter(name="B"): do stuff I've also tried: if request.user.groups.filter(name="A" or "B"): do stuff But I seem to be getting no luck and all I'm getting is that I need to be in group A to access the content when I want it to check whether I'm in A or B. -
There is no way to use app password on gmail account trough django app
I have running in production a django app, the webapp has a function in order to send emails with attachment to some guys using a gmail account through app password option . The functionallity worked OK for more than 3 years until a couple of days when show up this error in the errorlog: App 2165051 output: smtplib.SMTPAuthenticationError: (535, b'Incorrect authentication data') Things that i've already checked: 1.- When I checked the app password of gmail account there wasn´t anyone. ( weird, it seems that dissapeared) 2.- I created a new one, replace the new password in my code and still showing 535 error. 3.- I've create trhee app passwords and still no luck. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@adicra.org.ar' EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = True views.py #Vista de enviar por mail class pagosMailPdfView(View): def get(self,request,*args,**kwargs): print("Aca en pagosMailPdfView") mailServer = smtplib.SMTP(settings.EMAIL_HOST,settings.EMAIL_PORT) #print(mailServer.ehlo()) mailServer.starttls() #print(mailServer.ehlo()) print(settings.EMAIL_HOST_USER) print(settings.EMAIL_HOST_PASSWORD) mailServer.login(settings.EMAIL_HOST_USER,settings.EMAIL_HOST_PASSWORD) print("conectando...") # averiguo la dirección de email del socio pagoh=PagosHead.objects.get(pk=self.kwargs['pk']) emailsocio=pagoh.numero_socio.email I assume that the problem is related to the google account configuration. Does anybody knows how to check this? Thanks in Adavance, Regards -
Third level HTMX back to original page?
I am using Django & HTMX. I have two sites, lets say site FOO and site BAR They both load HTMX page #1 on load There are links on HTMX page #1 for a modal- HTMX page #2 I am trying to code DRY and need a way for a button on HTMX page #2 to take me back to site FOO or site BAR, depending on where I started. I could add a ? variable in the URL and take it through two levels but I was wondering if there was an easier way. thanks! -
Problem creating django project in Pycharm
When I try to create Django project using Pycharm I receive errors which doesn't allow me to create the project. Now I am only able to create Django project using the terminal. I am able to create a Django project using the terminal but I am currently in python web course where the creation of Django projects happens only with Pycharm so I will be really greatful to solve this problem [[(https://i.stack.imgur.com/0Y33j.png)](https://i.stack.imgur.com/3ecvJ.png)](https://i.stack.imgur.com/opu8j.png) -
aws CLI configured properly but why boto3 not getting the credential?
AWS cli working but boto3 not working. I installed aws CLI on my ubuntu server and the problem is boto3 not getting the credentials from my Ubuntu machine until I hardcode the key in my code like s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, region_name=REGION_NAME ) I also run this command to aws s3 ls to verify does aws CLI working or not and it's returning all of my aws bucket name which means CLI configured properly but why boto3 not getting the credential from my ubuntu machine. I am using boto3 in my django project. -
Django TypeError: str returned non-string (type NoneType) in admin change view
I'm encountering an error when trying to access the admin change view for an order object in my Django application. The error message states: "TypeError: str returned non-string (type NoneType)." This issue occurs when accessing the URL http://127.0.0.1:8000/admin/accounts/order/38/change/. Here are some additional details about the problem: Django version: 4.2 Python version: 3.11.3 Exception location: C:\Users\Brenn Alexander\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\models.py, line 1504 The error seems to be related to the str method defined in one of my models. Here's the relevant code snippet: class Order(models.Model): # ... def __str__(self): if self.product: return str(self.product) return f"No Product (Order #{self.id})" I suspect that there might be an issue with the product field in the Order model, causing the str method to return None. This error is then propagated to the admin change view, resulting in the mentioned error. I'm unsure how to troubleshoot and resolve this issue. I would greatly appreciate any insights or suggestions on how to fix this error and ensure that the str method returns a string value as expected. Thank you in advance for your help! `class Product(models.Model): CATEGORY = ( ('Residential', 'Residential'), ('Commercial', 'Commercial'), ('Auto', 'Auto'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = … -
Django REST Framework NOT NULL constraint failed: afritechjobsapi_postajob.job_category_id
When I try to create a new Job post by posting the following JSON: { "job_title": "Software Developer", "job_category": [ { "id": 1, "name": "Engineering" }, { "id": 2, "name": "IT" } ], "job_skills": [ { "id": 1, "title": "DJ", "category": [ { "id": 1, "name": "Web Development" }, { "id": 2, "name": "Python" } ] }, { "id": 2, "title": "RT", "category": [ { "id": 3, "name": "Frontend Development" }, { "id": 4, "name": "JavaScript" } ] } ], "job_salary_range": 80000, "job_description": "We are looking for a skilled software developer proficient in Django and React...", "job_type": { "id": 1, "job_type_choices": "FT" }, "job_location": [ { "id": 1, "name": "New York" }, { "id": 2, "name": "San Francisco" } ], "job_level": [ { "id": 1, "job_level_choices": "EL" }, { "id": 2, "job_level_choices": "ML" } ], "job_application_link": "https://example.com/apply", "company_name": "ABC Company", "company_hq": "New York", "company_logo": "https://example.com/logo.png", "companys_website": "https://example.com", "company_contact_email": "info@example.com", "company_description": "ABC Company is a leading software development company...", "date_created": "2023-06-09T12:00:00Z", "date_updated": "2023-06-09T14:30:00Z" } I get the following error: IntegrityError at /jobs/create NOT NULL constraint failed: afritechjobsapi_postajob.job_category_id MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True, null=True, blank=True) def __str__(self): return self.name class JobLocations(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class JobType(models.Model): … -
How to successfully set up both the html templace and view for Recaptcha v2 without using forms
I read other related questions about recaptcha and django without forms but I didn't find a complete solution or the posts where too old. My situation is this: I am using the package django-recaptcha. I added the "captcha" app in INSTALLED_APPS and setted up the private and public keys for recaptcha. This is currently my code in views: def verify_recaptcha(response): url = 'https://www.google.com/recaptcha/api/siteverify' params = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': response, } response = requests.post(url, data=params) data = response.json() return data['success'] def contact(request): context = { 'RECAPTCHA_PUBLIC_KEY': settings.RECAPTCHA_PUBLIC_KEY } if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') captcha_response = request.POST.get('recaptcha_response') if name and email and message: if verify_recaptcha(captcha_response): send_mail( subject="Contact Form Submission", message=f""" Name: {name} Email: {email} Message: {message} """, from_email=FROM_EMAIL, recipient_list=[TO_EMAIL], fail_silently=False, ) context['message'] = 'Your message has been sent!' else: context['error'] = 'Invalid reCAPTCHA response.' else: context['error'] = 'Please fill in all required fields.' return render(request, 'contact.html', context) And this is the extract of my html template: <div class="field"> <div class="g-recaptcha" data-sitekey="{{ RECAPTCHA_PUBLIC_KEY }}"></div> <input type="hidden" name="recaptcha_response"> </div> <div class="field has-text-centered"> <button type="submit" class="button is-success has-background-success-dark"> Submit </button> </div> I am using the recaptcha v2. The widget seems to work just fine in the … -
How to log user into Superset UI
I'm using Django and superset. I'm able to login programmatically in one of my views and get an access token and a csrf token with my username and password. However, my end goal is to log the user into an embedded superset dashboard in one of my templates. In my view I'm using request sessions and I can see my cookie session value. In my UI, the cookie that is set is a different value. Is there a way that I can tell Django to use the same request session in my template as what is being used in my view? Or, perhaps there is another way to accomplish the same task of logging a user into the UI automatically. I'm open to that too, it just seems like I'm so close. The code I'm using is below, specifically the programmatic_login function. It all works, I would just like to let my template know that the user has already been authenticated. class SuperSetApi(): csrf_token = '' access_token = '' refresh_token = '' session = None base_url = 'http://superset:8088/' username = '' password = '' guest_token = '' custom_token = '' def url(self, base_url, url_path): return base_url + url_path def add_remote_user_header(self, … -
How to display Comments total on other page using in django using annotate()
any one to help me on how to use annotate() to display the comments total for each object in django model. below is my code. models.py class GameArticle(models.Model): sno=models.AutoField(primary_key=True) status=models.CharField(max_length=10, choices=STATUS, default='Draft') uid= ShortUUIDField(help_text='Place for the Article ID ', unique=True, max_length=10, length=5, prefix='ar',alphabet='aBcDeFgHjKlM12345') title = models.CharField(max_length=200, help_text='Enter The Article Title') class GameArticleComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) article=models.ForeignKey(GameArticle, on_delete=models.CASCADE, related_name='comments') parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp=models.DateTimeField(default=now) class Meta: ordering=['-timestamp'] Views.py def game_article(request): article_list = GameArticle.published.all() #............ def article_detail(request, uid): data = get_object_or_404( GameArticle, slug=uid, status='p') comments = GameArticleComment.objects.filter(article= get_object_or_404(GameArticle, slug=uid), parent=None) any one to direct me on how to use annotate and return the total of the comments for each object -
Django form error using ManyToMany relationship - TypeError: Field 'id' expected a number but got <Profile: user1>
I am making a recommendation app where a user can recommend a movie/show/book to one or more users. The form is set up so that it displays a list of all users and you can check a box next to the users you want to send the recommendation to, but I am getting this error (Field 'id' expected a number but got <Profile: user1>) when I hit "Submit" on my form after checking the box next to the username and I'm not sure where I went wrong. Most of the other questions related to this are using ForeignKey rather than ManyToManyField in their model. models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField( 'self', related_name='followed_by', symmetrical=False, blank=True, ) def __str__(self): return self.user.username class Recommendation(models.Model): user = models.ForeignKey( User, related_name="recs", on_delete=models.DO_NOTHING ) recipients = models.ManyToManyField( User, related_name="received_recs", symmetrical=False, blank=True ) title = models.CharField(max_length=300) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return ( f"{self.user} " f"({self.created_at:%y-%m-%d %H:%M}): " f"{self.title}" ) views.py: from django.shortcuts import render, redirect from .models import Profile, Recommendation from .forms import RecForm def dashboard(request): all_recs = Recommendation.objects.all() if request.method == "POST": … -
Is it bad written my custom authentication backend in Django?
I'm trying to implement a custom authentication backend in Django, mi custom Auth model and my custom user creation form works ok, but when I'm try to login using my custom authentication backend, it raise me this excepcion. Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\authentication\views.py", line 12, in login usuario = UsuarioAuthBackend.authenticate(request, email=email, password=password) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: UsuarioAuthBackend.authenticate() missing 1 required positional argument: 'request' [09/Jun/2023 10:47:15] "POST /login/ HTTP/1.1" 500 66119 It tells me that I got 1 missing required positional argument, the request. But that argument was passed in the code, I'll share you my code. The Custom User Model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # choices CALIFICACION_USUARIO_CHOICES = [ (0,0), (1,1), (2,2), (3,3), (4,4) ] # Create your models here. class UsuarioManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('El usuario debe tener un correo electrónico') email = self.normalize_email(email) usuario = self.model(email=email, **extra_fields) usuario.set_password(password) usuario.save(using=self._db) return usuario def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, … -
Why is my django application on cpanel only recognising the root url and not any other url after the root url?
I recently deployed my Django application on a subdomain through Cpanel. However, when I try to access the application, only the root url is working. Any other address is not being sent. In the browser, anything after the / of the root url is grayed out and the logs of the application also suggest they are not receiving the entire address. I have attached screenshots herein for clarity. Any help will be appreciated. -
Django DB issue (Interface error: connection closed)
Calling all Pythonistas! I'm embarrassed to say, but this issue has been plaguing us for 3 weeks! It's intermittent with no rhyme or reason. Ubuntu 22.04 running Docker containers (uses the solid cookiecutter-django) as a base which we've used successfully for many years. django==4.1.9 gunicorn==20.1.0 psycopg2==2.9.6 When submitting a simple registration form, randomly, but very frequently we get the following error: InterfaceError connection already closed This issue is ALWAYS at django/db/backends/postgresql/base.py in create_cursor at line 269 which is cursor = self.connection.cursor() In Sentry it shows as a "System" error, not an "In-App" error (ie - code flaw). The form: class GuestForm(forms.ModelForm): time = forms.ChoiceField(choices=[]) # time = forms.ChoiceField(choices=[("18:30", "6:30 PM")]) class Meta: model = Guest fields = ["first_name", "last_name", "email", "opt_in"] def __init__(self, *args, **kwargs): logger.debug("=> Init GuestForm") super().__init__(*args, **kwargs) self.fields["time"].choices = get_choices() def clean_time(self): """Return a time.""" cleaned_data = super().clean() hours, minutes = cleaned_data["time"].split(":") try: return datetime.time(int(hours), int(minutes)) except ValueError as exc: raise ValidationError( "Invalid value: %(hours)s %(minutes)", code="invalid", params={"hours": hours, "minutes": minutes} ) from exc The view: class RegisterView(FormView): form_class = GuestForm template_name = "tour/register.html" tourgroup = None @transaction.atomic def form_valid(self, form): """While we are creating a Guest, we are ultimately creating a TourGroup.""" # Create or get … -
Django admin _continue and _addanother not working
I have 3 buttons in django admin: save, save and add another, save and continue. They have their input names in html like _save, _addanother and _continue. All of these buttons do the same thing - save model and redirect to the main page (like when I click on the save button) class StudyFormAdmin(admin.ModelAdmin): list_display = ['name'] fields = ['name'] I found out that response_add method contains redirect functionality (https://github.com/django/django/blob/ef62a3a68c9d558486145a42c0d71ea9a76add9e/django/contrib/admin/options.py#L1316). Then I tried to check what in my request.POST. I add these lines to my model: def response_add(self, request, obj): print(request.POST) return super().response_add(request, obj) Output: <QueryDict: {'csrfmiddlewaretoken': ['2IOoriUmt5IzfIKU7MY53hZ9dgupnM3sNU6ltcaKXXzwmDB73xekyXn55Pw197dF'], 'name': ['adfgdfg']}> I have tried all these buttons for each model I have but response always the same -
How to Fill in django form with a json file?
I'm building a django system that will receive a file and will return a json file and some graphics. The graphics is working but now and i need to fill in a django form with a json file. Basically, when the user make the upload a django form will filled and after that the graphics will return. How can i do that ? -
Django ModelForm CharField changed to ModelChoiceField results in not filled in values in edit mode
I have a model that has owner as CharField that should "house" the username of the owner of the object. I am using a ModelForm to create the form to create the object and the same to edit it later on. Now I want this owner field to be a choice field with the usernames of the current users. This is easily done by adding owner = forms.ModelChoiceField.... to the ModelForm. This works for creating new objects. Now when editing (going to the /{object_id}/edit link using a GET request) the object I call the ModelForm with the object instance. All fields are then nicely filled in except for my owner field, that just shows the default '-----' and you have to reselect it again. What I want is that that field is filled in with the value it currently is and I can then change it if I want based on the choices of current users. Just to preempt this answer: I do not want to make owner a ForeignKey relationship with user. My minified code: Model: class MyObjects(models.Model): owner = models.CharField(max_length=1024, blank=True) Form: class MyModelForm(ModelForm): owner = forms.ModelChoiceField(queryset = User.objects.all().only('username') def __init__(self, *args, **kwargs): super().__init__....... <bunch of code for … -
How to annotate Django models with new field based on existing fields?
I have Django models with a text field that is just a string. In views, I want to create a new field using annotate with the new fields being a comparison that compares the string of each of these objects text fields with another string, and ordering the queryset by that newly made comparison field. First I have this to get only objects that at least contain the other string: queryset = textObject.objects.filter(text_icontains=queryString) The next part is where I am confused. How can I access each objects text field from this queryset so that I can make a new field with annotate based on these comparisons? -
How display Average Ratings on several pages in Django
Am trying to display the Average ratings on other pages in Django, but it fails. Below its my code. models.py class ActionGame(models.Model): publication_status = models.CharField(max_length=20, choices=STATUS, default="Draft") cid =ShortUUIDField(help_text='Place for the Game ID ', unique=True, max_length=10, length=7, prefix='act',alphabet='abcdfgh12345' ) game_name = models.CharField(max_length=50, help_text='Enter The Name Of Game') game_image = models.ImageField(help_text='Enter The Game Picture Here',default='Action-images/default.jpg',upload_to='Action-images') RATING=[ (1,"★"), (2,"★★"), (3,"★★★"), (4,"★★★★"), (5,"★★★★★"), ] class ActionGameReview(models.Model): game_name =models.ForeignKey(ActionGame, on_delete=models.CASCADE, related_name='reviews') user =models.ForeignKey(User, on_delete=models.CASCADE) review =models.TextField(max_length=5000, blank=False) rating = models.IntegerField(default=1, choices=RATING) created_at=models.DateTimeField(auto_now_add=True) Views.py def action_description(request, cid): description=ActionGame.objects.get(cid=cid) #getting Average Review avg_rating=ActionGameReview.objects.filter(game_name=ActionGame.objects.get(cid=cid)).aggregate(rating=Avg('rating')) # ...... def action(request): action_pages = ActionGame.published.all() # ..... The issue is, l cant display the ratings average in the action view template yet on the action-description Works veryfine. how can l imprement the Average Rating on other pages, Anyone to help me. -
Django Templates: Render a dictionary object stored in a context object?
In Django I have a dictionary object like this: car = { 'color': 'red', 'doors': 4 } I would like to store this dictionary in an Django ORM Model class like so: class Things(models.Model): car = models.TextField() ... other fields My template is a view for Things. Is it possible to access values for car in the template a way such as this: Car color: {{ things_object.car.color }} Note, it is not a requirement to use TextField to save the car dictionary. -
Let Django access serial port in Lubuntu
So, I need my Django to access the serial port I'm correctly using it via pyserial package the issue is that, every time I boot the OS I got the error of Access denied. The only way to make it work is to grant access to the specific serial for everyone via sudo chmod 666 /dev/ttyUSB0 Is there a way to let Django access the serial anyway, instead of let eveyone access it with 666? -
Django race conditions between create() and get()
Since our last release a range of what seems can only DB race conditions have been happening.We use python 3.10, django-rq, Django 4 and Postgres. In one case: x = Model.objects.create() job.delay(x=x) In the job we call Model.objects.get(id=x.id) and it returns nothing. This is happening roughly 1 in 5 times from logs In another case we create the object, add it to a list then act on the list and again it works most of the time but we are getting one off 'matching query does not exist.' errors. I am completely stumped as to what I should do, I cant find many similar issues and can't recreate the issues in my test environment. My best assumption is too many writes to the DB so the transactions aren't being committed by the time the code tries to get the objects again. Any help/advice would be amazing Have gone through the code step by step to ensure the logic is sound Have tried recreating a 'busy' DB but have had no success there Have tried broken data etc but it all gets caught and our logs don't suggest anything like this either -
Enable adding a model field choices to Django admin dashboard and also be able to add or delete the choices
The normal way of interacting with a django model is by using admin.site.register(my_model) in admin.py file. If you want to enforce model's field validation you use the choices field option like this in models.py file. from django.db import models MY_CHOICES=[ ('A','choice 1'), ('B','choice 2'), ('C','choice 3'), .... ] class MY_MODEL(models.Model): ....Some other fields/columns.... options=models.CharField(max_length=2,choices=MY_CHOICES) How would I go about displaying the choices in the admin dashboard and also be able to add new types of choices? Also, is it possible to enforce validation by importing values from the database as field options? I tried having another model that will be a table containing the value and descriptions columns. class MY_CHOICES_MODEL(models.Model): value=models.CharField(max_length=2,..) descriptions=models.TextFeild(blank=False) Trying to pass this around to another models field options is the challenge -
Django model Attributes for Booking system
I'm itermediate in Django ... I work on Booking system with Django. I have two main models : 1.Service & 2.Reservation Service is like this: class AllService(models.Model): title = models.CharField(max_length=100) active = models.BooleanField(default=True) slug_service = models.SlugField(allow_unicode=True, max_length=100, unique=True, default='-') pic = models.ImageField(upload_to='service/') current_queue = models.PositiveSmallIntegerField(default=0) max_queue = models.PositiveSmallIntegerField(default=5) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='services') description = models.TextField() created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now=True) price = models.FloatField(null=True, blank=True, default=1000) service_off = models.FloatField(null=True, blank=True, validators=[MinValueValidator(0.0), MaxValueValidator(0.2)]) def full_queue(self): if self.current_limit > self.max_limit: self.is_available = False @property def remaining_queue(self): return (self.max_limit - self.current_limit) def adding_in_queue(self): k = self.current_limit k += 1 self.current_limit = k return self.current_limit def reset_queue(self): if datetime.now()==time(hour=0, minute=0, second=0.00): self.current_limit=0 and the Reservation is like this : class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reservations') service = models.ForeignKey(AllService, on_delete=models.CASCADE, related_name='reservation') pick_date = models.DateField() description = models.TextField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} {self.service}" class Meta: ordering = ['-created_at'] def clean(self): if self.pick_date < timezone.localdate(): raise ValidationError("day was passed") else: return super().clean() def adding_user_to_queue(self): AllService.adding_in_queue() what I try to do is : when someone choose a service in the Reservation model the "adding_user_to_queue" triger the "adding_in_queue()" method and add up the current_limit field by one, but it doesn't work! I see … -
Pytorch RuntimeError: mat1 & mat2 shapes cannot be multiplied(1x2 and 10000x100)
I am trying to build a spam classifier. However, when sending a POST request, I am getting this error. RuntimeError at /classify/ mat1 and mat2 shapes cannot be multiplied (1x2 and 10000x100) Yes, it's quite straightforward, but even when adjusting the variables, I still get the same result. How can I solve this issue? My model.py file: import nltk from nltk.stem import PorterStemmer import re import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from sklearn.feature_extraction.text import CountVectorizer from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('punkt') try: wordnet.ensure_loaded() except LookupError: nltk.download('wordnet') class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear1 = nn.Linear(10000, 100) self.linear2 = nn.Linear(100, 10) self.linear3 = nn.Linear(10, 2) def forward(self, x): x = torch.flatten(x) x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x def classify_spam(message): model = LogisticRegression() model.load_state_dict(torch.load('W:/SpamOrHamProject/SpamOrHamBack/api/AIModel/SpamClassification.pth')) model.eval() cv = CountVectorizer(max_features=10000) processed_message = preprocess_message(message) vectorized_message = cv.fit_transform([processed_message]).toarray() with torch.no_grad(): tensor_message = Variable(torch.from_numpy(vectorized_message)).float() output = model(tensor_message) _, predicted_label = torch.max(output, 0) return 'Spam' if predicted_label.item() == 1 else 'Not Spam' def preprocess_message(message): remove_non_alphabets = lambda x: re.sub(r'[^a-zA-Z]', ' ', x) tokenize = lambda x: word_tokenize(x) ps = PorterStemmer() stem = lambda w: [ps.stem(x) for …