You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Odoo 10自动登出问题:修改密码后无法跳转至登录页

Fixing Auto-Logout & Redirect After Password Change in Odoo 10

Hey there! Let's sort out this frustrating issue where your password change page isn't triggering a session logout and redirect to the login screen. I've looked at your code snippet, and the core problem is that model methods (like create) aren't the right place to handle session management or redirects—those belong in controller logic. Let's break down the solution step by step.

What's Missing in Your Current Code?

Your create method handles password validation and hashing, but it doesn't touch the user session or handle redirects. Odoo's model layer is for business logic, not HTTP-related tasks like session destruction or page redirects. You need to move that part to a controller, where you can access the request object to manage sessions and redirects.

Step-by-Step Solution

1. Fix the Model Logic (Ensure Passwords Are Updated Correctly)

First, let's make sure your custom password model properly validates and updates the user's password. Assuming your MyPass model is tied to the current user, here's a polished version:

from odoo import models, api, fields, exceptions
from passlib.context import CryptContext

class MyPass(models.Model):
    _name = 'my.pass'

    new_password = fields.Char(string='New Password', required=True)
    confirm_pwd = fields.Char(string='Confirm Password', required=True)
    user_id = fields.Many2one('res.users', string='User', default=lambda self: self.env.user, required=True)

    @api.model
    def create(self, vals):
        # Validate password match
        if vals.get('new_password') != vals.get('confirm_pwd'):
            raise exceptions.ValidationError("Passwords do not match!")
        
        # Hash the new password using Odoo's preferred method
        pwd_context = CryptContext(['pbkdf2_sha512'], deprecated='auto')
        hashed_password = pwd_context.hash(vals['new_password'])
        
        # Update the linked user's password
        user = self.env['res.users'].browse(vals['user_id'])
        user.write({'password': hashed_password})
        
        # Proceed with creating the password change record
        res = super(MyPass, self).create(vals)
        return res

2. Add a Controller to Handle Logout & Redirect

Create a controller file (e.g., controllers/password_controller.py) to handle the form submission, trigger the model logic, destroy the session, and redirect to login:

from odoo import http
from odoo.http import request
from odoo import exceptions

class PasswordChangeController(http.Controller):
    # Route to display the password change page
    @http.route('/my/change_password', type='http', auth='user', website=True)
    def show_change_password_page(self, **kw):
        return request.render('your_module_name.change_password_template', {})

    # Route to handle form submission
    @http.route('/my/submit_password_change', type='http', auth='user', website=True, methods=['POST'])
    def submit_password_change(self, new_password, confirm_pwd, **kw):
        try:
            # Trigger the model's create method to validate and update password
            request.env['my.pass'].create({
                'new_password': new_password,
                'confirm_pwd': confirm_pwd,
                'user_id': request.env.user.id
            })

            # Destroy the current user session
            request.session.logout(keep_db=True)

            # Redirect to the official Odoo login page
            return request.redirect('/web/login')
        
        except exceptions.ValidationError as e:
            # If validation fails, return to the form with an error message
            return request.render('your_module_name.change_password_template', {
                'error_message': e.name
            })

3. Key Notes to Make This Work

  • Controller vs Model: Always handle HTTP actions (like redirects and session management) in controllers—models don't have access to the request object needed for these tasks.
  • Session Destruction: request.session.logout(keep_db=True) safely ends the user's session while keeping the database connection intact, which is the cleanest way to log someone out in Odoo.
  • Permissions: Make sure your user has write access to the res.users model (specifically to update their own password).
  • Template Setup: You'll need a corresponding QWeb template (change_password_template) for your password change form that posts to the /my/submit_password_change route.

Quick Troubleshooting Tips

  • If the redirect still doesn't work, check your browser's dev tools to see if there are any JavaScript errors or if the session cookie is being cleared properly.
  • Ensure your custom module is installed and the routes are registered correctly (restart Odoo after adding the controller).

内容的提问来源于stack exchange,提问作者Stefani Johnsson

火山引擎 最新活动