Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

ValueError: time data '19/05/2022' does not match format '%Y-%m-%d'

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
datedatepickerecommercewebsitewebsite_sale
1 Responder
12939 Vistas
Avatar
John Wiltshire

I am trying to add a custom date input field to the Extra Info section on the eCommerce Website. I have the code below for a new module (the code in the view I copied from a date field using the Form Builder). It keeps giving me the error:

ValueError: time data '19/05/2022' does not match format '%Y-%m-%d'

when I submit the Extra Info page. If I remove the datepicker from the input field and enter it in manually in the %Y-%m-%d format (eg 2021-02-19) it works...How can I get the datepicker and input field working....I do not want to use type='date' due to browser compatibility issues.


Model

# -*- coding: utf-8 -*-

from odoo import models, fields, api

# Override the Customer Model to include Area Field
class WebsiteSaleOrderExtraInfo(models.Model):
_name = 'sale.order'
_inherit = ['sale.order']

x_website_delivery_date = fields.Date(string='Delivery Date', required=True)


Views

<odoo>
<data>

<!-- Override for Website Sale Addrees View -->
<template id="extra_info_custom" name="Checkout Extra Info with Delivery Date" inherit_id="website_sale.extra_info">
<xpath expr="//div[contains(@class,'s_website_form_submit')]" position="before">

<!-- Adding in Delivery Date at bottom of Form -->
<div class="form-group s_website_form_field col-12 s_website_form_custom" data-type="date" data-name="Field">
<div class="row s_col_no_resize s_col_no_bgcolor">
<label class="col-form-label col-sm-auto s_website_form_label " style="width: 200px" for="x_website_delivery_date">
<span class="s_website_form_label_content">Delivery Date</span>
</label>
<div class="col-sm">
<div class="s_website_form_date input-group date" id="datepicker_x_website_delivery_date" data-target-input="nearest">
<input type="text"
class="form-control datetimepicker-input s_website_form_input"
data-target="#datepicker_x_website_delivery_date"
name="x_website_delivery_date"
placeholder=""
id="x_website_delivery_date"
required="1"
/>

<div class="input-group-append" data-target="#datepicker_x_website_delivery_date" data-toggle="datetimepicker" options="{'datepicker':{'minDate': 0}}">
<div class="input-group-text">
<i class="fa fa-calendar"></i>
</div>
</div>
</div>
</div>
</div>
</div>

</xpath>
</template>


<!-- Allow x_website_delivery_date to be whitelisted in web forms -->
<function model="ir.model.fields" name="formbuilder_whitelist">
<value>sale.order</value>
<value eval="[
'x_website_delivery_date'
]"/>
</function>

</data>
</odoo>






0
Avatar
Descartar
John Wiltshire
Autor

Follow up debugging:

The Extra Info Next button calls the /website_form/shop.sale.order route in website_sale. It is failing at the:

order.write(data['record']) line

where data['record'] = {'x_website_delivery_date': '20/04/2021'}

Avatar
John Wiltshire
Autor Mejor respuesta

So I figured out how to do this...I'm hoping there might still be a better way. I created a controller that overrides the /website_form/shop.sale.order route. It seems that the website forms do not manage date fields well and it would be great if some helper/date handler was built in to the odoo base install.

# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
from odoo.addons.website_sale.controllers.main import WebsiteSaleForm
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
import datetime

# Extend the WebsiteSale class
class WebsiteSaleExtraInfo(WebsiteSaleForm):
    @http.route('/website_form/shop.sale.order', type='http', auth="public", methods=['POST'], website=True)
    def website_form_saleorder(self, **kwargs):
        user_date_format = request.env['res.lang']._lang_get(request.env.user.lang).date_format
        # Loop through args and convert dates if required
        for k, v in kwargs.items():
            new_date = self.convert_date(v, user_date_format)
            if new_date:
                kwargs[k] = new_date
        res = super(WebsiteSaleExtraInfo, self).website_form_saleorder(**kwargs)
        return res
    # Helper function to convert a date from the user date format to the server date format
    def convert_date(self, custom_date, original_date_format, new_date_format=DEFAULT_SERVER_DATE_FORMAT):
        try:
            new_date = datetime.datetime.strptime(custom_date, original_date_format).strftime(new_date_format)
        except:
            return False
        return new_date
0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Disable Automatic Confirmation of Website Orders
ecommerce website website_sale
Avatar
Avatar
1
may 24
3964
create a Button on the home page of website
javascript ecommerce website website_sale OWL
Avatar
0
ago 24
2209
How to Show Website shop product Based on GeoIP Address ?
product ecommerce geolocation website website_sale
Avatar
0
ene 23
2929
How to set Timer for Website Session Logout for Userwise in Odoo14?
ecommerce logout website website_sale v14
Avatar
Avatar
1
may 22
5247
Website Date Picker
date datetime datepicker website datetimepicker
Avatar
0
abr 22
5596
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now