SMTPSenderRefused at /appointment - django-views

I'm trying to send emails with Django, sendmail, but for some reason, it's throwing this error, and showing that the problem is my email, i.e this ['abrarshahriar360#gmail.com'], line. It was working fine on development server, after I deployed it using heroku, everything is working fine, just when I'm trying to send an email, it's showing this. I have my two factor authentication turned off and less secure apps turned on. Still why is this error being SHown? Thanks in advance!
My views.py:
def appointment(request):
if request.method == "POST":
your_name = request.POST['your-name']
your_phone = request.POST['your-phone']
your_email = request.POST['your-email']
your_address = request.POST['your-address']
your_schedule = request.POST['your-schedule']
your_date = request.POST['your-date']
your_message = request.POST['your-message']
appointment = "Name: " + your_name + " " + "Phone: " + your_phone + " " + "Email: " + your_email + " " + "Address: " + your_address + " " + "Schedule: " + your_schedule + " " + "Appointment Date: " + your_date + " " + "Message: " + your_message
send_mail(
'Appointment request form ' + your_name,
appointment,
your_email,
['abrarshahriar360#gmail.com'],
)
return render(request, 'appointment.html', {
'your_name' : your_name,
'your_phone' : your_phone,
'your_email' : your_email,
'your_address' : your_address,
'your_schedule' : your_schedule,
'your_date' : your_date,
'your_message' : your_message
})
else:
return render(request, 'home.html', {})
My settings.py:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Email Settings
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'abrarshahriar360#gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('Email_PASS')
EMAIL_USE_TLS = True
django_heroku.settings(locals())

It actually was my problem. I passed the wrong context variables. So it was throwing that error

Related

Testing views in Django, post requests. When I query my Workspace.objects.all() it never exists

Whenever I query my Workspace.objects.all() it never exists in my tests despite working fine on the server.
def create_workspace(request, primary_key):
if request.method == 'POST':
messages.success(request, "New workspace was successfully created!")
form = Workspace_Form(request.POST)
if form.is_valid():
user = User.objects.get(id=primary_key)
workspace = Workspace()
workspace.user = user
workspace.name = form.cleaned_data.get('name')
workspace.description = form.cleaned_data.get('description')
workspace.save()
messages.success(request, "New workspace " + workspace.name + " was successfully created!")
return redirect('core:user_page', primary_key)
else:
messages.error(request, "Workspace must have a name!")
return redirect('core:user_page', primary_key)
class Test_Create_Workspace(TestCase):
def setUp(self):
self.user_page_url = reverse('user_page',kwargs={'primary_key':1})
self.user = User.objects.create(username='testuser')
self.user.set_password('12345Bunny')
self.user.save()
self.group = Group(name = 'customer')
self.group.save()
self.group.user_set.add(self.user)
self.group.save()
client = Client()
client.login(username='testuser', password='12345Bunny')
return super().setUp()
def tearDown(self) -> None:
self.user.delete()
return super().tearDown()
def test_can_create_valid_workspace(self):
self.workspace={
'name' : 'workspace name',
'description' : 'h',
}
response = self.client.post(reverse('core:create_workspace',kwargs={'primary_key':1}),self.workspace)
Workspace.objects.all().refresh_from_db()
messages = list(get_messages(response.wsgi_request))
self.assertEqual(len(messages), 1)
self.assertEqual(str(messages[0]), "New workspace " + self.workspace.name + " was successfully created!")
self.assertEqual(response.status_code,302)
self.assertTrue(Workspace.objects.count(), 1)

my stylesheet and images doesn't work with Jinja2 templates with parameters - Django

I successfully converted my website templates to Jinja2, everything works as it should, except in urls with parameters.
I have this is views.py file
path("profile/<id>", views.profile),
When the template loads in my browser the css and images dont load.
But when I remove the parameter and set id manually in the view function everything works. Am I doing anything wrong?
profile function in views
def profile(request, id):
mydb.connect()
sql = "SELECT * FROM account_data WHERE user_id ="+str(id)
mycursor.execute(sql)
myresult = mycursor.fetchone()
if myresult == None:
mydb.connect()
sql = "SELECT * FROM account_data WHERE roblox_id="+str(id)
mycursor.execute(sql)
myresult = mycursor.fetchone()
if myresult == None:
return render(request, 'rostats_app/incorrectdetails.html', {"errormessage":"ERROR 404", "redirection":"signup", "banner":banner})
# gets skill squares
if myresult[5] != "":
skills_count = 1
for i in myresult[5]:
if i == "⏎":
skills_count += 1
skills_boxes = 0
if (skills_count >= 0) and (skills_count <= 4):
skills_boxes = 4
elif (skills_count >= 5) and (skills_count <= 8):
skills_boxes = 8
skills = myresult[5]
skills = skills.split("⏎", 4)
skills_1 = []
for x in range(0, len(skills)):
skills_1.append(skills[x])
for num, x in enumerate(skills_1):
skills_1[num] = x.split(":")
else:
skills_boxes = 0
skills_1 = []
indicator = myresult[8]
if "user_id" in request.session:
state = "Sign Out"
if str(id) == str(request.session["user_id"]):
config_profile = True
profile_heading = "Your Profile"
indicator = ""
else:
config_profile = False
if myresult[1] != "":
profile_heading = str(myresult[1])+"'s Profile"
else:
profile_heading = str(myresult[10])+"'s Profile"
else:
if myresult[1] != "":
profile_heading = str(myresult[1])+"'s Profile"
else:
profile_heading = str(myresult[10])+"'s Profile"
config_profile = False
state = "Sign Up"
status=myresult[6]
return render(request, "rostats_app/profile.html", {"username":myresult[1], "avatarurl":myresult[3], "avatarurl2":myresult[9], "discriminator":myresult[2], "roblox_username":myresult[10], "skills_boxes":skills_boxes, "skills_1":skills_1, "config_profile":config_profile, "state":state, "profile_heading":profile_heading, "indicator":indicator, "status":status, "banner":banner})
this loads the css file
<link rel="stylesheet"type="text/css" href="static/styles.css">
I fixed it by putting a / before the images and the css. I think the problem is that it tried loading it from somewhere else when parameters where in use.
try this
path("profile/<int:id>", views.profile,name='profile'),

How to communicate between C++ and django channels?

Iam doing django project using django channels. In my project I need to integrate and communicate between C++ code. In between i have to send some values to C++.
I checked without django channels and it is working fine,Can any one help me out how can I implement below code in consumers.py of django channels.
proc = subprocess.Popen(["/home/dev/integrated_module/front-face-camera/rest_project/CameraApplication/MakoContinuousFrameGrabberConsoleApplication" + ' ' + team_name + ' ' + user_name + ' ' + media_path],shell=True,preexec_fn=os.setsid,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
I have found the answer using Syncconsumer with synchronous function
class CameraParallelAsync(SyncConsumer):
def websocket_connect(self,event):
print("connected",self.channel_name)
print('Data after delay')
self.channel_group_name = "task_single_snap"
self.send({
"type":"websocket.accept"
})
def websocket_receive(self,event):
print("receive",event)
channel_data = event.get('text',None)
user_name = self.scope['url_route']['kwargs']['user']
team_name = self.scope['url_route']['kwargs']['team']
media_path = settings.MEDIA_ROOT
channel_name = self.channel_name
if channel_data is not None:
if channel_data =='CAMERA_ON':
self.scope['session']['camera'] = True
print('Camera Enabled')
global proc
os.environ['LD_LIBRARY_PATH'] = "/usr/local/lib/Libraries"
import subprocess
proc = subprocess.Popen(["/home/dev/integrated_module/front-face-camera/rest_project/CameraApplication/MakoContinuousFrameGrabberConsoleApplication" + ' ' + team_name + ' ' + user_name + ' ' + media_path],shell=True,preexec_fn=os.setsid,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
self.send({
"type":"websocket.send",
"text":"Camera Enabled"
})
elif channel_data == 'CAMERA_OFF':
print('Camera disabled')
self.scope['session']['camera'] = False
import signal
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
elif channel_data == 'SINGLE_SNAP':
self.send({
"type":"websocket.send",
"text":"We are processing your request"
})
print('Single Snap')
task = tasks.camera_single_task.delay(user_name,team_name,media_path,channel_name)
print(task.status,'status')
elif channel_data == 'GROUP_SNAP':
print('Group Snap')
os.environ['LD_LIBRARY_PATH'] = "/usr/local/lib/Libraries"
import subprocess
proc = subprocess.Popen(["/home/dev/integrated_module/front-face-camera/rest_project/CameraApplication/MakoGroupFrameGrabberConsoleApplication" + ' ' + team_name + ' ' + user_name + ' ' + media_path],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print(proc.communicate())
self.send({
"type":"websocket.send",
"text":"Group snap Snaptured"
})
else:
print('No detection')
def websocket_disconnect(self,event):
print("disconnected",event)
# Receive message from room group
def task_message(self, event):
message = event['message']
print('hello')
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))

Convert CGI to Django framework

Can anyone help me on what approache should be used to convert a CGI script to Django Framework?
I will need to use HTTP Get method request from an HTML Form to obtain user inputs and inject them into a python script.
Here is a sample of CGI python script:
#!/usr/bin/python
import cgi, cgitb
from RTTexec import *
# from RTTexecCustom import *
from globals import *
form = cgi.FieldStorage()
print "Content-Type: text/html"
print ""
print "<html>"
print "<head>"
print "<title>RTT</title>"
print '<link rel="stylesheet" href="../jquery-ui-1.11.4.custom/jquery-ui.css">'
print "</head>"
print "<body>"
print '<div class="inside">'
print '<p>'
print "The user entered data are:<br>"
step = 0
try:
execTypeExtract = ''
execTypeExec = ''
try:
execTypeExtract = form["execTypeExtract"].value
except:
None
try:
execTypeExec = form["execTypeExec"].value
except:
None
try:
info = form["information"].value
except:
None
if execTypeExtract != '' and execTypeExec != '':
executionIncludes = execTypeExtract+'_'+execTypeExec
elif execTypeExtract != '':
executionIncludes = execTypeExtract
elif execTypeExec != '':
executionIncludes = execTypeExec
else:
step = 1
print "<b>execution Includes:</b> " + executionIncludes + "<br>"

Python class __str__

My work-out: This is an assignment
class Person(object):
def __init__(self, name):
self.name = name
def __str__(self):
if isinstance(person1, Lecturer):
return "Name: " + self.name + "\tOccupation: " + self.occupation
elif isinstance(person2, Student):
return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
class Lecturer(Person):
def Occupation(self, occupation):
self.occupation = occupation
class Student(Person):
def StudentNumber(self, studentNumber):
self.studentNumber = studentNumber
person1 = Lecturer("Elisha Nsemwa")
person2 = Student("Fabian Hamza")
person1.Occupation("Senior Lecturer")
person2.StudentNumber("HD5603")
print person1
print person2
My output:
Name: Elisha Nsemwa Occupation: Senior Lecturer
"assignment.py", line 26, in <module>
print person2
"assignment.py", line 7, in __str__
return "Name: " + self.name + "\tOccupation: " + self.occupation
AttributeError: 'Student' object has no attribute 'occupation'
person1 execute the if part, this is OK the output get printed, now my error is person2 execute the if not the elif; how can I correct this
In
def __str__(self):
if isinstance(person1, Lecturer):
return "Name: " + self.name + "\tOccupation: " + self.occupation
elif isinstance(person2, Student):
return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
you are testing person1 and person2, so isinstance(person1, Lecturer) is always true. What you want to know is the instance of self:
... def __str__(self):
... if isinstance(self, Lecturer):
... return "Name: " + self.name + "\tOccupation: " + self.occupation
... elif isinstance(self,Student):
... return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
...
...
>>> print person1
Name: Elisha Nsemwa Occupation: Senior Lecturer
>>> print person2
Name: Fabian Hamza Student Number: HD5603