Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - TypeError - save() unexpected argument 'force_insert'
I have a Django app which works fine locally but I sent it to a Heroku server using postgres, everything loads fine from the database but if I try to register a new user with the following view: def register(request, *args, **kwargs): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save(*args, **kwargs) username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('core:index') else: form = UserRegisterForm() return render(request, 'registration/register.html', {'form': form}) I get this error: Django - TypeError - save() got an unexpected keyword argument 'force_insert' I read in a similar post about using *args and **kwargs within the view but that didn't make a difference, or, I didn't implement it correctly? -
Unable to mail with abc@mydomain email using python
import smtplib fromAddr='my_domain_emailid' toAddr='user@gmail.com' text= "This is a test of sending email from within Python." server = smtplib.SMTP('smtp.gmail.com' , 587) server.ehlo() server.sendmail(fromAddr, toAddr, text) server.quit() I am trying to send a mail with abc@mydomain email using above code in python but getting the below error Traceback (most recent call last): File "C:/Users/Mr.Mg/Documents/Python/Pratice/input.py", line 9, in <module> server.sendmail(fromAddr, toAddr, text) File "C:\Users\Mr.Mg\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 871, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError q34sm7754386pja.22 - gsmtp', 'welcome@quotesclub.in') -
Why do we use nginx as a front to django applications instead of directly exposing them?
I have always used nginx as a front to django applications but recently I've been working with java webservices at work. And I've noticed that we expose raw java services and don't use any proxy server such as nginx or apache. So why do we need to do it for django applications? -
Django and ajax request: ValueError: Cannot assign must be a instance
I'm trying to integrate in my django modal an ajax call to modify directly the value of my data. In other words I have the following views.py class UpdateCrudUser(View): def get(self, request): id1 = request.GET.get('id', None) conto1 = request.GET.get('conto', None) obj = Materiale.objects.get(id=id1) obj.conto = conto1 obj.save() element = { 'id':obj.id, 'conto':obj.conto} data = { 'element': element} return JsonResponse(data) After that I have build before my table as following: {% for element in elements %} <tr id="element-{{element.id}}"> <td class="elementConto userData" name="conto">{{element.conto}}</td> </tr> {% endfor %} ... And after that the modal: <form id="updateUser"> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="conto">Conto</label> <input class="form-control" id="form-conto" name="formConto"/> Finally the script with the ajax call: function editUser(id) { if (id) { tr_id = $("#element-" + id); conto = $(tr_id).find(".elementConto").text(); $('#form-id').val(id); $('#form-conto').val(conto); } } $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val(); var contoInput = $('input[name="formConto"]').val(); if (contoInput && tipologiaInput ) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': idInput, 'conto': contoInput, }, dataType: 'json', success: function (data) { if (data.element) { updateToUserTabel(data.element); } } }); } else { alert("Vediamo se funziona."); } $('form#updateUser').trigger("reset"); $('#myModal').modal('hide'); return false; }); But If I try to modify using the modal my data, … -
How to access nested dictionary in python. how do i access total_cases
how do i access the total_cases, death in python {"status":200,"type":"stack","data":{"2020-05-29":{"total_cases":1212,"deaths":6,"recovered":206,"critical":1000,"tested":0,"death_ratio":0.0049504950495049506,"recovery_ratio":0.16996699669966997},"2020-05-28":{"total_cases":1042,"deaths":5,"recovered":187,"critical":0,"tested":162730,"death_ratio":0.0047984644913627635,"recovery_ratio":0.17946257197696738}}} -
Django on Linux Server is not recognizing changes in views.py
So, I was trying to deploy my django webapp using an ubuntu linux server from linode and I noticed that the views.py file was not working as expected So rather than correct the mistake on my terminal using nano, I opened the copy of the application on my local machine and edited the views.py file using VS Code. Then, I scp'ed the views.py file to my server. I deleted the previous views.py file on my server and moved the new, edited views.py in its place Now, that I run my server Django will not notice the change at all. I even edited some print statements I had in the non-edited part of the file and it wont even see that. It still keeps on operating as it the old views.py file still existed. Any ideas what could be causing this? Thanks A lot for your help! -
Page not found (404) , error in django logout function
When i click on 'logout' link in home page(html page) ,i get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login1/logout Using the URLconf defined in webapp.urls, Django tried these URL patterns, in this order: admin/ Home/ [name='Home'] login/ [name='login'] Signup/ [name='Signup'] login1/ [name='login1'] logout/ [name='logout'] The current path, login1/logout, didn't match any of these. i don't understand why it can't find 'logout' function in views.py file...... This is Home.html <body> <center> <h1 style="color:white">Welcome to my web page</h1> <a href= 'logout' target="_blank">LogOut</a> </center> </body> This is urls.py: from django.contrib import admin from django.urls import path from application import views urlpatterns = [ path('admin/', admin.site.urls), path('Home/', views.Home , name = "Home"), path('login/', views.login,name = 'login'), path('Signup/', views.Signup , name = 'Signup'), path('login1/',views.login1,name='login1'), path('logout/',views.logout,name='logout'), ] This is views.py: from django.contrib.auth.models import User from django.shortcuts import render, redirect def login(request): return render(request, 'login.html') def login1(request): if request.method == "POST": uname = request.POST['username'] pwd = request.POST['pass'] user = auth.authenticate(username=uname, password=pwd) if user is not None: auth.login(request, user) return render(request, 'Home.html') else: return render(request, 'login.html', {'error': 'invalid credential details'}) else: return render(request, 'Signup.html') def logout(request): auth.logout(request) # logout is predefined return redirect('/login/') kindly provide solution asap. -
DetailView Django dont work error page not found
[urls.py ][1] [models.py][2] [main urls.py][3] When I click on the article I get error How can I fix it? [1]: https://i.stack.imgur.com/QI7YI.png [2]: https://i.stack.imgur.com/peBWG.png [3]: https://i.stack.imgur.com/JM5TN.png [4]: https://i.stack.imgur.com/FDGTM.png -
Django how to get input element in crispy field in modal
I have the following modal: <div class="modal-body"> <label for="conto">Conto</label> <input class="form-control" id="form-conto" name="formConto"/> </div> And that field is given by the following models: class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) Now, I want to use {{form.conto|as_crispy_field}} in my modal holding the structure of the modal form, or rather: for="conto" id="form-conto" and name="formConto". It is possible? -
Authenticate in Swagger - Django Rest Framework
I'm trying to use Swagger with DRF and it's not working as expected somehow. This is the swagger_view function I'm using: def get_swagger_my_view(title=None, url=None, patterns=None, urlconf=None): """ Returns schema view which renders Swagger/OpenAPI. """ from rest_framework.views import APIView class SwaggerSchemaView(APIView): # _ignore_model_permissions = True # permission_classes = [AllowAny] permission_classes = [IsAuthenticated] exclude_from_schema = True renderer_classes = [ CoreJSONRenderer, renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): generator = SchemaGenerator( title=title, url=url, patterns=patterns, urlconf=urlconf ) schema = generator.get_schema(request=request) if not schema: raise exceptions.ValidationError( 'The schema generator did not return a schema Document' ) return Response(schema) return SwaggerSchemaView.as_view() And my idea was login into /admin/ (in my case dashboard) and redirecting to swagger Here are my SWAGGER_SETTINGS SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, 'LOGIN_URL': '/dashboard/login/' } And when I go to the Swagger URL, I see this here: Which is great. Then, when I click on Session Login I go to the /dashboard/login with /dashboard/login/?next=/docs/, which looks great to me. But after login, I return to the same view as in the image. And when I click on Session login again, it logs into the /admin/ (in my case dashboard), which means it sees I'm … -
Error "TypeError: FirstForm() missing 1 required positional argument: 'request'"
Good day! When working views.py constantly you get this kind of error: TypeError: FirstForm() missing 1 required positional argument: 'request' Views.py def FirstForm(request): if request.method == 'GET': form = FirstForm() else: form = FirstForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] date = form.cleaned_data['date'] number = form.cleaned_data['number'] try: send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['daribian@list.ru']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'index.html', {'form': form}) def successView(request): return HttpResponse('Success!') Сan you tell me what the problem is? -
Django: Update create new record instead of updating
I try to inlineformset nested using FormView. Below the entity relationship diagram: Projet 1---* ProjetUtilisateur *---1 Utilisateur 1 | * Application But I don't understand why it create new record instead of updating my object. I have read about similar problems and all deals with instance missing but I do pass my form the instance. What's wrong with my logic? forms.py NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, #Utilisateur, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, ) class UtilisateurProjetUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs) # print('kwargs',self.request) # print('projet',self.request['projet']) # print('utilisateur',self.request['utilisateur']) PROJETS = Projet.objects.all() UTILISATEURS = Utilisateur.objects.all() self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet'])) self.fields["uti_ide"] = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select, initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur'])) class Meta: model = UtilisateurProjet fields = ('pro_ide','uti_ide',) views.py class UtilisateurUpdateView(FormView): template_name = 'project/utilisateurprojet_form.html' form_class = UtilisateurProjetUpdateForm def get_form_kwargs(self): kwargs = super(UtilisateurUpdateView, self).get_form_kwargs() kwargs['request'] = dict(utilisateur = self.kwargs['pk'], projet = self.kwargs['projet']) # kwargs['request'] = self.request # print('projet',self.kwargs['projet']) # print('utilisateur',self.kwargs['pk']) # print('kwargs',kwargs) return kwargs def get_context_data(self, **kwargs): data = super(UtilisateurUpdateView,self).get_context_data(**kwargs) # print('projet',self.kwargs['projet']) # print('utilisateur',self.kwargs['pk']) instance = UtilisateurProjet.objects.get(pro_ide=self.kwargs['projet'],uti_ide=self.kwargs['pk']) data['projet'] = Projet.objects.get(pro_ide=self.kwargs['projet']) data['utilisateur_app'] … -
Set dynamic ForeignKey with a method or function which reference the model itself
I have the following model with a default field which is a ForeignKey to the model itself. This ForeignKey default value is set by a function/method which makes a query to the model itself based in a dictionary which is independent of the model. Basically I want to set this field as a reference to previous created objects of that model which are assigned by the method set_default_content class SeoTag(models.Model): def set_default_content(tag_name, attr): return SeoTag.objects.get(tag_name = tag_names[tag_name][attr]) tag_name = models.CharField(max_length=50) default = models.ForeignKey('self', related_name="dep_tags", default = set_default_content(tag_name, 'default_tag_name')) content = models.CharField(max_length=1000, default = set_default_content(tag_name, 'default_text')) This throws this exception: NameError: name 'SeoTag' is not defined I thought defining the set_default_content method as a @classmethod would help but the method cannot still be executed because the class is not defined: TypeError: 'classmethod' object is not callable. How could I fix this? -
Axios doesn't work (return 401 error) with Django REST API
I use React + Django REST API and I got an error from the server with code 401 when I send any request from Axios (GET, POST..) whatever the view (Authentication, getting users...). But with Postman that's work fine, and when I replace Axios by fetch request, that's works, and directly in my browser, that's work too. React : componentDidMount() { axios.get("/api_tct/product/") .then((data) => { this.setState({ products: data }) }) } On my docker server : Unauthorized: /api_tct/product/ Do you have any idea? Thank you very much :) -
Django filter request result
I have two models Player and Game class Player(models.Model): userId = models.CharField(max_length = 150, primary_key=True) username = models.CharField(max_length = 250) email = models.CharField(max_length = 150) playedGames = models.IntegerField() class Game(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) date = models.DateTimeField() award = models.IntegerField() And request that returns winners list. wins = Player.objects.annotate( max_award=Max('game__award') ).filter( game__award=F('max_award') ).annotate( date=F('game__date') award=F('game__award') ).values( 'userId', 'date', 'award' ).order_by('-max_award') But there is one bug. If player have 2 or more of the same max Awards with different dates, then in result we get the same number of records (one for each date). For example: Alex, 75, 2020-05-29 Alex, 75, 2020-04-23 Richard, 68, 2020-05-27 But I'd like to get list, like this: Alex, 75, 2020-05-29 Richard, 68, 2020-05-27 How can I get just one record for each user with his max award (with last date)? -
Channels: why message is send at the end of processing
why using sync function get_channel_layer().send(), message is send at the end of processing def external_send(channel_name, data): channel_layer = get_channel_layer() send_sync = async_to_sync(channel_layer.send) send_sync( channel_name, { "type": "send_json", "message": {"datetime": datetime.datetime.now().isoformat(), **data}, }, ) using self.send() in consumer work as expected here is my consumer class for testing purpose: class TestConsumer(JsonWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive_json(self, content, **kwargs): logger.debug(f"RECEIVE {content}") self.send_json( { "id": 1, "text": "Before sleep: self.send_json", "datetime": datetime.datetime.now().isoformat(), } ) external_send( self.channel_name, {"id": 2, "text": "Before sleep external_send"} ) sleep(10) # Simuleting long processing self.send_json( { "id": 3, "text": "After sleep: self.send_json", "datetime": datetime.datetime.now().isoformat(), } ) super().receive_json(content, **kwargs) logger.debug("END") At frontend I'm receiving order {id: 1, text: "Before sleep: self.send_json", datetime: "2020-05-29T14:30:58.226545"} {id: 3, text: "After sleep: self.send_json", datetime: "2020-05-29T14:31:03.244865"} {id: 2, text: "Before sleep external_send", datetime: "2020-05-29T14:30:58.230164"} -
how can i ntegrate an AI model with .net? [closed]
i'm curently trying to integrate an AI model developed with python to a website which is developped with .net in the backend and angular in the frontend how can i connect the model with the backend ? it is possible to use django in this case? -
Limiting a query by a greater number returns different results
I have this query obj = Model.objects.filter(created_at__gte=start_date, status=[3,4]) \ .annotate(some_return=Case( \ When(some_status_id=4, then=Value(0)), \ default=F('field') * (1 + (F('other_field') / 100)), \ output_field=FloatField())) \ .values('id') \ .annotate( \ avg_variable=ExpressionWrapper(Avg('some_field'), output_field=FloatField()), \ other_var=Count('id') \ ) \ .filter(other_var__gte=10, avg_variable__gt=0) \ .order_by('-avg_variable')[:10] then, I subquery: subquery = OtherModel.objects.filter(id__in=Subquery(obj.values('id'))) .values('user__id').filter(times_posted__gte=10, timeframe_id=3)[:10] which returns result that is correctly sorted from the obj query above (avg_variable) When I increase the LIMIT keyword to 100 ([:100]) the results are sorted differently which should be wrong. It's good until around the :20 sort but everything above that is differently sorted. I can not figure why for the life of me. So: why are the results sorted differently depending on the LIMIT? Using POSTGRES -
Why models aren't loaded yet error show when using embedded models?
I'm trying to connect my django app with mongoDB, I have been using djongo for that. When I create a simple model with no embedded documents the migrations runs perfect. but when I try to create a embedded model document in my model the "models aren't loaded yet error show when running python manage.py makemigrations. I would like to know first why this error appears and why it happens when I use embedded models. Python Code: Project Tree ➜ reports tree . ├── db.sqlite3 ├── manage.py ├── rep │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── models.cpython-36.pyc │ ├── tests.py │ └── views.py └── reports ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── settings.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── wsgi.cpython-36.pyc ├── settings.py ├── urls.py └── wsgi.py 5 directories, 19 files rep/models.py from djongo import models from django import forms class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ('name', 'tagline') class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() class Meta: abstract = True class AuthorForm(forms.ModelForm): … -
Translate SQL query into a well made QuerySet
I have a raw queryset that i want to translate in QuerySet. But i always ends up with error. Here is the raw query : q = Table1.objects.raw( '''SELECT base_table1.id, base_table1.name, base_table1.n_id, count(base_table2.id) as 'count', max(base_table2.timestamp) as 'latest' FROM base_table1 INNER JOIN base_table3 on base_table3.table1_id = base_table1.id INNER JOIN base_table2 on base_table2.table3_id = base_table3.id GROUP by base_table1.id''' Note : here i don't need the base_table1.id, but it was required for the rawQuerySet Great thanks in advance for your answers. -
Django how to assign posts to user
I need to assign posts to user in Django. I created user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE) and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file : def formularz(request): form = DodajForm(request.POST) if form.is_valid(): ogloszenie = form.save(commit=False) ogloszenie.user = request.user ogloszenie.save() return redirect('atrakcje:after') else: ogloszenie = DodajForm() context = { 'form': form,} return render(request, 'formularz.html', context) Can i please know how to resolve it? -
how to add foriegnkey object and connnect it a post object through a single endpoint in Django rest Framework
models.py class PostAdvertisment(models.Model): # post=models.ForeignKey(Post,on_delete=models.CASCADE,null=True,blank=True) created_at=models.DateTimeField(auto_now_add=True) title=models.CharField(max_length=255,null=True,blank=True) url=models.URLField(null=True,blank=True) advertizing_content= models.TextField(null =True ,blank=True) def __str__(self): return f'{self.title}' class Post(models.Model): # created_at=models.DateTimeField(efault=datetime.now, blank=True) created_at=models.DateTimeField(auto_now_add=True) author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post") title=models.CharField(max_length=128,null=True,blank=True) rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True) # rating=models.IntegerField(null=True,blank=True) content=models.TextField(null=True,blank=True) review=models.CharField(max_length=250,null=True,blank=True) url=models.URLField(null=True,blank=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters") tags = TaggableManager(blank=True) comments=models.ManyToManyField('Comment',blank=True,related_name="comments_post") anonymous = models.BooleanField(default=False, blank=True) fake = models.BooleanField(default=False, blank=True) genuine = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_genuines") spam = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_spames") advertisement=models.ForeignKey(PostAdvertisment,on_delete=models.CASCADE,null=True,blank=True) def __str__(self): return f'{self.content}' def get_absolute_url(self): return reverse('post:post_detail' , kwargs={'post_id':Post.id}) so here is my serializers.py class PostSerializer(TaggitSerializer,serializers.ModelSerializer): tags = TagListSerializerField() author = serializers.StringRelatedField(read_only=True) comments = CommentSerializer(many=True, required=False, read_only=True) # title = serializers.CharField() advertisement = PostAdvertisementSerializer() # advertisement = serializers.SlugRelatedField( # queryset=PostAdvertisment.objects.all(), # slug_field='advertisement' # ) # category_name = serializers.CharField(source='advertisement.title') class Meta: model = Post fields = ('id','title','rate','author','content','review','url','tags', 'fake','comments', 'created_at', 'anonymous','advertisement') # def create(self, validated_data): # tag = validated_data.pop('advertisement') # tag_instance, created =PostAdvertisment.objects.get_or_create(title=tag) # article_instance = Post.objects.create(**validated_data, advertisement=tag_instance) # return article_instance # def create(self, validated_data): # serializer = self.get_serializer(data=self.request.data) # advertisment = self.request.data.pop('advertisement') # company_instance = PostAdvertisment.objects.filter(id=advertisment).first() # if not serializer.is_valid(): # print(serializer.errors) # data = serializer.validated_data # serializer.save(PostAdvertisment=company_instance) # headers = self.get_success_headers(serializer.data) # return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def create(self,validated_data): advertisement=validated_data.pop('advertisement') post= Post.objects.create(**validated_data) for advertise in advertisement: PostAdvertisment.object.create(**advertise) return post so the commented part of the code is something which I've Tried differnt … -
Upload a file in admin and then download from the website Django
****I am trying to create a website, where customer can upload a file in an Admin section, and after any person can download this file from the website. Preferably any files like pdf, exe, doc (is it possible?) I am able to upload a file in Admin and it shows it on the website. It downloads the file with a correct name (saved in media) but shows a failure , file missing.strong text So far I have : setting.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class TEACHING(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) excercise = models.FileField(upload_to="files/", default='default value') def __str__(self): return self.title views.py def teaching(request): context = { 'teaches' : TEACHING.objects.all()} return render(request, 'blog/teaching.html', context) urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) teaching.html {% for teach in teaches %} <a href="{{ teach.excercise }}" download>Download</a>{% endfor %}** -
"bash: django-admin: command not found" after running django-admin
I had similar problems with pip that was fixed with "python3 -m" but now after install Django I want to make a new project. When I try to run "django-admin startproject ..." I get "bash: django-admin: command not found". I don't know if I should mention it but, this is in a virtualenv. -
Run the python script on reactjs button and display the output
My frontend is on reactjs and I need to pass the user input in text box and the python script should be run on this input when the button is clicked. The output from the script should be sent back to frontend. Here is my frontend code sample: Reactjs File:-App.js <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <TextField label="Comment" multiline rows="4" fullWidth defaultValue="Add the comment you want to analyse" variant="outlined" style={{ margin: 20 }} /> <Button style={{ margin: 20 }} variant="contained" color="primary"> Analyse </Button> Python script: comment.py review = "User comments here " review_vector = vectorizer.transform([review]) # vectorizing print(classifier_linear.predict(review_vector))