Error with rendering webapp2 - google-app-engine

Good personal day. I have a problem I can not solve.
It happens that in an app I am creating have 3 files: main, config and home.html
The config file is used to grab the User data and adds them to a dictionary. If the User does not exist in the datastore, he adds.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api.app_identity import get_default_version_hostname
from google.appengine.ext import ndb
url = get_default_version_hostname()
# BANCO DE DADOS PARA SALVAR OS USUARIOS
class Usuarios(ndb.Model):
usuario = ndb.StringProperty()
email = ndb.StringProperty()
openID = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
tipo = ndb.StringProperty()
#classmethod
def get_email(cls, email):
return cls.query(cls.email == email)
########### FUNÇÃO QUE CHAMA O LOGIN ########
def Redir():
from google.appengine.api import users
user = users.get_current_user()
if users.is_current_user_admin():
redir = 'http://' + url + '/admin'
else:
redir = None
return redir
def Geral():
from google.appengine.api import users
user = users.get_current_user()
providers = {
'Google' : 'https://www.google.com/accounts/o8/id',
'Yahoo' : 'yahoo.com',
}
rt = {
'titulo' : 'BETA HCBravin',
'version' : '14.11.10',
'url' : 'http://' + url,
}
# O USUARIO ESTA LOGADO?
if user:
# O USUARIO E UM ADMINISTRADOR?
if users.is_current_user_admin():
dtipo = 'Admin'
else:
dtipo = 'Aluno'
# O USUARIO EXISTE NO BANCO DE DADOS?
quser = Usuarios.get_email(user.email())
buser = quser.get()
if not buser:
dbuser = Usuarios(usuario = user.nickname(), email = user.email(), openID = user.user_id(), tipo = dtipo)
dbuser.put()
if buser:
if buser.tipo == 'Professor':
dtipo = 'Professor'
else:
dtipo = 'Aluno'
rt.update({
'usuario': user.nickname(),
'email': user.email(),
'openID': user.user_id(),
'logout_url': users.create_logout_url('/'),
'user_tipo': dtipo,
})
else: # let user choose authenticator
#login_url = {'usuario': None, 'logout_url': None}
login_url = {}
for name, uri in providers.items():
login_url[name] = users.create_login_url(dest_url = ('/usuario') ,federated_identity=uri)
rt.update(login_url)
return rt
########## ############
The main file is the main file of my app that renders the home.html
import os
import webapp2
import sys
from config import *
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
Geral = Geral()
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(template.render('home.html', Geral))
app = webapp2.WSGIApplication([
('/', MainHandler),
], debug=True)
The home.html only has a value that is to get the variable {{ email }} and print it (that's not all, logical. Bad am using the simplest approach)
The problem:
When I login with a User it perfectly shows email. But if I make out and User mute rather than appearing email "new" keeps popping up the old email.
This remains even if I refresh the page.

Code outside of your handler's methods only runs when an instance starts up, not once-per-request.
So your call Geral = Geral() isn't being repeated for visitors after the first one.
You should move that line inside your get method (and probably change the name on the left-hand-side to not be the same as the function-name!)

Related

AbstractBaseUser.get_username() missing 1 required positional argument: 'self' | Error while accessing current user's username

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.

Identify the custom user model in REST_FRAMEWORK settings Django

I'm new in Django rest_framework. I'm using a custom user model and djoser as my authentication system. I want to use my custom user model in the djoser register view and I don't know how to identify that in the rest_framework settings?
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSIONS_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
),
}
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, phone, password=None):
if not email:
raise ValueError("Users must have an email address")
if not username:
raise ValueError("Users must have an username")
if not phone:
raise ValueError("Users must have a phone number")
user = self.model(
email=self.normalize_email(email),
username=username,
phone=phone
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email, username, phone, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
phone=phone,
password=password
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email",max_length=60, unique=True)
username = models.CharField(max_length=60,unique=True)
phone = models.CharField(max_length=60,unique=True)
date_joined = models.DateTimeField(verbose_name="date joined",auto_now_add=True)
last_login = models.DateTimeField(verbose_name="last login",auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
first_name = models.CharField(max_length=60,null=True)
last_name = models.CharField(max_length=60,null=True)
wilaya = models.CharField(max_length=60,null=True)
city = models.CharField(max_length=60,null=True)
address = models.CharField(max_length=200,null=True)
store_coordinates = models.CharField(max_length=60,null=True)
documents1 = models.CharField(max_length=60,null=True)
documents2 = models.CharField(max_length=60,null=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','phone']
objects = MyAccountManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
What should I add to use my custom user model in djoser register view?
You're doing almost everything right, but you need to tell Django in the settings what user model it should use.
In models.py use something like this
from django.contrib.auth.models import AbstractUser
from .managers import UserManager
class User(AbstractUser):
# Add whatever fields you want
# Use your custom manager
objects = UserManager()
In settings.py
# Tell Django what user model should be used
AUTH_USER_MODEL = 'auth.User' # app_label.model
make sure you use python manage.py makemigrations && python manage.py migrate to create your custom user model.
Enjoy!

Admin doesn't register address type how come (I use django)?

This is the problem:
if a address is submitted the address should automatically register a ADDRESS TYPE in the address section in my admin as you can see on this picture where an address is submitted in an checkoutform (the address type should be the shipping address): enter image description here
this is the code of my models.py:
from django.db import models
from billing.models import BillingProfile
ADDRESS_TYPES = (
('billing', 'Billing'),
('shipping', 'Shipping'),
)
# Create your models here.
class Address(models.Model):
billing_profile = models.ForeignKey(BillingProfile)
address_type = models.CharField(max_length=120, choices=ADDRESS_TYPES)
address_line_1 = models.CharField(max_length=120)
address_line_2 = models.CharField(max_length=120, null=True, blank=True)
city = models.CharField(max_length=120)
country = models.CharField(max_length=120)
state = models.CharField(max_length=120)
postal_code = models.CharField(max_length=120)
def __str__(self):
return str(self.billing_profile)
and this is the views.py:
from django.shortcuts import render, redirect
from django.utils.http import is_safe_url
# CRUD create update retrieve delete
from billing.models import BillingProfile
from .forms import AddressForm
def checkout_address_create_view(request):
form = AddressForm(request.POST or None)
context = {
"form": form
}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
if form.is_valid():
instance = form.save(commit=False)
billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)
if billing_profile is not None:
instance.billing_profile = billing_profile
instance.address_type = request.POST.get('address_type', 'shipping')
instance.save()
else:
print("Error here")
return redirect("cart:checkout")
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("cart:checkout")
return redirect("cart:checkout")
This rule should do the trick in views.py, but unfortunately not showing in the admin (as seen on the picture :( :
instance.address_type = request.POST.get('address_type', 'shipping')
Does someone has advice?

Adding methods to GAE database class

I am messing around with GAE. I want to place my database object in one file and call it from another. Here is the DB object:
import webapp2
import os
import jinja2
import json
import logging
import main
from google.appengine.ext import db
class User(db.Model):
user_name = db.StringProperty(required = True)
hashed_password = db.StringProperty(required = True)
email = db.EmailProperty(required = True)
created_dttm = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
coords = db.GeoPtProperty(required = False)
# def as_dict(self):
# time_fmt = '%c'
# d = {
# 'subject':self.subject,
# 'content':self.content,
# 'created':self.created_dttm.strftime(time_fmt),
# 'last_modified': self.last_modified.strftime(time_fmt)
# }
# return d
def isValueUnique(self,column,value):
result = None
q = User.all()
q.filter(column, value)
result = q.get()
return result
I cannot instantiate the DB because it thinks I'm trying to store data.
I want to call the isValueUnique method from another file like so:
import webapp2
import os
import jinja2
import json
import logging
import main
import database
import validation
from google.appengine.ext import db
class SignUp(main.Handler):
def post(self):
user_username = self.request.get("username")
user_email = self.request.get("email")
user_pass = self.request.get("password")
user_verify = self.request.get("verify")
valid = validation.Valid()
error1=""
error2=""
error3=""
error4=""
q = database.User.all()
q.filter("username =", user_username)
result = q.get()
if result:
error1="Username already taken"
if (not valid.valid_user(user_username)) and (not error1):
error1 = "Enter a valid username"
if not valid.valid_password(user_pass):
error2 = "Enter a valid password"
if not valid.valid_pass_match(user_pass,user_verify):
error3 = "Passwords must match"
# Email Validation
email=valid.valid_email(user_email)
if not email:
error4 = "Invalid email"
email=""
elif not database.User.isValueUnique("email",email):
error4 = "Email already in use, please sign in"
email=""
I get this error:
elif not database.User.isValueUnique("email",email):
TypeError: unbound method isValueUnique() must be called with User instance as first argument (got str instance instead)
I can't instantiate User like I already said. What is the work around here?
database.User.isValueUnique("email",email)
This is attempting to call a method on the database.User class, but isValueUnique is an instance method.
If you decorate isValueUnique with #staticmethod you'll get farther.
Where are you trying to instantiate a User?

TypeError: takes exactly 1 argument (2 given) within GAE

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')

Resources