簡體   English   中英

如何修復 Flask 中的“請求的 URL 不允許使用該方法”

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

我正在嘗試將經過身份驗證的用戶重定向到新的模板文件,但每次我都會收到“請求的 URL 不允許使用該方法”錯誤。

這是我的登錄 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')

這是我用來渲染表單字段以將它們與材料設計引導程序一起使用的宏。

 {% 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 %}

這是我的路線的視圖函數。

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

這是我實現登錄模式的方法。

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

當我嘗試提交時,它會彈出錯誤,如果我給表單一個操作到圓圈頁面它不會驗證它只是重定向到頁面。如果我將主頁視圖分成兩個不同的視圖功能,即。 登錄和注冊,並給他們每個人自己的模板,它工作正常。 當我將它們移回我的主視圖以便使用模態訪問導航欄上的兩個模態時,它無法進行身份驗證。 任何人都可以請洞察我可能搞砸的地方。 我是 Flask 的新手。

使用標簽<form method="POST" action=""> ,您的表單將被提交到當前 url,因此/ 但只有/home端點支持 POST 方法。 您應該將裝飾器更改為@app.route("/",methods=['GET','POST']) ,或者將表單標記更改為action="/home"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM