I have changed my table definitions to use Reference Property. Now when I try to do an insert I get if value is not None and not value.has_key(): AttributeError: 'Query' object has no attribute 'has_key'
subject = self.request.get('subject')
content = self.request.get('content')
user = self.request.get('name')
name = User.all().filter('name =', user)
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content, user = name)
p.put()
This is my Post class
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
user = db.ReferenceProperty(User)
I am using Python 2.7. I have tried to follow the instruction from another posting regarding if value is not None and not value.has_key(): but those suggestions haven't worked for me.
Thanks everyone for your help.
I added and then set name to p.
for p in q.run():
print "name ", p.name
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content, name = p)
Related
I have the following function:
signature_request = client.send_signature_request_embedded_with_template(
client_id = self.CLIENT_ID,
template_id = self.template_id,
title = self.title,
subject = self.email_subject,
message = self.message,
signers = self.signers,
custom_fields = self.custom_fields
)
signature_id = signature_request.signatures[0].signature_id
I cannot for the life of me mock the signature_id value in my test. I know that I am properly mocking the correct target because I am successfully mocking another return value from this signature_request object. Any help would be highly appreciated!
I have tried the following:
send_request_mocked.return_value.signatures.return_value =
[PropertyMock(signature_id = 'signature_id')]
send_request_mocked.return_value.signatures.return_value =
[Mock(signature_id = 'signature_id')]
etc.
I making a email delivery WebApp, I have an Email Class with uploadcsvfile to upload the .csv contact file from the user's computer to server at location CONTACT_DIR, what I'm unable to figure out is how to get the saved contacts_some_char.csv name in my views.py, the purpouse of getting it's name is so that I can parse the email list and send email to them.
I have my model.py as follows :
class Email(models.Model):
fromemail = models.EmailField(blank = False, max_length = 254)
uploadcsvfile = models.FileField(upload_to = 'Contacts', blank = False)
subject = models.CharField(blank=False,max_length = 254)
bodyHeading = models.CharField(blank = False,max_length = 254)
bodytext = models.TextField(blank = False)
name = models.CharField(blank = False,max_length = 254)
Here is my views.py :
def index(request):
if request.method == 'POST':
email_form = EmailForm(request.POST, request.FILES)
if email_form.is_valid():
email_form.save(commit = True)
print(Email.uploadcsvfile)
contacts = Contacts()
#path = settings.CONTACT_DIR
f = open(settings.CONTACT_DIR+"/"+str(uploaded_file_name))
csv_f = csv.reader(f)
Emails = []
Names= []
L_Names = []
for x in csv_f:
Emails.append(x[0])
Names.append(x[1])
L_Names.append(x[2])
f.close()
contacts.ListOfEmails = json.dumps(Emails)
contacts.ListOfFirstNames = json.dumps(Names)
contacts.ListOfLastNames = json.dumps(L_Names)
contacts.save()
Here is forms.py for the same :
from django import forms
from dcsvreader.models import Email
class EmailForm(forms.ModelForm):
class Meta():
model = Email
fields = "__all__"
A.K.A How do i get uploaded_file_name in views.py, I'm reading in various QnA at S.O that this is related to FileDescriptor but can't find how exactly also, print(Email.uploadcsvfile) gives <django.db.models.fields.files.FileDescriptor object at 0x03F7DF90> as output.
request.FILES is a dictionary-like object containing all uploaded files and the uploadcsvfile is the key in which you are making a POST request. Hence, request.FILES['uploadcsvfile'] will hold the particular file as InMemoryUploadedFile and it has a variable .name which holds the filename
Try this,
file_name = request.FILES['uploadcsvfile'].name
Reference
uploadfile.name
request.FILES
I'm pretty new to django myself but it looks like here:
print(Email.uploadcsvfile)
You're trying to print a class attribute rather than an attribute of an instance.
Have you tried the following?
print(email_form.uploadcsvfile.name)
I am developing an API using Google App Engine in Python. I am having trouble sending a GET request to a particular url. I get the 'NoneType' object has no attribute to_dict error. The trouble comes in at out = client.to_dict() in the apiClient.py, which is routed to in main.py by
app.router.add(webapp2.Route(r'/api/client/<clientid:[0-9]+><:/?>', 'apiClient.Client'))
I do not understand why ndb.Key(db_defs.Client, int(kwargs['clientid'])).get() is returning None
apiClient.py:
import webapp2
from google.appengine.ext import ndb
import db_defs
import json
class Client(webapp2.RequestHandler):
#returns all or a specified client(s)
def get(self, **kwargs):
if 'application/json' not in self.request.accept:
self.response.status = 406
self.response.status_message = "Not acceptable: json required"
return
if 'clientid' in kwargs:
client = ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
out = client.to_dict()
self.response.write(json.dumps(out))
else:
q = db_defs.Client.query()
keys = q.fetch(keys_only=True)
results = { 'keys' : [x.id() for x in keys]}
self.response.write(json.dumps(results))
db_defs.py:
from google.appengine.ext import ndb
#http://stackoverflow.com/questions/10077300/one-to-many-example-in-ndb
class Model(ndb.Model):
def to_dict(self):
d = super(Model, self).to_dict()
d['key'] = self.key.id()
return d
class Pet(Model):
name = ndb.StringProperty(required=True)
type = ndb.StringProperty(choices=set(["cat", "dog"]))
breed = ndb.StringProperty(required=False)
weight = ndb.IntegerProperty(required=False)
spayed_or_neutered = ndb.BooleanProperty()
photo = ndb.BlobProperty()
owner = ndb.KeyProperty(kind='Client')
class Client(Model):
lname = ndb.StringProperty(required=True)
fname = ndb.StringProperty(required=False)
phone = ndb.StringProperty(required=False)
email = ndb.StringProperty(required=False)
staddr = ndb.StringProperty(required=False)
pets = ndb.KeyProperty(kind='Pet', repeated=True, required=False)
def to_dict(self):
d = super(Client, self).to_dict()
d['pets'] = [p.id() for m in d['pets']]
return d
EDIT:
When I do a GET request to http://localhost:8080/api/client/ I get a list of client ids:
{"keys": [4679521487814656, 4855443348258816, 5136918324969472,
5242471441235968, 5277655813324800, 5559130790035456,
5699868278390784, 5805421394657280, 6051711999279104,
6368371348078592, 6544293208522752, 6614661952700416,
6685030696878080]}
which I have verified are the same as those present in the GAE Datastore Viewer.
But when I do a GET request to http://localhost:8080/api/client/4679521487814656
I get the NoneType Error.
client is set to None, which is not an object with a to_dict() method.
client is None because the following expression returned None:
client = ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
e.g. there is no Client object with that key.
So I am trying to create a unique permalink each time that a person posts on my webpage and I want it to be relatively search engine friendly so I have made a little code to change the title to a good search engine title and it is working but then my handler cannot accept it. At least that is what I think is happening because the webpage just gives me a 404 error. The HTML works fine because when I redirect to a static page it all goes through. Here is the applicable code:
def post(self):
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content)
p.put()
id=str(p.key().id())
subject = str(subject)
subject = subject.replace(' ', '25fdsa67ggggsd5')
subject = ''.join(e for e in subject if e.isalnum())
subject = subject.replace('25fdsa67ggggsd5', '-')
subject = subject.lower()
url = '/blog/%s/%s' % (id, subject)
self.redirect('/blog/%s/%s' % (id, subject))
class PostPage(BlogHandler):
def get(self, post_id):
key = db.Key.from_path('PersonalPost', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.error(404)
return
self.render("permalink.html", post = post)
class PersonalPost(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
user_id = db.StringProperty(required = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
def blog_key(name = 'default'):
return db.Key.from_path('blogs', name)
app = webapp2.WSGIApplication([('/blog/([0-9]+)/([.*]+)', PostPage)]
And again it works when I just have it redirect to the main page and list them but not when I try to direct to the new SEO page.
UPDATE:
The test url I am using is setting
subject = "test-url"
id = "1234"
The app then directs me to www.url.com/blog/1234/test-url but it gives me a 404 error.
You define two groups in ('/blog/([0-9]+)/([.*]+) but your PostPage.get() only takes one.
Change it to def get(self, post_id, subject) or remove the second group ('/blog/([0-9]+)/[.*]+
I think you should have a look at the quotes on ur handler mapping, it seems inconsistent.
yours: app = webapp2.WSGIApplication([('/blog/([0-9]+)/([.*]+)', PostPage)]
try : app = webapp2.WSGIApplication(['/blog/([0-9]+)/([.*]+)', PostPage)]
I need to update a record in the datastore, but instead of updated record I get always a new record.
My model:
class PageModel(db.Model):
title = db.StringProperty()
content = db.TextProperty()
reference = db.SelfReferenceProperty()
user = db.UserProperty(auto_current_user = True)
created = db.DateTimeProperty(auto_now_add = True)
modified = db.DateTimeProperty(auto_now = True)
type = db.StringProperty()
template = db.StringProperty()
position = db.IntegerProperty()
hidden = db.BooleanProperty()
historical = db.BooleanProperty()
My handler:
class EditHandler(webapp.RequestHandler):
def post(self):
if self.request.path[6:] == '':
page_id = 8
else:
page_id = int(self.request.path[6:]) # path: /edit/35
#id = self.request.get('id')
CP = PageModel.get_by_id(int(page_id))
key = CP.key()
title = self.request.get('title')
content = self.request.get('content')
type = self.request.get('type')
hidden = self.request.get('hidden')
#position = self.request.get('type')
reference = PageModel.get_by_id(int(self.request.get('reference')))
template = self.request.get('template')
if ".htm" not in template:
template = "index.htm"
#if title == '' or content == '':
#doRender(self,'create_page.htm',{'error' : 'Please fill in all fields'} )
#return
#edited_page = PageModel(key=CP.key, title=title, content=content, type=type, reference=reference, template=template)
edited_page = PageModel()
edited_page.key = CP.key()
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()
There should be something wrong with edited_page.key = CP.key(), or what?!
Why are you created a new PageModel everytime? instead edit the one you got by id i.e. CP ? e.g.
edited_page = CP
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()