Sentimental analysis - not able to rectify this error - python-2.7

sid=SentimentIntensityAnalyzer
def sentiment_pos(sentence):
snt =sid.polarity_scores(sentence)
return snt['pos']
def sentiment_neg(sentence):
snt = analyser.polarity_scores(sentence)
return snt['neg']
def sentiment_neu(sentence):
snt = analyser.polarity_scores(sentence)
return snt['neu']
def sentiment_com(sentence):
snt = analyser.polarity_scores(sentence)
return snt['compound']
data['positivity']= data['body_text'].apply(sentiment_pos)
giving error; polarity_scores() missing 1 required positional argument: 'text'

Related

Strange TyperError put() missing 1 required positional argument: 'path'

I've been trying to test my PUT method in the following APITestcase:
def test_story_delete(self):
c = APIRequestFactory
user = User.objects.get(username='test1')
payload = {'storyName': 'changetest'}
request = c.put(reverse('storyFunctions',args=[self.room.pk,self.story.pk]), format='json')
force_authenticate(request,user=user)
My URL:
path('room/<int:pk>/story/<int:idStory>/adm', APIHstory.as_view(),name='storyFunctions'),
And I'm keep receiving this error:
TypeError: put() missing 1 required positional argument: 'path'
I don't understand what is going on because i declared the path inside request. Can someone help me?
Edit: sharing the view that I'm testing
class APIstory(APIView):
permission_classes = [IsAuthenticated]
def put(self,request, pk, idStory):
data = self.request.data
pk = self.kwargs['pk']
id = self.kwargs['idStory']
name = data['storyName'].strip()
if name == "" or str.isspace(name) or len(name) < 4:
return Response({"error": "minimum of 4 words"}, status=400)
if PokerRoom.objects.filter(id=pk).exists():
session = PokerRoom.objects.filter(id=pk)
if session[0].status == 'Finished':
return Response({'error': 'Session already ended'}, status=400)
else:
session = PokerRoom(id=pk)
if Story.objects.filter(id=id, idRoom=session).exists():
if not Story.objects.filter(idRoom=session, storyName=name).exists():
for hist in Story.objects.filter(id=id, idRoom=session):
if hist.status == 'Pending':
if hist.storyName == name:
return Response({'error':'story with the same name'}, status=400)
hist.storyName = name
hist.save()
status = hist.status
body = {"id":id,"storyName":name,"status":status}
message_socket("STORY_UPDATE", pk, body)
return Response({'success': 'story {} edited, status is {}.'.format(hist.id,hist.status)})
else:
return Response({'error': 'story already ended'}, status= 400)
else:
return Response({'error': 'story with the same name'}, status= 400)
return Response({'error': 'session doesnt exists.'}, status=400)
else:
return Response({'error': 'session doesnt exists.'}, status=400)
Edit2: I was forgetting to put the body in my request, but now I'm getting the following error: TypeError: super(type, obj): obj must be an instance or subtype of type
Shouldn't you add the request body also in a put request?
Something like this?
request = c.put(reverse('storyFunctions', kwargs={'pk': self.room.pk, 'idStory': self.story.pk}), payload, format='json')
As per the docs

Cannot assign must be a "" instance

i'm working on my first django project and i got this error
(Cannot assign "'433245675'": "Lockers.locker_id" must be a "Renters" instance.)
anyone here can help me pleas.
the views:
def adding_renter(request):
form_data = forms.AddingRenter(request.POST or None)
msg = ''
if form_data.is_valid():
renters = models.Renters()
renters.renter_id = form_data.cleaned_data['renter_id']
renters.renter_name = form_data.cleaned_data['renter_name']
renters.renter_email = form_data.cleaned_data['renter_email']
renters.renter_phone_number = form_data.cleaned_data['renter_phone_number']
renters.renting_start_date = form_data.cleaned_data['renting_start_date']
renters.renting_end_date = form_data.cleaned_data['renting_end_date']
renters.save()
msg = 'Renter has been added successfully'
context = {
'form': form_data,
'msg': msg
}
return rend
er(request, 'addingrenter.html', context)
def adding_locker(request):
form_data = forms.AddingLocker(request.POST or None)
msg = ''
if form_data.is_valid():
lockers = models.Lockers()
lockers.locker_id = form_data.cleaned_data['locker_id']
lockers.locker_number = form_data.cleaned_data['locker_number']
lockers.locker_information = form_data.cleaned_data['locker_information']
lockers.locker_status = form_data.cleaned_data['locker_status']
lockers.locker_notes = form_data.cleaned_data['locker_notes']
lockers.save()
msg = 'Locker has been added successfully'
context = {
'form': form_data,
'msg': msg
}
return render(request, 'addinglocker.html', context)
I'm going to guess you have the field named as locker_id. If that's the case, the actual ID field is named locker_id_id. So try using:
lockers.locker_id_id = form_data.cleaned_data['locker_id']
Though your error makes it seem like your model is defined as:
class Renters(models.Model):
...
class Lockers(models.Model):
locker_id = models.ForeignKey(Renters)
Instead it should be:
class Renter(models.Model): # Models should be singular
...
class Locker(models.Model):
renter = models.ForeignKey(Renter)

Django get_total_topup() missing 1 required positional argument: 'request'

class IndexAjaxView(View):
def get(self, request):
param = request.GET.get('param')
if param == 'get_total_topup':
return self.get_total_topup()
return JSONResponse({}, status=404)
def get_total_topup(self, request):
return JSONResponse({
'value': 'Rp.{:,.0f},-'.format(
TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum']
)
})
somebody can help me ? I want to get data via ajax, but the response is 500 with message get_total_topup() missing 1 required positional argument: 'request'
Your call in return self.get_total_topup() has no arguments but your definition def get_total_topup(self, request) requires one. Try return self.get_total_topup(request).
class IndexAjaxView(View):
def get(self, request):
param = request.GET.get('param')
if param == 'get_total_topup':
return self.get_total_topup(request) # <--- just change this
return JSONResponse({}, status=404)
def get_total_topup(self, request):
return JSONResponse({
'value': 'Rp.{:,.0f},-'.format(
TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum']
)
})
You are missing one positional argument in the method call.
return self.get_total_topup()
Fix it to
return self.get_total_topup(request)

TypeError: 'str' object is not callable python3

def SaveRoles(request):
if 'user_name' in request.session:
if request.method == "POST":
user_roles = request.POST['user_roles']
user_permission_level = request.POST['user_permission_level']
user_role_code = request.POST['user_role_code']
code = user_roles(user_roles=user_roles, user_permission_level=user_permission_level, user_role_code=user_role_code)
print("qqqqqq", code)
try:
model_status = code.save()
except Exception as e:
print("exception occured", e)
return render(request, 'administrator/add_role.html', {'message': 'Oops some error occured'})
if model_status == None:
role = user_roles.objects.all()
return HttpResponseRedirect('http://'+request.get_host()+'/admin/role-list/',{'message': 'Role added successfully','code': code})
else:
return HttpResponseRedirect('http://'+request.get_host()+'/admin/role-list/')
else:
return HttpResponseRedirect('/admin/')
When I am running this function I got the
TypeError: 'str' object is not callable
I searched all my code and I don't even use the word str anywhere in my project
But I cant figure out the error
user_roles is a string because you are assigning the value of request.POST['user_roles']. You probably need to change.
user_roles = request.POST['user_roles']
to
user_roles_val = request.POST['user_roles']
Ex:
def SaveRoles(request):
if 'user_name' in request.session:
if request.method == "POST":
user_roles_val = request.POST['user_roles'] #Update
user_permission_level = request.POST['user_permission_level']
user_role_code = request.POST['user_role_code']
code = user_roles(user_roles=user_roles_val, user_permission_level=user_permission_level, user_role_code=user_role_code) #Update
print("qqqqqq", code)
try:
model_status = code.save()
except Exception as e:
print("exception occured", e)
return render(request, 'administrator/add_role.html', {'message': 'Oops some error occured'})
if model_status == None:
role = user_roles.objects.all()
return HttpResponseRedirect('http://'+request.get_host()+'/admin/role-list/',{'message': 'Role added successfully','code': code})
else:
return HttpResponseRedirect('http://'+request.get_host()+'/admin/role-list/')
else:
return HttpResponseRedirect('/admin/')

Flask login 'function' object has no attribute 'is_active'

I try to use flask login in may app:
My controller:
#app.route("/process_log", methods=['POST'])
def process_login():
filled_form = LoginForm(request.form)
if filled_form.validate():
phone = filled_form.phone.data
password = filled_form.password.data
if User.phone_exists(phone) and User.pass_match(phone, password):
user = User.get_by_phone(phone)
login_user(user.get_id)
return redirect(url_for("index"))
else:
return render_template("login.html", form = filled_form, error = u"Не верный логин или пароль")
else:
return render_template("home.html", form = filled_form)
and I have some class with defined functions which required for API of flask login
My User class:
from pymongo import MongoClient
from bson.objectid import ObjectId
class User():
client = MongoClient()
db = client['test']
col = db['user']
user_id = None
def __init__(self, dic):
self.dic = dic
def is_authenticated():
return True
def is_anonymous():
return False
def is_active():
return True
def get_id(self):
return unicode(str(self.user_id))
def save(self):
self.user_id = self.col.insert(self.dic)
print "Debug:" + str(self.user_id)
#staticmethod
def _get_col():
client = MongoClient()
db = client['test']
col = db['user']
return col
#staticmethod
def phone_exists(phone):
col = User._get_col()
if col.find_one({'phone': phone}) != None:
return True
else:
return False
#staticmethod
def pass_match(phone, password):
col = User._get_col()
if col.find_one({'phone': phone})['password'] == password:
return True
else:
return False
#staticmethod
def get(userid):
col = User._get_col()
return col.find_one({'_id':userid})
#staticmethod
def get_by_phone(phone):
col = User._get_col()
dic = col.find_one({'phone': phone})
print dic['password']
return User(dic)
As you see function is_active is defined(Note:I also tried to pass refference with self)
But I still have this error AttributeError: 'function' object has no attribute 'is_active'
I am sorry for too much code here, but it should be pretty straightforward.
Note: I am using mongodb for my project.
Please help me to find my error. Thank you too much
One more thing:
Should I provide login_user(....) with Id or with my user object?
You must sent to login_user User instance (not id), see: https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L576.
So next code must work:
user = User.get_by_phone(phone)
login_user(user)