Ok, a project that a small team I am working on is new to django and developing a webapp, when all of a sudden we lost all ability to add a model object into the database. We are all at a complete loss. Below is where we are in debugging currently.
views.py
def postOp(request):
if request.method == 'POST':
operation = request.POST.get("operation","noop")
#Registered user operations
if request.user.is_authenticated():
username = request.session.get("member","Guest")
user = ToolUser.objects.get(name=username)
zipcode = user.location
.
.
#AddTool
if operation == "addTool":
toolName = request.POST.get("toolName","N/A")
toolDesc = request.POST.get("toolDesc","N/A")
print("In addtools")
user.submitTool(toolName, toolDesc)
print("SUBITTED")
return HttpResponseRedirect("tools")
model
def submitTool(self, Nname, Ndescription):
print("IN SUBMIT ")
t = Tool(name=Nname, owner=self.id, shed=self.id, description=Ndescription, currOwner=0, location=self.location)
print("tool made :", t.name, ", ", t.owner, ", ", t.shed, ", ", t.description, \
", ",t.currOwner ,", ", t.location)
t.save()
print("saving tool")
It appears that it gets all the way to the t.save(), then breaks. using a seperate tool to view the database, it is clearly not getting saved to the table. BUT with the following output to the terminal, it does appear to be creating this instance.
terminal output:
In addtools
IN SUBMIT
tool made : tooltest , 2 , 2 , description , 0 , 12345
EDIT: forgot to update this, found the problem, turns out one field was empty, and django refuses to save something that has empty fields.
So wait, you have a model function called saveTool() but you're calling user.savetool (which I presume is django.contrib.auth.user)? If you say that resolves, then fine.
It's probably better to just populate the object in the postOp() function and save it there. If saveTool() were indeed part of the model class you'd be instantiating a model object, and then calling a method to instantiate another function.
My point is that from a style perspective, the code is needlessly complex, or this requires more data to really work out what's happening there.
Related
So Im trying to follow users, but the problem is that it works on every user except the last one that I have in my to_follow.txt:
Chile_Temblores
Aguas_Antof
costaneranorte_
onemichile
Edelaysen
Chilquinta600
CGE_Clientes
Frontel_
EnelClientesCL
javi1597
The code that Im using is the following:
def createFriends(api):
accounts = open("to_follow.txt", "r")
friends = api.friends_ids()
print("friends:", friends)
follow = accounts().split('\n')
print (follow)
for account in follow:
if account not in follow:
api.destroy_friendship(account)
for account in follow:
if account not in friends:
print("account: ", account)
fuentes.append(account)
api.create_friendship(account)
print("friendship created")
print(fuentes)
accounts.close()
So when I print what is happening, it stops in javi1597 and it does not exit de execution, Where is the problem?
I think you should have used the variable "accounts" instead of using the file name "to_follow" as a method:
def createFriends(api):
accounts = open("to_follow.txt", "r")
friends = api.friends_ids()
print("friends:", friends)
print(accounts)
for account in accounts:
if account not in friends:
print("account: ", account)
fuentes.append(account)
api.create_friendship(account)
print("friendship created")
print(fuentes)
accounts.close()
Else I don't understand where the function to_follow() is coming from and why you don't use the created variable "accounts".
Edit: I refactored your code. You don't have to split the file but can directly iterate over the rows with "for in".
Edit 2: When you trying to add the last element "javi1597" it could be possible, that it also contains the "end of file" and it should be removed before you pass it into your API. Only an idea.
for i in xrange(1,NUM_USERS+1):
print i
private = RSA.generate(3072,Random.new().read)
public = private.publickey()
new_user = User(public_rsa=public.exportKey(), secret_rsa=private.exportKey())
new_user.save()
In the above loop, I have given the value of NUM_USERS=100 but the loop is iterating till 200 instead of 100. What might be the possible reason for this ?
EDIT:
I am so sorry guys, I accidentally figured out that the whole python method is being called twice, I don't know why though, so I will describe in detail. I am writing a django based server side, which has methods as following:
def index(request):
return HttpResponse("CREST Top Dir: " + PROJECT_ROOT)
def server_setup(request):
try:
process = subprocess.check_output(BACKEND+"mainbgw setup " + str(NUM_USERS), shell=True,\
stderr=subprocess.STDOUT)
for i in xrange(1,NUM_USERS+1):
print i
Now what happens is when I call the server_setup view sometimes it executes more than once. Similarly if I call index view sometimes server_setup is also called in simultaneously. So the problem is not with xrange but with method calling. What could be the reason for this problem ?
Check if NUM_USERS is 100.
for i in xrange(1,NUM_USERS+1):
print 'NUM_USERS:', NUM_USERS # check it
print i
private = RSA.generate(3072,Random.new().read)
public = private.publickey()
new_user = User(public_rsa=public.exportKey(), secret_rsa=private.exportKey())
new_user.save()
I have a website with these models:
class TrainingSession(models.Model):
user = models.ForeignKey(user)
active_exercise = models.ForeignKey(Exercise)
class Passage(models.Model):
text = models.TextField()
class Exercise(models.Model):
training_session = models.ForeignKey(TrainingSession)
passage = models.ForeignKey(Passage)
where a user is assigned a TrainingSession that generates exercises of passages.
The general idea of the website is to give users reading exercises to work on. But I want to generate new exercises with passages the users haven't read yet during their current session. So to that end, the TrainingSession class has this method:
# this passes
def generate_exercise(self):
passages = Passage.objects.exclude(exercise__trainingsession=self)
if not passages:
raise ObjectDoesNotExist()
passage = random.choice(passages)
new_exercise = Exercise.objects.create(training_session=self,
passage=passage)
self.active_exercise = new_exercise
So if I tried to generate an exercise before creating any passages, you'd expect an ObjectDoesNotExist to be raised. And that's exactly what happens in this test:
# this test passes
def test_no_passages(self):
Passage.objects.all().delete()
user = User.objects.create()
session = TrainingSession.objects.create(user=user)
with self.assertRaises(ObjectDoesNotExist):
session.generate_exercise()
And if I have one passage, and generate the exercise, it works:
# this test passes
def test_generate_one(self):
Passage.objects.all().delete()
user = User.objects.create()
session = TrainingSession.objects.create(user=user)
Passage.objects.create(passage_title='a', passage_text='b')
session.generate_exercise()
And if I have one passage, and try to generate two exercises in a row, it raises the exception, as I'd hoped:
# this test passes
def test_cant_generate_second(self):
Passage.objects.all().delete()
user = User.objects.create()
session = TrainingSession.objects.create(user=user)
Passage.objects.create(passage_title='a', passage_text='b')
session.generate_exercise()
with self.assertRaises(ObjectDoesNotExist):
session.generate_exercise()
But then if I have TWO passages, and try to generate THREE exercises, no error gets raised and this following test fails:
# never raises the exception and fails
def test_cant_generate_third(self):
Passage.objects.all().delete()
user = User.objects.create()
session = TrainingSession.objects.create(user=user)
Passage.objects.create(passage_title='a', passage_text='b')
Passage.objects.create(passage_title='c', passage_text='d')
session.generate_exercise()
session.generate_exercise()
with self.assertRaises(ObjectDoesNotExist):
session.generate_exercise()
And if I print out what should be the 'used' passages:
print 'used:', [ex.passage for ex in
Exercise.objects.filter(trainingsession=session)]
at different points in the last test, something weird happens. At first it's empty, when I haven't generated any exercises. After I generate the first exercise, it prints out an array with the passage attached to the first generated exercise. But when I generate a second exercise, it ONLY SHOWS THE NEWEST EXERCISES'S PASSAGE. So somehow,
Exercise.objects.filter(trainingsession=session)
is only finding the latest created exercise, and not all the exercises that I've created pointing to the given training session.
So my question is: might there be a reason why the line:
new_exercise = Exercise.objects.create(training_session=self,
passage=passage)
might cause this later query:
passages = Passage.objects.exclude(exercise__trainingsession=self)
to misbehave?
I already tried:
new_exercise.save() # --doesn't help
Or, if that question doesn't have an obvious answer, my follow up: can you see what I'm doing wrong?
Figured it out:
passages = Passage.objects.exclude(exercise__trainingsession=self)
should be
passages = Passage.objects.exclude(exercise__training_session=self)
Using
exercise__trainingsession
was following the reverse path from TrainingSession to Exercise through TrainingSession's active_exercise foreign key, so only the 'active' exercise was being excluded.
I am currently trying out python's web.py module by making a small form. I wrote one, and received input from the user and wrote them to a (mysql) database table. Every thing is fine, except for one issue. When I run the program and write something in one of the form's fields, it persists to the next time I want to write in that field. How can I reset the field after receiving the data?
this is my code:
import web
import MySQLdb
url=('/search', 'search_by_name')
db=web.database(dbn='mysql' ,db='std',user='root', pw='123456')
tmpl=web.template.render('templates/')
class search_by_name:
form=web.form.Form(
web.form.Textbox('username',vpass,web.form.notnull),
web.form.Button('search')
)
def GET(self):
return tmpl.page( self.form)
def POST(self):
form=self.form
if not form.validates():
return tmpl.page(form)
else:
name=form['username'].value
a=db.select('student', where="name=$name", vars=locals())
row=list(a)
if row:
col=row[0]
return tmpl.table(row,col)
else:
return tmpl.message("There isn't student with this name in list")
app=web.application (url,globals())
if __name__=='__main__':
app.run()
I have this datastore model
class Project(db.Model)
projectname = db.StringProperty()
projecturl = db.StringProperty()
class Task(db.Model)
project = db.ReferenceProperty(Project)
taskname= db.StringProperty()
taskdesc = db.StringProperty()
How do I edit the value of taskname ? say I have task1 and i want to change it to task1-project
oops sorry, Here is the formatted code:
taskkey = self.request.get("taskkey")
taskid = Task.get(taskkey)
query = db.GqlQuery("SELECt * FROM Task WHERE key =:taskid", taskid=taskid)
if query.count() > 0:
task = Task()
task.taskname = "task1-project"
task.put()
by the way, I get it now. I changed the task=Task() into task = query.get() and it worked.
Thanks for helping by the way.
Given an instance t of Task (e.g. from some get operation on the db) you can perform the alteration you want e.g. by t.taskname = t.taskname + '-project' (if what you want is to "append '-project' to whatever was there before). Eventually, you also probably need to .put t back into the store, of course (but if you make multiple changes you don't need to put it back after each and every change -- only when you're done changing it!-).
Probably the easiest way is to use the admin console. Locally it's:
http://localhost:8080/_ah/admin
and if you've uploaded it, it's the dashboard:
http://appengine.google.com/dashboard?&app_id=******
Here's a link: