python flask mini-application global name not defined - python-2.7

I keep getting the error NameError: global name 'NameForm' is not defined
Here is my views.py
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from app import forms
app = Flask(__name__)
bootstrap = Bootstrap(app)
#app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)
if __name__ == '__main__':
app.run(debug=True)
And here is my forms.py
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
class NameForm(Form):
"""docstring for ClassName"""
name = StringField('Your name please', validators=[Required()])
submit = SubmitField('Submit')
Any ideas on what i might be doing wrong???

Related

flask_uploads Can Not Find Destination For Images

What I'm basically trying to do is use flask_uploads to find the path for an uploaded photo. I'm getting 'RuntimeError: no destination for set images' whenever I run the code. I've been over about 10 different tutorials and have gone over the code about 50 times. Please, for my sanity, help me out.
Here's my code
from colorthief import ColorThief
import matplotlib.pyplot as plt
from flask_uploads import configure_uploads, IMAGES, UploadSet
from flask import Flask, render_template, redirect, url_for, request
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, FileField
import os
class InsertPic(FlaskForm):
image = FileField('Select Your Picture')
URL = 'D:\Python Porfolio\Colors\static\images'
app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
app.config['UPLOADED_PHOTOS_DEST'] = 'static/images'
Bootstrap(app)
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
#app.route('/', methods=['GET', 'POST'])
def index():
form = InsertPic()
if form.validate_on_submit():
filename = images.save(form.image.data)
file_url = images.url(filename)
ct = ColorThief(f"{file_url}")
colors = ct.get_palette(color_count=11)
plt.imshow([[colors[a] for a in range(10)]])
plt.axis('off')
plt.savefig("output.jpg", bbox_inches='tight', pad_inches=0)
# Convet to HEX Values
separate_colors = []
for color in colors:
a = f"#{color[0]:02x}{color[1]:02x}{color[0]:02x}"
separate_colors.append(a)
return render_template('colors.html', colors=separate_colors)
return render_template('index.html', form=form)
if __name__ == "__main__":
app.run(debug=True)
Here's my Traceback info:
File "D:\prjects\pythonProject3\main.py", line 23, in <module>
configure_uploads(app, images)
File "D:\prjects\pythonProject3\venv\lib\site-packages\flask_uploads\flask_uploads.py", line 122, in configure_uploads
config = config_for_set(uset, app, defaults)
File "D:\prjects\pythonProject3\venv\lib\site-packages\flask_uploads\flask_uploads.py", line 84, in config_for_set
raise RuntimeError("no destination for set %s" % uset.name)
RuntimeError: no destination for set images

How to have scrapy spider run on flask app form submit?

I'm setting up a flask app that will allow me to input a string and it will pass that string argument to my spider to webscrape a page. I'm having difficulty getting the spider to run on the press of a form submit(integrating scrapy&flask).
I've looked at the following code snippet solutions to no avail:
Run Scrapy from Flask,
Running Scrapy spiders in a Celery task,
Scrapy and celery `update_state`
It definitely appears that there are different ways to complete the task. However - each of the code snippets above does not appear to be working.
routes.py
from flask import render_template, flash, redirect, url_for, session, jsonify
from flask import request
from flask_login import login_required
from flask_login import logout_user
from app import app, db
from app.forms import LoginForm
from flask_login import current_user, login_user
from app.models import User
from werkzeug.urls import url_parse
from app.forms import RegistrationForm, SearchForm
#from app.tasks import scrape_async_job
import pprint
import requests
import json
#app.route('/')
#app.route('/index', methods=['GET','POST'])
#login_required
def index():
jobvisuals = [
{
'Job': 'Example',
'Desc': 'This job requires a degree...',
'link': 'fakelink',
'salary': '10$/hr',
'applied': 'Boolean',
'interview': 'Boolean'}]
params = {
'spider_name': 'Indeedspider',
'start_requests': True
}
response = requests.get('http://localhost:9080/crawl.json', params).json()
data = response
pprint.pprint(data)
form = SearchForm()
if request.method == 'GET':
return render_template('index.html', title='home', jobvisuals=jobvisuals, form=form, search=session.get('search',''))
job_find = request.form['search']
session['search'] = job_find
if form.validate_on_submit():
print('Working on this feature :D')
flash('Searching for job {}').format(form.search.data)
return render_template('index.html', title='Home', jobvisuals=jobvisuals, form=form)
spider
import scrapy
class IndeedSpider(scrapy.Spider):
name = 'indeedspider'
allowed_domains = ['indeed.com']
def __init__(self, job='', **kwargs):
self.start_url('http://www.indeed.com/jobs?q={job}&l=San+Marcos%2C+CA')
super().__init__(**kwargs)
def parse(self, response):
for item in response.xpath("//div[contains(#class,'jobsearch-SerpJobCard unifiedRow row result clickcard')]").getall():
yield {
'title': item.xpath("//div[contains(#class,'title')]/text()").get(default='None'),
'desc': item.xpath("//div[contains(#class,'summary')]/text()").get(default='None'),
'link': item.xpath("//div[contains(#class,'title')]/#href").get(default='None'),
'location': item.xpath("//span[contains(#class,'location')]/text()").get(default='None'),
'salary': item.xpath("//div[contains(#class,'salarySnippet')]/text()").get(default='None')
}
Expected:
I type in a input box the job, job gets passed to spider on submit, spider scrapes indeed.com and pulls the first page only and returns that data on the index page.
Actual:
Unsure of where to start.
Can anyone point me in the right direction?

mailgun and flask forms

I keep getting the following error when I run my code:
TypeError: 'Response' object is not callable
Here is my code...
from flask import Flask, render_template, flash
import os
import requests
import forms
app = Flask(__name__)
app.secret_key = 'jfdsjajfjds'
mg_key = os.environ['MAILGUN_API_KEY']
#app.route("/", methods=('GET', 'POST'))
def landing():
form = forms.OptinForm()
if form.validate_on_submit():
return requests.post(
"https://api.mailgun.net/v3/lists/test_list#sandbox.mailgun.org/members",
auth=('api', 'mg_key'),
data={'subscribed': True,
'address': form.email.data,
'name': form.first_name.data})
flash("Thanks! Check your email.")
return render_template('landing.html', form=form)
if __name__ == "__main__":
app.run()
I figured out the problem. I was calling my API key variable as a string. fixed it by changing 'mg_key' to mg_key

global name 'csrf' is not defined in Django 1.10

NameError at /todos/accounts/register/
global name 'csrf' is not defined
Request Method: GET
Request URL: http://localhost:8000/todos/accounts/register/
Django Version: 1.10.5
Exception Type: NameError
Exception Value:
global name 'csrf' is not defined
Exception Location: /home/rahul/Desktop/apps/todolist/todos/views.py in register, line 37
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
Error in views.py :
from django.shortcuts import render
from django.http import HttpResponse
from .models import Todo
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm
#from django.core.context_processors import csrf
def index(request):
todos = Todo.objects.all()[:10]
context = {
'todos' : todos
}
return render(request, 'index.html', context)
def details(request, id):
todo = Todo.objects.get(id=id)
context = {
'todo' : todo
}
return render(request, 'details.html', context)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register/complete')
else:
form = UserCreationForm()
token = {}
token.update(csrf(request))
token['form'] = form
return render_to_response('registration/registration_form.html', token)
def registration_complete(request):
return render_to_response('registration/registration_complete.html')
Currently my code is showing global name 'csrf' is not defined. To overcome this error, If I uncomment from django.core.context_processors import csrf, than it shows context_processors module not found. Please help.
Thanks in advance.
Django built-in template context processors were moved from package django.core to django.template. So you should change your import as
from django.template.context_processors import csrf

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.