Related
Below is my error:
AttributeError at /admin/r/31/3/
'NoneType' object has no attribute 'startswith'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/r/31/3/
Django Version: 3.2.13
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'startswith'
Exception Location: C:\github\project\venv\lib\site-packages\django\contrib\contenttypes\views.py, line 41, in shortcut
Python Executable: C:\github\project\venv\Scripts\python.exe
Python Version: 3.7.1
This occurs when I'm trying to access certain type of model via admin, since I cannot access it through the tag related to get_absolute_url function of the model. The template appears, but never let me access the get_absolute_url.
The thing is, there is another model in another app which is almost identical in views.py, urls.py and models.py but only difference is 'permission_required' decorator which I can't sure if it's outdated.
views.py of error model.
from django.urls import reverse_lazy
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.decorators import login_required, permission_required
from .models import *
def landing(request):
return render(
request,
'instructor/landing.html'
)
def paymentrequired(request):
return render(
request,
'instructor/paymentrequired.html'
)
def lecture_in_category(request, category_slug=None):
current_category = get_object_or_404(Category, slug=category_slug)
categories = Category.objects.all()
lectures = Lecture.objects.filter(category=current_category)
return render(request, 'instructor/lecture_list.html',
{'current_category': current_category, 'categories': categories, 'lectures': lectures})
class LectureDetail(DetailView):
model = Lecture
def lecture_detail(request, id):
lecture = get_object_or_404(Lecture, id=id)
return render(request, 'instructor/lecture_detail.html', {'lecture':lecture})
# Create your views here.
models.py of the error page
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
import os
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
meta_description = models.TextField(blank=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)
class Meta:
ordering = ['name']
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('instructor:lecture_in_category', args=[self.slug])
class Lecture(models.Model):
title = models.CharField(max_length=40)
description = models.CharField(max_length=200, blank=True)
video_key = models.CharField(max_length=20, blank=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)
video_upload = models.FileField(upload_to='instructor/files/%Y/%m/%d', blank=True)
head_image = models.ImageField(upload_to='instructor/images/%Y/%m/%d', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
available_display = models.BooleanField('Display', default=True)
author = models.CharField(max_length=40)
category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL)
class Meta:
ordering = ['-created_at']
index_together = [['id', 'slug']]
def __str__(self):
return self.title
def get_absolute_url(self):
reverse('instructor:lecture_detail', args=[self.id, self.slug])
# Create your models here.
urls.py of the error page
from django.urls import path
from . import views
from .views import *
app_name = 'instructor'
urlpatterns = [
path('', landing, name='landing'),
path('<slug:category_slug>/', lecture_in_category, name='lecture_list_category'),
path('<int:id>/<lecture_slug>/', LectureDetail.lecture_detail, name="lecture_detail"),
path('payment_required/', paymentrequired, name="paymentrequired"),
]
this is my database setting
DATABASES = {
'default': {
'ENGINE': os.environ.get("SQL_ENGINE", 'django.db.backends.sqlite3'),
'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')),
'USER': os.environ.get('SQL_USER', 'user'),
'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'),
'HOST': os.environ.get('SQL_HOST', 'localhost'),
'PORT': os.environ.get("SQL_PORT", '5432'),
}
}
This is the traceback.
Traceback (most recent call last):
File "C:\github\rhizomeedu\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\contrib\admin\sites.py", line 250, in wrapper
return self.admin_view(view, cacheable)(*args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\contrib\contenttypes\views.py", line 41, in shortcut
if absurl.startswith(('http://', 'https://', '//')):
AttributeError: 'NoneType' object has no attribute 'startswith'
With that model, the error doesn't appear so I once deleted the decorator but the result was same.
So I assume it's about settings.py ..?
Help me.
I am trying to access the Id of current logged in User. but i am getting the below error.
models.py of derived model
from django.db import models
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from accounts.models import CustomUser
# Create your models here.
class PostProblem(models.Model):
problem_type_choices = (
('c','Confidential'),
('sc','Semi-confidential'),
('p','Public')
)
problem_category_choices = (
('agriculture','Agriculture'),
('computer_science','Computer Science'),
('social_studies','Social Studies'),
('environment','Environmental Science'),
('mathematics','Mathematics'),
('engineering','Engineering'),
('physics','physics'),
('chemistry','chemistry'),
('other','Other')
)
author = models.ForeignKey("accounts.CustomUser", verbose_name= "Creater", default = CustomUser.get_username ,on_delete=models.CASCADE)
problem_title = models.CharField(max_length=200, verbose_name="Problem's title")
problem_type = models.CharField(choices=problem_type_choices,max_length=5, verbose_name='Confidentiality of the problem ')
problem_category = models.CharField(choices=problem_category_choices, max_length=50, verbose_name="Catrgory of the problem")
problem_brief = models.CharField(max_length=1000, verbose_name='Breif description of the problem ')
problem_description = models.TextField(verbose_name='Problem complete description ')
problem_reward = models.IntegerField(verbose_name='Prize money for providing the solution ')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now
self.save()
def __str__(self):
return self.problem_title
def get_absolute_url(self):
return reverse("problem_detail", kwargs={"pk": self.pk})
def approve_solutions(self):
return self.solutions.filter(approved_solutions = True)
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from problems.models import PostProblem, Solutions
from problems.forms import PostProblemForm, SolutionsForm
from django.views.generic import TemplateView, CreateView, DetailView, DeleteView, UpdateView, ListView
# Create your views here.
class PostProblemCreateView(CreateView, LoginRequiredMixin):
login_url = 'login/'
redirect_field_name = 'problems/problem_detail.html'
form_class = PostProblemForm
model = PostProblem
forms.py
from django import forms
from problems.models import PostProblem, Solutions
class PostProblemForm(forms.ModelForm):
class Meta:
model = PostProblem
fields = ("problem_title","problem_type","problem_category","problem_brief","problem_description","problem_reward")
widgets = {
'problem_title':forms.TextInput(attrs={'class':'textinputclass'}),
'problem_type': forms.TextInput(attrs={'class':'choice_input'}),
'problem_category':forms.TextInput(attrs={'class':'choice_input'}),
'problem_brief': forms.Textarea(attrs={'class':'editable medium-editor-textarea post_brief'}),
'problem_description': forms.Textarea(attrs={'class':'editable medium-editor-textarea post_complete'}),
'problem_reward': forms.TextInput(attrs={'class':'textinputclass'})
}
model.py of base model
from django.db import models
from django.contrib import auth
from django.urls import reverse
# Create your models here.
# for custom user
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, User
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser, PermissionsMixin):
'''Model representation for user'''
user_type_choices = (
('ps','Problem Solver'),
('pp','Problem Provider')
)
account_type_choices = (
('o','Organization'),
('i','Individual')
)
user_type = models.CharField(max_length=5, choices=user_type_choices, default='pp', verbose_name="Who you are? ")
account_type = models.CharField(max_length=5, choices= account_type_choices, default='o', verbose_name="Account Type ")
email = models.EmailField(max_length=50, unique=True, blank=False, verbose_name="Your Email ")
is_active = models.BooleanField(default=True) # anyone who signs up for thsi application is by default an active user
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False) # the person who has highest level of control over database
# need to specify manager class for this user
objects = CustomUserManager()
# we are not placing password field here because the password field will always be required
REQUIRED_FIELDS = ['user_type', 'account_type']
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
I searched the web for answers but they have mentioned only about accessing current user id in function based views. How can I resolve this kind of error? I am new to Django.
Trying a django project from the documentations.
This is my Models.py I am trying to make a simple employee goals management system. I have also used DRF and serializers, integrated swagger for only doing 'GET' of the models below. I have removed (commented out) all ForeignKey and ManyToMany Fields yet, when I add modify the goal or project I get this error. I cant seem to solve this, please help.
class Department(models.Model):
department_name = models.CharField(max_length=200)
department_location = models.CharField(max_length=200)
department_region = models.CharField(max_length=200)
department_site = models.CharField(max_length=200)
department_job_titles = models.CharField(max_length=200)
def __str__(self):
return self.department_name
class Employee(models.Model):
#department_name = models.ManyToManyField(Department)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email_id = models.CharField(max_length=100)
#employee_id = models.IntegerField()
supervisor_name = models.CharField(max_length=100)
designation = models.CharField(max_length=100)
doj = models.DateTimeField('date joined')
def __str__(self):
return self.first_name
class Objectives(models.Model):
objective_name = models.CharField(max_length=200)
#employee = models.ManyToManyField(Employee)
def __str__(self):
return self.objective_name
class Project(models.Model):
#employee = models.ManyToManyField(Employee)
project_name = models.CharField(max_length=200)
def __str__(self):
return self.project_name
class Goals(models.Model):
goal_id = models.IntegerField()
goal_name = models.CharField(max_length=200)
#department = models.ManyToManyField(Department)
role = models.CharField(max_length=200)
#objective_id = models.ManyToManyField(Objectives)
goal_start = models.DateTimeField('date goal added')
goal_end = models.DateTimeField('date goal ends')
#employee = models.ManyToManyField(Employee)
def __str__(self):
return self.goal_name
This is my views.py
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Employee
from .models import Goals
from .models import Objectives
from .models import Department
from .models import Project
from .serializers import EmployeeSerializer
from .serializers import ProjectSerializer
from .serializers import GoalsSerializer
from .serializers import ObjectivesSerializer
from .serializers import DepartmentSerializer
from django.http import HttpResponse
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='UpYourGame API')
#just a view if someone hits the index
def index(request):
return HttpResponse("Hello and Welcome to UpyourGame")
# this will be the URL /employee/
class Employee(APIView):
def get(self, request):
employee = Employee.objects.all()
serializer = EmployeeSerializer(employee, many=True)
return Response(serializer.data)
class Project(APIView):
def get(self, request):
project = Project.objects.all()
serializer = ProjectSerializer(project, many=True)
return Response(serializer.data)
class Goals(APIView):
def get(self, request):
goals = Goals.objects.all()
serializer = GoalsSerializer(goals, many=True)
return Response(serializer.data)
class Objectives(APIView):
def get(self, request):
objectives = Objectives.objects.all()
serializer = ObjectivesSerializer(objectives, many=True)
return Response(serializer.data)
#class Company(APIView):
# def get(self, request):
# company = Company.objects.all()
# serializer = CompanySerializer(company, many=False)
# return Response(serializer.data)
class Department(APIView):
def get(self, request):
department = Department.objects.all()
serializer = DepartmentSerializer(Department, many=True)
return Response(serializer.data)
This is myproject/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from enterprise import views
urlpatterns = [
url(r'^$', views.schema_view, name='schema_view'),
url(r'^enterprise/', include('enterprise.urls')),
url(r'^admin/', admin.site.urls),
url(r'^employee/', views.Employee.as_view()),
url(r'^goals/', views.Goals.as_view()),
url(r'^department/', views.Department.as_view()),
url(r'^department/', views.Department.as_view()),
url(r'^objectives/', views.Objectives.as_view()),
url(r'^project/', views.Project.as_view()),
]
This is my serializers.py
from rest_framework import serializers
from .models import Employee
from .models import Goals
from .models import Objectives
from .models import Department
from .models import Project
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'
#class EmployeeDetailsSerializer(serializers.ModelSerializer):
# class Meta:
# model = EmployeeDetails
# fields = '__all__'
class ObjectivesSerializer(serializers.ModelSerializer):
class Meta:
model = Objectives
fields = '__all__'
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'
#class CompanySerializer(serializers.ModelSerializer):
# class Meta:
# model = Company
# fields = '__all__'
class GoalsSerializer(serializers.ModelSerializer):
class Meta:
model = Goals
fields = '__all__'
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
The SQLlite DB was corrupt due to too many migrations, it can happen. I deleted SQLlite and all my migrations, I retried migrate, makemigrate and sqlmigrate, it resolved the issue.
If you run into a similar issue in a dev environment please try the following
1. Delete all your migrations in the migrations folder
2. Delete db.sqlite3
3. Run python manage.py migrate
4. Run python manage.py makemigrations
5. Run python manage.py sqlmigrate appname 0001
This will fix this issue.
I've been trying to use webapp2 to store user data in session.
I tried to store the Key of the parent object in session data:
self.session['client'] = client.key
But I keep getting a:
TypeError: Key('Client', 6401356696911872) is not JSON serializable
How should I store an entity key in a session?
My code fairly simple:
import os
import urllib
import logging
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
from webapp2_extras import sessions
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
# dispatch the request
webapp2.RequestHandler.dispatch(self)
finally:
# save all sessions
import pdb; pdb.set_trace()
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
# Returns a session using the default cookie key.
return self.session_store.get_session()
JINJA_ENVIRONMENT = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
DEFAULT_LEADBOOK_NAME = 'whatsmyname'
def leadbook_key(leadbook_name=DEFAULT_LEADBOOK_NAME):
"""Constructs a Datastore key for a LeadBook entity with leadbook_name."""
return ndb.Key('LeadBook', leadbook_name)
class Client(ndb.Model):
email = ndb.StringProperty()
name = ndb.StringProperty(indexed=True)
street1 = ndb.StringProperty()
street2 = ndb.StringProperty()
city = ndb.StringProperty()
zipcode = ndb.IntegerProperty()
phone = ndb.StringProperty()
signup = ndb.DateTimeProperty(auto_now_add=True)
# this just creates a Client to use
if not ( Client.query( Client.name == "Bryan Wheelock").get()):
logging.info("create Admin")
client = Client(
email = "bryan#mail.com",
name = "Bryan Wheelock",
street1 = "555 Main St",
street2 = "unit 1",
city = "Atlanta",
zipcode = 99999,
phone = "(888)555-1212"
).put()
class Customer(ndb.Model):
client = ndb.KeyProperty(kind=Client)
email = ndb.StringProperty(indexed=True)
name = ndb.StringProperty(indexed=True)
street1 = ndb.StringProperty()
street2 = ndb.StringProperty()
city = ndb.StringProperty()
zipcode = ndb.IntegerProperty()
phone = ndb.StringProperty()
signup = ndb.DateTimeProperty(auto_now_add=True)
class MainPage(BaseHandler):
def get(self):
leadbook_name = self.request.get('leadbook_name',
DEFAULT_LEADBOOK_NAME)
# This should be the Client record that shows the info of the owner of the local clinic
# the question is how do I get the site to show the correct Client?
client = Client.query( Client.name == "Bryan Wheelock").get()
self.session['client'] = client.key
template_values = {
'client': client,
'leadbook_name': urllib.quote_plus(leadbook_name),
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
class LeadBook(webapp2.RequestHandler):
def post(self):
leadbook_name = self.request.get('leadbook_name',
DEFAULT_LEADBOOK_NAME)
client = self.session.get('client')
cl = Client.query(client.key )
customer = Customer( client = cl.key)
customer.name = self.request.get('id_name')
customer.street = self.request.get('id_street')
customer.phone = self.request.get('id_phone')
customer.zip = self.request.get('id_zip')
import pdb; pdb.set_trace()
# How can I see the number of Customers before and after save?
customer.put()
query_params = {'leadbook_name': leadbook_name}
self.redirect('/?' + urllib.urlencode(query_params))
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'my-super-secret-key',
}
application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', LeadBook),
], config = config,
debug=True)
Traceback (most recent call last):
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/Users/Bryan/work/GoogleAppEngine/dermalfillersecrets/main.py", line 22, in dispatch
self.session_store.save_sessions(self.response)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 420, in save_sessions
session.save_session(response)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 205, in save_session
response, self.name, dict(self.session), **self.session_args)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 423, in save_secure_cookie
value = self.serializer.serialize(name, value)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/securecookie.py", line 47, in serialize
value = self._encode(value)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/securecookie.py", line 92, in _encode
return json.b64encode(value)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/json.py", line 84, in b64encode
return base64.b64encode(encode(value, *args, **kwargs))
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/json.py", line 55, in encode
return json.dumps(value, *args, **kwargs).replace("</", "<\\/")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Key('Client', 6401356696911872) is not JSON serializable
Use a urlsafe version of the key:
https://cloud.google.com/appengine/docs/python/ndb/entities#retrieving_entities
self.session['client'] = client.key.urlsafe()
On retrieval, use
client = ndb.Key(urlsafe=self.session['client']).get()
Within the GAE I'm getting an error telling me:
TypeError: get_default_tile() takes exactly 1 argument (2 given)
As you can see the code from my main py file get_default_tile() is being passed only one argument which is name:
default_tile = self.get_default_tile(name)
The full code follows:
import jinja2 # html template libary
import os
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
import urllib
import urllib2
import webapp2
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Default_tiles(db.Model):
name = db.StringProperty()
image = db.BlobProperty(default=None)
class MainPage(webapp2.RequestHandler):
def get(self):
# this just prints out the url which the user enters into input
image_name = self.request.get('image_name')
template_values = {
'image_name': image_name,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
class Upload(webapp2.RequestHandler):
def post(self):
# get information from form post upload
image_url = self.request.get('image_url')
image_name = self.request.get('image_name')
# create database entry for uploaded image
default_tile = Default_tiles()
default_tile.name = image_name
default_tile.image = db.Blob(urlfetch.Fetch(image_url).content)
default_tile.put()
self.redirect('/?' + urllib.urlencode({'image_name': image_name}))
class Get_default_tile(webapp2.RequestHandler):
def get(self):
name = self.request.get('image_name')
default_tile = self.get_default_tile(name)
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(default_tile.image)
def get_default_tile(name):
result = db.GqlQuery("SELECT * FROM Default_tiles WHERE name = :1 LIMIT 1", name).fetch(1)
if (len(result) > 0):
return result[0]
else:
return None
app = webapp2.WSGIApplication([('/', MainPage),
('/upload', Upload),
('/default_tile_img', Get_default_tile)],
debug=True)
Any help would be appreciated.
get_default_tile(): is a member method of class Get_default_tile so you need to define it like this:
def get_default_tile(self, name):
Or if you want it to be a static method:
#staticmethod
def get_default_tile(name):
ok, i getting too that erro but the code following:
class myclassname( webapp2.RequestHandler ):
def get(self):
self.response.write('hola')
i solved with =
class myclassname( webapp2.RequestHandler ):
def get(self, **name**):
self.response.write('hola')