简体   繁体   English

如何修复 Flask 中的“请求的 URL 不允许使用该方法”

[英]How to fix "The method is not allowed for the requested URL" in Flask

I am trying to redirect an authenticated user to a new template file but i keep getting this "The method is not allowed for the requested URL" error each time.我正在尝试将经过身份验证的用户重定向到新的模板文件,但每次我都会收到“请求的 URL 不允许使用该方法”错误。

This my login Wtform model:这是我的登录 Wtform 模型:

class Register(FlaskForm):
      username = StringField('Username',validators=[DataRequired(),
                    Length(min=2, max=20)],)
      email = StringField('Email',validators=[DataRequired(),Email()])

      password = PasswordField('Password', validators=[DataRequired()])
      confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
      submit = SubmitField('Sign Up')

      def validate_email(self,data_field):
              if User.query.filter_by(email =data_field.data).first():
            raise ValidationError('There is an account with that email')

      def validate_username(self,data_field):
      if User.query.filter_by(username = data_field.data).first():
        raise ValidationError('That username is taken')

class Login(FlaskForm):
      email = StringField('Email',validators=[DataRequired(),Email()])

      password = PasswordField('Password', validators=[DataRequired()])
      remember = BooleanField('Remember Me')
      submit = SubmitField('Login')

This is the macro i used to render the form fields to use them with material design bootstrap.这是我用来渲染表单字段以将它们与材料设计引导程序一起使用的宏。

 {% macro render_field(field, label_visible=true) %} {{ field(class_='form-control validate' , **kwargs) }} {% if field.errors %} {% for e in field.errors %} <p class="help-block">{{ e }}</p> {% endfor %} {% else %} {% if field.type != 'HiddenField' and label_visible %} <label for="{{ field.id }}" data-error="wrong" data-success="right">{{ field.label }}</label> {% endif %} {% endif %} {% endmacro %}

Here are the view functions for my routes.这是我的路线的视图函数。

@app.route("/")
@app.route("/home",methods=['GET','POST'])
def home():
    registerForm = Register()
    form = Login()
    if current_user.is_authenticated:
        return redirect(url_for('circles'))
    if registerForm.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user = User(username = form.username.data, email = form.email.data, password = hashed_password)
        db.session.add(user)
        db.session.commit()
        flash(f'Your account has been created! You are now able to login!','success')
        return redirect(url_for('home'))

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
    if user and bcrypt.check_password_hash(user.password,form.password.data):
        login_user(user, remember=form.remember.data)
        next_page = request.args.get('next')
        return redirect(next_page) if next_page else redirect(url_for('circles'))

    else:
        flash('Login Unsuccessful. Please check email and password','danger')
#form=form, registerForm=registerForm

return render_template('home.html', title='login',form=form )


@app.route("/circle",methods=['GET','POST'])
def circles():
    return render_template('circle.html')

Here is how i implemented the modal for login.这是我实现登录模式的方法。

 <div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Sign in</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="POST" action=""> {{ form.hidden_tag() }} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category,message in messages%} <div class="alert alert-{{ category }}"> {{message}} </div> {% endfor %} {% endif %} {% endwith %} <div class="modal-body mx-3"> <div class="md-form mb-5"> <i class="fas fa-envelope prefix grey-text"></i> {{ macros.render_field(form.email, label_visible=false, placeholder='Email', type='email') }} </div> <div class="md-form mb-4"> <i class="fas fa-lock prefix grey-text"></i> {{ macros.render_field(form.password, label_visible=false, placeholder='Password', type='password') }} <p class="font-small blue-text d-flex justify-content-end">Forgot <a href="#" class="blue-text ml-1"> Password?</a></p> </div> </div> <div class="modal-footer d-flex justify-content-center"> <!-- {{ form.submit(class="btn blue-gradient btn-block btn-rounded z-depth-1a") }} --> <button type="submit">submit</button> </div> </form> </div> </div> </div>

When i try submitting, it pops the error, if i give the form an action to the circles page it does not authenticate it just redirects to the page.If i separate the home view into two different view functions ie.当我尝试提交时,它会弹出错误,如果我给表单一个操作到圆圈页面它不会验证它只是重定向到页面。如果我将主页视图分成两个不同的视图功能,即。 login and register, and give them each their own template, it works fine.登录和注册,并给他们每个人自己的模板,它工作正常。 when i move them back to my home view so as to access both modals on my navbar with modals it fails to authenticate.当我将它们移回我的主视图以便使用模态访问导航栏上的两个模态时,它无法进行身份验证。 Could anyone please give insight to where i maybe messing up.任何人都可以请洞察我可能搞砸的地方。 I'm a newbie in Flask.我是 Flask 的新手。

With the tag <form method="POST" action=""> , your form would be submitted to the current url, so / .使用标签<form method="POST" action=""> ,您的表单将被提交到当前 url,因此/ But only the /home endpoint supports a POST method.但只有/home端点支持 POST 方法。 You should either change the decorator to @app.route("/",methods=['GET','POST']) , or change form tag to action="/home" .您应该将装饰器更改为@app.route("/",methods=['GET','POST']) ,或者将表单标记更改为action="/home"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM