I have this method on my views.py:
def contact_us(request):
form = ContactUsForm()
d = {'form': form}
if request.method == 'POST':
form = ContactUsForm(request.POST)
if form.is_valid():
Contact.objects.create(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
)
try:
send_mail(first_name,last_name,email,message,['kristian.koci#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
d['message'] = _('Thank You! We will contact you shortly')
else:
d['form'] = form
return render_to_response('profiles/contact_us.html', d,
context_instance=RequestContext(request))
This is the url:
http://beta.contratalos.com/profiles/contact_us/
I want to send that message to the recipient I've specified on sned_mail method.
But everytime I try it throws this error:
NameError: global name 'first_name' is not defined
File "apps/profiles/views.py", line 737, in contact_us
send_mail(first_name,last_name,email,message,['kristian.koci#gmail.com'])
Any ideas on what that could be?
Thanks in advance!
You are not declaring the variable first_name, last_name anywhere.
The following code will help you.
temp_contact=Contact.objects.create(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
)
temp_contact.save()
try:
send_mail(temp_contact.first_name,temp_contact.last_name,temp_contact.email,temp_contact.message, ['kristian.koci#gmail.com'])
except:
...
Edit:
The following code will help you send the right thing.
temp_contact=Contact.objects.create(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
)
temp_contact.save()
try:
email_subject = "Contact Registration - "+temp_contact.email
email_content = "Name:"+temp_contact.first_name+" "+temp_contact.last_name+"\nContent:"+temp_contact.message
send_mail(email_subject,email_content,temp_contact.email, ['kristian.koci#gmail.com'])
except:
...
Related
I have an Issue trying to Bind my PostForm with an Image Uploading Ability for a Post Made, However there is a functional Profile picture coding which accepts images and save the name to the data base and to avoid error, it adds uuid1 to the image name which is saved on the data base and the image itself is saved in the static folder, image section where it is called upon when needed, all part of the UserForm, but for the PostForm, the method is the same, but instead of a profile picture, it is a post image which should appear there and it keeps giving me interface error, however if the image is excluded, the Post is added to the Database successfully, please I need your help to know what is going wrong, Here is the Code:
#app.route('/add-post', methods=['GET', 'POST'])
def add_post():
form = PostForm()
if form.validate_on_submit():
if request.files['post_image']:
post_image = request.files['post_image']
post_filename = secure_filename(post_image.filename)
post_name = str(uuid.uuid1()) + "_" + post_filename
saver = request.files['post_image']
post_image = str(uuid.uuid1()) + "_" + post_filename
try:
db.session.commit()
saver.save(os.path.join(app.config['UPLOAD_FOLDER'], post_name))
except:
flash("Error! Looks Like There Was a Problem... Try Again!")
else:
db.session.commit()
poster = current_user.id
post = Posts(title=form.title.data, post_image=form.post_image.data, content=form.content.data, poster_id=poster, slug=form.slug.data)
form.title.data = ''
form.content.data = ''
form.slug.data = ''
form.post_image.data = ''
db.session.add(post)
db.session.commit()
flash("Blog Post Submitted Successfully !")
return render_template("add_post.html", form=form)
After weeks of trying and having errors, I finally got the hang of it... I will post the answer below:
#app.route('/add-post', methods=['GET', 'POST'])
def add_post():
form = PostForm()
if form.validate_on_submit():
poster = current_user.id
post = Posts(title=form.title.data, content=form.content.data, file=form.file.data, poster_id=poster, slug=form.slug.data)
if request.files['file']:
upload.file = request.files['file']
filename = secure_filename(upload.file.filename)
file_name = str(uuid.uuid1()) + "_" + filename
saver = request.files['file']
post.file = file_name
try:
db.session.add(post)
db.session.commit()
saver.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))
flash("User Updated Successfully !")
return render_template("add_post.html",
form=form)
except:
flash("Error! Looks Like There Was a Problem... Try Again!")
return render_template("add_post.html",
form=form)
else:
db.session.add(post)
db.session.commit()
flash("User Updated Successfully !")
return render_template("add_post.html",
form=form)
form.title.data = ''
form.content.data = ''
form.slug.data = ''
db.session.add(post)
db.session.commit()
return render_template("add_post.html",
form=form,
id = id or 1)
Here I am trying to redirect to another page if the form is submitted successfully but this code is not working properly .The code saves the form data sends the email , everything is fine but the problem is while redirecting to another page if the form succeed. The error I get is:
Django Version: 2.0.6
Exception Type: ValueError
Exception Value:
dictionary update sequence element #0 has length 0; 2 is required
context_processor.py
def volunteer_page2(request):
volunteer = Volunteer.objects.all().order_by('date')
if request.method == 'POST':
form = VForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = "{0} with email address {1} has sent you new message \n\n{2}".format(name, email, form.cleaned_data['message'])
form.save(commit = False)
try:
send_mail(name, message, 'appname <settings.EMAIL_HOST_USER>', ['myemail'])
except:
return HttpResponse('Invalid header found')
form.save()
messages.success(request, 'Success')
return redirect('volunteer_page')
else:
messages.error(request, "Sorry try again")
else:
form = VForm()
return {'volunteer': volunteer, 'form':form}
views.py
def about_page(request):
about = About.objects.all().order_by('date')
banner = Banner.objects.all()
testimonial = Testimonial.objects.order_by('-pk')[0:2]
nav = Nav.objects.all()
footer = Footer.objects.all()
latest_event2 = Events.objects.order_by('-pk')[0:2]
context = {
'about': about,
'testimonial': testimonial,
'footer':footer,
'banner': banner,
'nav': nav,
'latest_event2': latest_event2,
}
return render(request, 'myapp/about.html', context)
settings.py
'myapp.context_processor.volunteer_page2'
Django's context processor should always return dictionary. In your code you are returning HttpResponse also. This is problem.
I have a webpage where user chooses one object from a model. Based on the button clicked, certain actions are executed. One of the actions is by calling one of the views, and dislaying another webpage.
So, when user visits http://127.0.0.1:8000/clinic/manage, he sees the below form:
Code:
#login_required
def manage_clinics(request):
msg = ''
if request.method == 'POST':
clid = int(request.POST.get('clinics'))
print("POST details", request.POST)
if request.POST.get('createdoctor')=='Create Doctor':
clinicobj = Clinic.objects.get(clinicid=clid)
print("Creating Doctor for clinic:", clinicobj)
createdoctor(request, clinicobj.label)
else:
form = ChooseClinicMetaForm()
return render(request, 'clinic/manageclinics.html', {'form': form, 'msg': msg})
If he clicks on 'Create Doctor', the following view function is to be executed:
#login_required
def createdoctor(request, cliniclabel):
msg =''
cliniclink = '/clinic/'+cliniclabel+'/createdoctor'
cl = Clinic.objects.get(label=cliniclabel)
if request.method == 'POST':
print("POST details", request.POST)
form = DoctorMetaForm(request.POST)
if form.is_valid():
print("Form is valid.")
# form.save()
username = request.POST.get('username')
name = request.POST.get('name')
email = request.POST.get('email')
phone = request.POST.get('phone')
msg = SaveDoctortoSQLNew(request)
print(msg)
if 'Error:' not in msg:
doctorobj = doctor.objects.get(name=name, email=email, phone=phone, username=username)
clinicobj = Clinic.objects.get(label=cliniclabel)
permobj = ClinicPermissions(clinicid=clinicobj, doctorid=doctorobj, viewperms =1)
permobj.save()
msg = "Successfully created a doctor and assigned permissions"
else:
msg = "Invalid details."
print(msg)
else:
# cl = Clinic.objects.get(label=cliniclabel)
form = DoctorMetaForm()
return render(request, 'clinic/doctorprofile.html', {'form': form, 'rnd_num': randomnumber(), 'cliniclink': cliniclink, 'msg': msg, 'clinic':cl})
When this is executed, I get the following exception:
[14/Oct/2018 14:40:37] "GET /appointments/static/appointments/js/bootstrap.min.js.map HTTP/1.1" 404 1758
POST details <QueryDict: {'csrfmiddlewaretoken': ['3Jt28ToKqHiP6rGaTmbOOZH0yNRaU1TCOx427C6sV42VCbFrbrdJVlpzaSQiI3EK'], 'clinics': ['1'], 'createdoctor': ['Create Doctor']}>
Creating Doctor for clinic: Dr Joel's ENT Clinic
POST details <QueryDict: {'csrfmiddlewaretoken': ['3Jt28ToKqHiP6rGaTmbOOZH0yNRaU1TCOx427C6sV42VCbFrbrdJVlpzaSQiI3EK'], 'clinics': ['1'], 'createdoctor': ['Create Doctor']}>
Invalid details.
2018-10-14 14:40:40,928 django.request ERROR Internal Server Error: /clinic/manage
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 137, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view clinic.views.manage_clinics didn't return an HttpResponse object. It returned None instead.
So this is apparently because no HttpResponse object is returned. But doesnt the createdoctor function return just that? Or is python complaining about the return of the statement createdoctor(request, clinicobj.label)? Am I supposed to wrap this up in a HttpResponse?
It appears like you forgot to add return in manage_clinics
#login_required
def manage_clinics(request):
msg = ''
if request.method == 'POST':
clid = int(request.POST.get('clinics'))
print("POST details", request.POST)
if request.POST.get('createdoctor')=='Create Doctor':
clinicobj = Clinic.objects.get(clinicid=clid)
print("Creating Doctor for clinic:", clinicobj)
return createdoctor(request, clinicobj.label)
else:
form = ChooseClinicMetaForm()
return render(request, 'clinic/manageclinics.html', {'form': form, 'msg': msg})
First off, I know what the error means, I'm just confused on the configuration.
I'm getting an error of:
views.Registration didn't return an HttpResponse object
The issue is when I visit localhost/Register, I get the above error.
Q: If I want localhost/Register to show form from RegistrationForm() when it loads the register.html template within render() (at the bottom) when /Register is accessed. How do I do that? Do I need to create another view like /NewUser that I currently have specified? My thought was that render() was going to execute to show the template (with the form inside it) when viewing /Register
Code:
a view of:
def Registration(request):
RegForm = RegistrationForm(request.POST or None)
if request.method == 'POST':
if RegForm.is_valid():
clearUserName = RegForm.cleaned_data['userNm']
clearPass = RegForm.cleaned_data['userPass']
RegForm.save()
try:
return HttpResponseRedirect('/NewUser/?user=' + clearUserName)
except:
raise ValidationError('Invalid Request', code='300') ## [ TODO ]: add a custom error page here.
else:
RegForm = RegistrationForm()
return render(request, 'VA/reuse/register.html', {
'form': RegForm
})
You need to render something if the request is 'GET' instead of 'POST': ie.
def Registration(request):
RegForm = RegistrationForm(request.POST or None)
if request.method == 'POST':
if RegForm.is_valid():
clearUserName = RegForm.cleaned_data['userNm']
clearPass = RegForm.cleaned_data['userPass']
RegForm.save()
try:
return HttpResponseRedirect('/NewUser/?user=' + clearUserName)
except:
raise ValidationError('Invalid Request', code='300') ## [ TODO ]: add a custom error page here.
else:
RegForm = RegistrationForm()
return render(request, 'VA/reuse/register.html', {
'form': RegForm
})
else:
RegForm=RegistrationForm()
return render(request, 'template.html', {'formset': RegForm})
of course, you should change the context for your template, depending on whatever it is you need to render.
No, you should just move everything from the else onwards back one indentation level. Otherwise, nothing is returned if the request is not a POST.
def addbook(request):
if request.method == 'POST':
book_name =request.POST['book_name']
Book = Book.objects.get()
Book.save()
return render_to_response('book_detail.html', {'books': books},context_instance=RequestContext(request))
else:
return render_to_response('addbook.html',context_instance=RequestContext(request))
def book_detail(request):
return render(request, 'book_detail.html')
the above is my view.py i am getting this error"MultiValueDictKeyError at /addbook/"
please help me
That error means that 'book_name' isn't in your POST data.
If you want to handle that case, you can use book_name = request.POST.get('book_name'), which will default book_name to None if it isn't in the POST data.
If not, you need to make sure the form has an input called 'book_name'.