MultiValueDictKeyError at /registroEstudianteMayor/ "'Acudiente'" - python

I have this error
MultiValueDictKeyError at /registroEstudianteMayor/"'Acudiente'" ",
I searched a lot for an answer to this error but I couldn't find any.
I have this controller:
def post(self, request, *args, **kwargs):
generos = parametros['generos']
tiposDocumento = parametros['tiposDocumento']
zonas = parametros['zonas']
#Toma de datos
numeroDocumento = request.POST['numeroDocumento']
tipoDocumento = request.POST['tipoDocumento']
contrasena = request.POST['contrasena']
contrasena2 = request.POST['contrasena2']
correoElectronico = request.POST['correoElectronico']
nombres = request.POST['nombres']
apellidos = request.POST['apellidos']
fechaNacimiento = request.POST['fechaNacimiento']
genero = request.POST['genero']
direccion = request.POST['direccion']
barrio = request.POST['barrio']
telefonoFijo = request.POST['telefonoFijo']
telefonoCelular = request.POST['telefonoCelular']
seguridadSocial = request.POST['seguridadSocial']
#Toma de datos particulares
nombreAcudiente = request.POST['Acudiente']
telefonoAcudiente = request.POST['telefonoAcudiente']
foto = request.FILES['foto']
cedula = request.FILES['cedula']
#Inicializo datos opcionales
zona = ""
comuna = ""
grupoEtnico = ""
condicion = ""
enviarInfoAlCorreo = False
#Inicializo Datos Opcionales particulares
desempeno = ""
lugar = ""
#Tomo los datos opcionales
if request.POST['zona']: zona = request.POST['zona']
if request.POST['comuna']: comuna = request.POST['comuna']
if request.POST['grupoEtnico']: grupoEtnico = request.POST['grupoEtnico']
if request.POST['condicion']: condicion = request.POST['condicion']
if "enviarInfoAlCorreo" in request.POST.keys(): enviarInfoAlCorreo = True
#tomo datos opcionales particulares
if request.POST['Labor']: desempeno = request.POST['Labor']
if request.POST['Lugar']: lugar = request.POST['Lugar']
#Validaciones
errorNumeroDocumento = (User.objects.filter(username=numeroDocumento) or not re.match("^([0-9]{8,20})$",numeroDocumento))
errorTipoDocumento = (tipoDocumento not in (parametros["tiposDocumento"]))
errorContrasena = (request.POST["contrasena"]!=request.POST["contrasena2"])
errorCorreoElectronico = (User.objects.filter(email=correoElectronico) or not re.match(r"^[A-Za-z0-9\._-]+#[A-Za-z0-9]+\.[a-zA-Z]+$", correoElectronico))
errorFechaNacimiento = not fechaCorrecta(fechaNacimiento)
errorGenero = (genero not in (parametros["generos"]))
errorTelefonos = (not re.match("^([0-9]{7,12})$",telefonoFijo) or not re.match("^([0-9]{7,12})$",telefonoCelular) or not re.match("^([0-9]{7,12})$",telefonoAcudiente))
if (errorContrasena or errorNumeroDocumento or errorTipoDocumento or errorCorreoElectronico or errorFechaNacimiento or errorGenero or errorTelefonos):
return render_to_response('Generales/registroEstudianteMayor.html', locals(), context_instance = RequestContext(request))
#Guardar usuario
usuario = User.objects.create_user(id=User.objects.all().count() + 1, username=numeroDocumento, email=correoElectronico, password=contrasena)
usuario.first_name = nombres
usuario.last_name = apellidos
usuario.save()
#Guardo estudiante
estudiante = Estudiante(user = usuario, tipoDocumento = tipoDocumento, fechaNacimiento = fechaNacimiento, genero = genero, direccion = direccion, barrio = barrio, zona = zona, comuna = comuna,
telefonoFijo = telefonoFijo, telefonoCelular = telefonoCelular, grupoEtnico = grupoEtnico, condicion = condicion, seguridadSocial = seguridadSocial, enviarInfoAlCorreo = enviarInfoAlCorreo)
estudiante.save()
#Guardo datos particulares del Mayor
datosMayor = DatosFamiliaMayor(idEstudiante= user, nombreContacto= nombreAcudiente, telefonoContacto= telefonoAcudiente,
desempeno= desempeno, lugar= lugar, cedula= cedula, foto= foto)
datosMayor.save()
return inicioControl(request, registerSuccess=True)
and the part of the view being affected is:
<label class="control-label col-md-4" for="acud">Nombre Acudiente:</label>
<div class= "col-md-8">
<input type="text" name="Nomacud" requiered="true" value="{{Acudiente}}" class="form-control" id="nomacud">
</div>
</div>
<div class="form-group" id="TelAcudiente">
<label class="control-label col-md-4" for="Acudtel">Telefono Acudiente:</label>
<div class="col-md-8">
<input type="text" name="Telacud" requiered="true" value="{{telefonoAcudiente}}" class="form-control" id="telacud">
</div>
</div>
In TelefonoAcudiente the error is the same.

You don't have a field called Acudiente in your view; you have one called Nomacud instead.
Really though you should be using Django forms for all this.

Related

Getting 405 http error in POST on Django, the is problem in the urls?

Getting 405 status after using POST method in this django aplication
#urls
"""Configuracoes de URL dos Resultados das Buscas
https://docs.djangoproject.com/en/3.1/topics/http/urls/
"""
from django.conf.urls import url
from django.urls import path
from . views import BuscaHorarios, AgendaHorario
app_name = "agendamento"
urlpatterns = [
url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$',
AgendaHorario.as_view(),
name='horarios',
),
url('/', AgendaHorario.as_view(), name="agenda_horario"),
]
I think the problem occurs over here, but i'm not sure
##forms
from django.forms import Form, CharField, EmailField, EmailInput, TextInput
class AgendaHorarioForm(Form):
nome_paciente = CharField(required=True, widget=TextInput(
attrs={'placeholder': 'Digite seu nome completo',
'class': 'form-control', 'label_tag': 'Nome do paciente'}))
email_paciente = EmailField(widget=EmailInput(attrs={'placeholder': 'Digite seu e-mail', 'class': 'form-control', 'label_tag': 'E-mail'}))
telefone_paciente = CharField(required=True, widget=TextInput(
attrs={'placeholder': 'Digite seu telefone com DDD',
'data-mask': '(00) 00000-0000',
'class': 'form-control',
'label_tag': 'Telefone com DDD'}))
views
class AgendaHorario(View):
form_class_agenda = AgendaHorarioForm
paciente = {}
prestadorunidade = None
prestadorservicos = None
servicoregioes = None
agenda_service = None
horario_marcado = None
def get_context_data(self, **kwargs):
print('a')
context = super().get_context_data(**kwargs)
context['prestadorunidade'] = self.prestadorunidade
context['prestadorservicos'] = self.prestadorservicos
context['horario_marcado'] = self.horario_marcado
context['paciente'] = self.paciente
print('a')
return context
def post(self, *args, **kwargs):
print('b')
if self.request.is_ajax and self.request.method == "POST":
form = self.form_class_agenda(self.request.POST)
if form.is_valid():
post_data = form.cleaned_data
self.paciente['nome'] = post_data['nome_paciente']
self.paciente['email'] = post_data['email_paciente']
self.paciente['telefone'] = post_data['telefone_paciente']
lista_unidades = list(cache.get('PrestadorUnidades', PrestadorUnidades.objects.values()))
unidadeid = int(self.request.POST.get('prestadorunidadeid'))
self.prestadorunidade = [item for item in lista_unidades if item['unidadeid'] == unidadeid][0]
lista_prestadorservicos = list(cache.get('PrestadorServicos', PrestadorServicos.objects.values()))
prestadorservicosid = int(self.request.POST.get('prestadorservicosid'))
self.prestadorservicos = [
item for item in lista_prestadorservicos if item['prestadorservicoid'] == prestadorservicosid][0]
lista_servicos = list(cache.get('ServicosRegioesCorpo', ServicosRegioesCorpo.objects.values()))
self.servicoregioes = [item for item in lista_servicos if item['idservicosregioes']
== self.prestadorservicos['idservicosregioes_fk_id']][0]
servico = ServicosRegioesCorpo.objects.get(
idservicosregioes=self.prestadorservicos['idservicosregioes_fk_id'])
horario = self.request.POST.get('horario-escolhido')
self.horario_marcado = refatora_data(horario)
self.horario_marcado = datetime.datetime.strptime(self.horario_marcado, '%Y-%m-%dT%H:%M')
prestadorunidade_calendar_list = list(cache.get('Calendar', Calendar.objects.values()))
prestadorunidade_calendar = [item for item in prestadorunidade_calendar_list if item['id']
== self.prestadorunidade['calendar_id_fk']][0]
prestadorunidade_calendar_obj = Calendar.objects.get(id=self.prestadorunidade['calendar_id_fk'])
self.agenda_service = GoogleCalendarService(
prestadorunidade_calendar, prestadorunidade_calendar_obj, self.prestadorservicos)
self.marcar_servico(self.horario_marcado)
msg_sucesso = f'%s agendado com sucesso para %s. Anote na sua agenda!' % (
servico, self.paciente['nome'])
return JsonResponse({"msg_sucesso": msg_sucesso, "horario_marcado": horario}, status=200)
else:
return JsonResponse({"error": form.errors}, status=400)
return JsonResponse({"error": ""}, status=400)
def marcar_servico(self, horario):
print('c')
servico = ServicosRegioesCorpo.objects.get(
idservicosregioes=self.prestadorservicos['idservicosregioes_fk_id'])
summary = f'%s com paciente %s. Contato: %s ou %s' % (str(servico),
self.paciente['nome'],
self.paciente['telefone'],
self.paciente['email'])
lista_bairros = list(cache.get('Bairros', Bairros.objects.values()))
bairro = [item for item in lista_bairros if item['bairroid'] == self.prestadorunidade['bairroid_fk_id']][0]
location = f'%s %i, %s\n%s, %s\n%s' % (self.prestadorunidade['logradourounid'],
self.prestadorunidade['numerounid'],
self.prestadorunidade['complementounid'],
bairro['bairro'],
bairro['cidade'],
self.prestadorunidade['cep'])
descricao = 'Agendado pelo Saúde Pra Já.'
self.agenda_service.marcar_evento(summary, location, horario, descricao)
html simplified
<form id="schedule-form" action="" method="POST">
<input type="submit" id="submit-horario" value="Confirmar"/>
Am i seting my urls wrong ?
Is the error ou the views.py file ?
The only message i get in the console is: POST /agendamento/11749/1341/ HTTP/1.1" 405 0
When i run this post in Insomnia i get http status 403

Django cannot serialize into migration file

Hi there i'm having problems when trying to use the command makemigrations with manage.py.
The output is the following:
Migrations for 'reg':
reg\migrations\0012_auto_20190917_1711.py
- Remove field Products from tenant
- Add field products to tenant
- Alter field productos on preaprobado
- Alter field tenant_id on preaprobado
- Alter field CMS_id on producto
- Alter field CMS_id on tenant
Traceback errors
ValueError: Cannot serialize: <Producto: Basico - ['IPTEL', 'Rocstar', 'Test_DVT']>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/2.2/topics/migrations/#migration-serializing
The thing is that the entire app works just fine but for some reason i can't understand i cannot migrate the db.
Here is the models.py:
class Producto(models.Model):
Name = models.CharField(max_length = 50, unique = True)
CMS_id = models.PositiveIntegerField(unique = True)
def __str__(self):
#Toma los tenants que tienen el producto asignado por el nombre y forma una lista de los nombres de los tenants
#para que aparezcan al lado del nombre del producto
tenants_with_product = Tenant.objects.filter(products__Name = self.Name)
tenants_dict = tenants_with_product.in_bulk(field_name = "Name")
tenants_list = []
for tenant_name in tenants_dict.keys():
tenants_list.append(tenant_name)
return(self.Name + " - " + tenants_list.__str__())
class Tenant(models.Model):
Name = models.CharField(max_length = 30, unique = True)
Enabled = models.BooleanField(default = False)
CMS_id = models.PositiveIntegerField(unique = True)
Logo = models.ImageField(upload_to = "Logos/", blank = True)
Icon = models.ImageField(upload_to = "Icons/", blank = True)
Domain = models.URLField(default = "http://localhost:8000")
Master = models.BooleanField(default = False)
products = models.ManyToManyField(Producto, related_name = "tenants")
def __str__(self):
return(self.Name)
# Override del metodo que salva en la db para que si se quiere salvar un Tenant con Master = True y
# existe un Tenant con mismo dominio y Master = True no pueda salvar
def save(self, *args, **kwargs):
#busca tenant con mismo dominio y Master = True
try:
master_tenant = Tenant.objects.filter(Domain = self.Domain).get(Master = True)
#Si el tenant encontrado es el que se quiere salvar chequeo que sea Master = True y salvo
#sino pido Master = True. Chequea tambien que el master tenga logo e icono si o si
if master_tenant.id == self.id:
if self.Master:
if self.Logo != "" and self.Icon != "":
super(Tenant, self).save(*args, **kwargs)
else:
raise ValidationError({"Logo" : "Logo required", "Icon" : "Icon rquired"})
else:
raise ValidationError({"Master" : "At least one Master per Domain"})
else:
#Si no es el Master = True del dominio y Master = False guarda, sino error
if self.Master:
if self.Logo != "" and self.Icon != "":
super(Tenant, self).save(*args, **kwargs)
else:
raise ValidationError({"Logo" : "Logo required", "Icon" : "Icon rquired"})
else:
super(Tenant, self).save(*args, **kwargs)
#Si no existe tenant con mismo Domain y Master = True, Se fija que Master = True y que tenga logo e icono y salva, sino, error
except Tenant.DoesNotExist:
if self.Master:
if self.Logo != "" and self.Icon != "":
super(Tenant, self).save(*args, **kwargs)
else:
raise ValidationError({"Logo" : "Logo required", "Icon" : "Icon rquired"})
else:
raise ValidationError({"Master" : "At least one Master per Domain"})
class Preaprobado(models.Model):
codigo = models.CharField(max_length = 100)
tenant_id = models.ForeignKey(Tenant, on_delete = models.CASCADE, related_name = "tenant")
can_register = models.BooleanField(default = True)
is_registered = models.BooleanField(default = False)
productos = models.ManyToManyField(Producto, related_name = "preaprobados", default = Producto.objects.get(id = 1))
def __str__(self):
return(self.codigo + "-" + self.tenant_id.Name)
class Meta():
#No permite un par codigo-tenant repetido dentro del modelo Preaprobado
constraints = [
models.UniqueConstraint(fields = ["codigo", "tenant_id"], name = "par código-Tenant únicos"),
]
Any help is welcomed since i actually can't find what is wrong with the code. Not even in the documentation. I'm new with Django so maybe the solution is pretty easy but i can't find it.

Django search "DoesNotExist"

I'm using Django to build a website for a football club, which contains many blog articles. I'm trying to include a search bar, but I can't make it work. When submitting the search term, the following error is shown:
DoesNotExist at /web/search/
Articulo matching query does not exist.
Here is my code:
views.py
def search(request):
query = request.GET.get('q', '')
if query:
try:
qset = (
Articulo(titulo__icontains=query) |
Articulo(cuerpo_icontains=query)
)
results = Articulo.objects.filter(qset).distinct()
except Articulo.DoesNotExist:
results = None
else:
results = []
return render_to_response('web/buscar.html', {"results": results, "query": query})
index.html
<div id="busqueda" class="row">
<div class="col-md-12">
<span id="cruz" class="fas fa-times fa-2x"></span>
<form method="GET" action="/web/search/" class="form my-2 my-lg-0">
<input id="searchBox" value="{{ query|escape }}" class="form-control mr-sm-2" type="text" name="q" placeholder="Buscar" aria-label="Buscar">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button>
</form>
</div>
</div>
urls.py
url(r'^search/$', search),
models.py
class Articulo(models.Model):
"""Un artículo de la página"""
id = models.AutoField(primary_key=True)
titulo = models.CharField(max_length=100)
slug = models.SlugField(unique=True, default="")
CATEGORIAS = (
('Primera y Sub 21', 'Primera y Sub 21'),
('Inferiores', 'Inferiores'),
('Básquet', 'Básquet'),
('Hockey', 'Hockey'),
('Gurises', 'Gurises'),
('Generales', 'Generales'),
('Institucionales', 'Institucionales'),
('Senior', 'Senior'),
)
categoria = models.CharField(
max_length=200,
choices=CATEGORIAS
)
cuerpo = RichTextField()
fecha_hora= models.DateTimeField()
foto = models.ImageField()
url_video = models.CharField(help_text='Url del video de facebook (opcional). Para obtener el link, ir al video, apretar donde están los 3 puntitos y poner "insertar". Pegar aquí solo el link del video, borrar el resto. Ejemplo: https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FJuanCruzPiornoOficial%2Fvideos%2F302760100205413', max_length=500,blank=True)
album_flickr = models.CharField(help_text="Subir fotos a Flickr, crear un álbum, compartirlo eligiendo la opción 'Insertar', elegir el tamaño más grande, y pegar el link aquí", max_length=700, blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.titulo)
super(Articulo, self).save(*args, **kwargs)
def __str__(self):
return self.titulo
try this
def search(request):
query = request.GET.get('q', '')
if query:
try:
qset = Articulo.objects.filter(Q(titulo__icontains=query) | cuerpo_icontains = query) # change is here <<
results = Articulo.objects.filter(some_field=some_value).distinct() # change is here <<
except Articulo.DoesNotExist:
results = None
else:
results = []
return render_to_response('web/buscar.html', {"results": results, "query": query})
Note: I'm not sure why you are using qset and result there!
Since you are trying to perform a "search" (or filtering) you should use "fitler()" instead of get(), it makes more sense semantically. For your information, filter does not raise an exception if the result is empty.
Your code will look similar to:
from django.db.models import Q
def search(request):
results = []
query = request.GET.get('q', '')
if query:
qset = Q(titulo__icontains=query) | Q(cuerpo__icontains=query)
results = Articulo.objects.filter(qset).distinct()
ctx = {"results": results, "query": query}
return render_to_response('web/buscar.html', ctx)
If you are getting DoesNotExist exceptions with code which uses filter() you should take a look to the traceback to look for the liurls.py file to ensure that your desired views is being called and not other one.
first you need to import Q after that you can lookup function that takes keyword-arguments (e.g. filter(), exclude(), get()
from django.db.models import Q
def search(request):
query = request.GET.get('q', '')
if query:
Articulo.objects.get(
Q(titulo__icontains=query) |
Q(cuerpo_icontains=query)
)
return query
for more info you can check the docs here
from django.db.models import Q
def search(request):
results = []
query = request.GET.get('q', None)
if query:
try:
results = Articulo.objects.filter(Q(titulo__icontains=query) | Q(cuerpo_icontains=query))
except Articulo.DoesNotExist:
pass
return render_to_response('web/buscar.html',{"results": results, "query": query})

Google App Engine: Extracting the value of the radio button chosen

I'm building an application which allows users to create surveys and vote on the questions of the surveys. Now, the answers to those questions will be stored in the datastore so that I can analyze the results in the end. However, I am unable to figure out a way to extract the value of the radio button chosen by the user. Each question has three options, all of whom represented by a radio button.
Here's the code:
main.py
import os
import webapp2
import jinja2
from google.appengine.ext import db
from random import randint
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
#databases
class Survey(db.Model):
vam_id = db.StringProperty()
subject = db.StringProperty(required = True)
description = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
q1 = db.TextProperty(required = True)
o11 = db.TextProperty(required = True)
o12 = db.TextProperty(required = True)
o13 = db.TextProperty(required = True)
q2 = db.TextProperty(required = True)
o21 = db.TextProperty(required = True)
o22 = db.TextProperty(required = True)
o23 = db.TextProperty(required = True)
q3 = db.TextProperty(required = True)
o31 = db.TextProperty(required = True)
o32 = db.TextProperty(required = True)
o33 = db.TextProperty(required = True)
q4 = db.TextProperty(required = True)
o41 = db.TextProperty(required = True)
o42 = db.TextProperty(required = True)
o43 = db.TextProperty(required = True)
q5 = db.TextProperty(required = True)
o51 = db.TextProperty(required = True)
o52 = db.TextProperty(required = True)
o53 = db.TextProperty(required = True)
class Votes(db.Model):
vam_id = db.StringProperty(required = True)
q1_opt = db.TextProperty(required = True)
q2_opt = db.TextProperty(required = True)
q3_opt = db.TextProperty(required = True)
q4_opt = db.TextProperty(required = True)
q5_opt = db.TextProperty(required = True)
class MainPage(Handler):
def get(self):
self.render("homepage.html")
class NewSurvey(Handler):
def get(self):
self.render("newsurvey.html")
def post(self):
vam_id = str(randint(1, 500))
subject = self.request.get("title")
description = self.request.get("description")
q1 = self.request.get("q1")
o11 = self.request.get("o11")
o12 = self.request.get("o12")
o13 = self.request.get("o13")
q2 = self.request.get("q2")
o21 = self.request.get("o21")
o22 = self.request.get("o22")
o23 = self.request.get("o23")
q3 = self.request.get("q3")
o31 = self.request.get("o31")
o32 = self.request.get("o32")
o33 = self.request.get("o33")
q4 = self.request.get("q4")
o41 = self.request.get("o41")
o42 = self.request.get("o42")
o43 = self.request.get("o43")
q5 = self.request.get("q5")
o51 = self.request.get("o51")
o52 = self.request.get("o52")
o53 = self.request.get("o53")
a = Survey(vam_id = vam_id, subject = subject, description = description, q1 = q1,
o11 = o11, o12 = o12, o13 = o13, q2 = q2,
o21 = o21, o22 = o22, o23 = o23, q3 = q3,
o31 = o31, o32 = o32, o33 = o33, q4 = q4,
o41 = o41, o42 = o42, o43 = o43, q5 = q5,
o51 = o51, o52 = o52, o53 = o53)
a.put()
class Existing(Handler):
def get(self):
surveys = Survey.all()
self.render("existingsurvey.html", surveys = surveys)
class PermaSurvey(Handler):
def get(self):
vam = self.request.get("vam_id")
su = Survey.all().filter("vam_id =", vam).get()
self.render("perma.html", su = su)
def post(self):
vam = self.request.get("vam_id")
q1_opt = self.request.get("q1")
q2_opt = self.request.get("q2")
q3_opt = self.request.get("q3")
q4_opt = self.request.get("q4")
q5_opt = self.request.get("q5")
v = Votes(vam_id = vam, q1_opt = q1_opt, q2_opt = q2_opt, q3_opt = q3_opt,
q4_opt = q4_opt, q5_opt = q5_opt)
v.put()
app = webapp2.WSGIApplication([('/', MainPage),
('/new', NewSurvey),
('/existing', Existing),
('/perma', PermaSurvey)], debug=True)
perma.html
<html>
<head>
<title>Perma Survey</title>
</head>
<body>
<form method = "post">
{% block content %}
<h2>{{su.subject}}</h2>
<p>{{su.description}}</p>
<br>
{{su.q1}}
<br>
<input type="radio" name="q1">{{su.o11}}<br>
<input type="radio" name="q1">{{su.o12}}<br>
<input type="radio" name="q1">{{su.o13}}
<hr>
{{su.q2}}
<br>
<input type="radio" name="q2">{{su.o21}}<br>
<input type="radio" name="q2">{{su.o22}}<br>
<input type="radio" name="q2">{{su.o23}}
<hr>
{{su.q3}}
<br>
<input type="radio" name="q3">{{su.o31}}<br>
<input type="radio" name="q3">{{su.o32}}<br>
<input type="radio" name="q3">{{su.o33}}
<hr>
{{su.q4}}
<br>
<input type="radio" name="q4">{{su.o41}}<br>
<input type="radio" name="q4">{{su.o42}}<br>
<input type="radio" name="q4">{{su.o43}}
<hr>
{{su.q5}}
<br>
<input type="radio" name="q5">{{su.o51}}<br>
<input type="radio" name="q5">{{su.o52}}<br>
<input type="radio" name="q5">{{su.o53}}
<hr>
<br>
<input type = "submit">
{% endblock %}
</form>
</body>
</html>
Now, no matter what options I select from the three listed ones, the value that's stored in the datastore is 'on', indicating that a radio button from the radio button group is selected. How can I store the actual choices that were chosen by the user into the datastore ?
You have not assigned any values to your form elements. I think you want:
<input type="radio" name="q3" value="{{su.o31}}" />{{su.o31}}<br>
Now, you can retrieve it's value. Since you're already using jinja, I suggest you use the WTForms package to make this all easier.

tornado dont accept the POST method

i get the 405: Method Not Allowed, so where is the problem, it's a
post method since i want to send data to the server
class VendreHandler(BaseHandler):
#tornado.web.authenticated
def post(self):
self.db = conn["essog"]
user = self.get_secure_cookie("mechtari")
info = tornado.escape.json_decode(user)
email = info["email"]
namep = self.get_argument("namep")
prix = self.get_argument("prix")
description = self.get_argument("description")
date = datetime.datetime.now().date()
try:
photo = self.request.files['photo'][0]["body"]
try:
avctype = self.request.files['avatar'][0]["content_type"]
image = Image.open(StringIO.StringIO(buf=avat))
type = image.format
(x, y) = image.size
if x < y:
orientation = "portrait"
else:
orientation = "paysage"
pref = str(time.time())
nomfi = pref.replace(".", "")
nomfich = nomfi + "-" + self.request.files['avatar'][0]["filename"]
self.fs = GridFS(self.db)
avatar_id = self.fs.put(avat, content_type=avctype,filename=nomfich)
except IOError, TypeError:
self.redirect("/error-im")
except KeyError:
nomfich = "nofile"
orientation = "paysage"
avctype = "image/jpeg"
avatar_id = '503ae8553a5f3a0dd8b9cb4c'
self.db.users.update({"email":email}, {"$set":{"produit_up.namep":namep,"produit_up.prix":prix,"produit_up.photo":photo_id, "produit_up.description":description,"produit_up.date":date, "produit_up.vendu":False}})
self.redirect("/success")
and the template:
<form id="formvente" name="formvente" method="post" action="/vendre" enctype="multipart/form-data">
{% raw xsrf_form_html() %}
<label for="namep">Le nom du Produit</label>
<input type="text" name="namep" required title="vous devez mettre le nom du produit" placeholder="exemple: peugeot 206">
<label for="prix">Son prix (en Dinars Algérien)</label>
<input type="number" name="prix" required title="vous devez mettre le prix en chiffre (en Dinars Algérien)" placeholder="exemple: 800000">
<label for="photo">Une photo de votre produit</label>
<input name="photo" type="file">
<label for="description">Veuillez donner une déscription du produit (maximum 160 caractères)</label>
<textarea name="description" id="description" rows="3" cols="60" required title="vous devez mettre une petite description" placeholder="escence, 2006, roulant 100000km, toutes options, siege en cuir" onKeyDown="textCounter(document.formvente.description,160)" onKeyUp="textCounter(document.formvente.description, 160)"></textarea>
<meter name="shower" min="1" max="160" value="1"id="shower" low="30" high="140">afficher son etat</meter>
<input id="vendre" type="submit" value="Mettre en Vente"/>
</form>
and i have simplified the handler to this
class VendreHandler(tornado.web.RequestHandler):
def post(self):
namep = 1
prix = 3
description = 43
date = 345
self.db = conn["essog"]
self.db.users.update({"email":email}, {"$set":{"produit_up.namep":namep,"produit_up.prix":prix, "produit_up.photo":photo_id, "produit_up.description":description,"produit_up.date":date, "produit_up.vendu":False}})
self.redirect("/profil#vendu")
always the method error it dident check the handler content at all
(else it raised and error when not finding email)!
NB: is it because i've used the accodion effect (CSS3)? the page contains 3 parts: the profile, upload product, and search for product, and of course every part has its own handler; so the profile will call
a GET to get the user information and the avatar, and the upload product will make a POST to write product information to the server, and finally the search will make a GET to the server to search for the product.
so, am i making mistake?
SOLVED!
it seems that the problem is coming from the picture handler; in the URLSpec, IT MUST BE THE LAST ONE IN THE LIST
url = [
...,
...,
...,
(r"/(?P<picture>.*)", handlers.PictureHandler)]
this is why when using GET method return errors concerning picture!
hope this will help, and thank you :)

Categories

Resources