403 forbidden

hi
my website error 403 in login
my english not good.

Help
Reason given for failure:

CSRF token from POST incorrect.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

Your browser is accepting cookies.
The view function passes a request to the template’s render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

my setting is

tnx

Please post the form and template that you are trying to submit.

Copy/paste the code into the body of the message, surrounded by lines of three backtick - ` characters. This means you should have a line of ```, then your code (or template), then another line of ```.

Side note: ALLOWED_HOSTS entries do not include the scheme. It’s the host name only without the http:// or https:// prefix.

1 Like

thanks for answer me

class LoginForm(forms.Form):
    username = forms.CharField(
        label='* نام کاربری :',
        error_messages={
            'required': 'برای ورود به سایت نام کاربری لازم است'
        },
        widget=forms.EmailInput(attrs={'class': "form-control", 'type': "text", 'required': "required",
                                       'placeholder': "نام کاربری را وارد کنید"}),
        validators=[
            validators.MinLengthValidator(2),
            validators.MaxLengthValidator(50)
        ]

    )
    password = forms.CharField(
        label='* کلمه عبور :',
        error_messages={
            'required': 'برای ورود به سایت پسورد لازم است'
        },
        widget=forms.PasswordInput(attrs={
            'class': "form-control", 'type': "password", 'required': "required", 'placeholder': "پسورد را وارد کنید"}),
        validators=[
            validators.MinLengthValidator(6),
            validators.MaxLengthValidator(20)
        ]
    )

    remember_me = forms.BooleanField(label='من را به خاطر بسپار', initial=False, required=False,
                                     widget=forms.CheckboxInput(
                                         attrs={'type': "checkbox", 'class': "custom-control-input",
                                                'id': "customCheck1"}))

class UserLogin(View):
    def get(self, request):
        login_form = LoginForm()
        context = {'login_form': login_form}
        return render(request, 'login.html', context)

    def post(self, request: HttpRequest):
        wrong_pass_username = ""
        deactive_user = ""

        login_form = LoginForm(request.POST)

        if login_form.is_valid():
            login_username_enterd = login_form.cleaned_data.get('username')
            login_password_entered = login_form.cleaned_data.get('password')
            remember_me = login_form.cleaned_data.get('remember_me')
            user: Users = Users.objects.filter(username__iexact=login_username_enterd).first()

            if user is not None:
                if not user.is_active:
                    deactive_user = 'حساب کاربری شما فعال نشده است.به ایمیل خود مراجعه کنید'
                else:
                    is_password_corect = user.check_password(login_password_entered)
                    if is_password_corect:
                        login(request, user)
                        request.session.set_expiry(1209600)  # 2 weeks
                        if not remember_me:
                            self.request.session.set_expiry(0)
                        return redirect(reverse('Home_page'))
                    else:
                        wrong_pass_username = 'کاربری با مشخصات بالا یافت نشده'
            else:
                wrong_pass_username = 'کاربری با مشخصات بالا یافت نشده'
        context = {'login_form': login_form, 'wrong_pass_username': wrong_pass_username, 'deactive_user': deactive_user}
        return render(request, 'login.html', context)


{% extends 'share/Master2.html' %}
{% load static %}
{% load widget_tweaks %}
{% block title %}
    ورود به آپشن ویو
{% endblock %}


{% block content %}

    <div class="col-lg-5">
        <div class="card mb-0">
            <div class="card-body">
                <div class="p-2">
                    <h4 class="text-muted float-right font-18 mt-4">ورود به سایت</h4>
                    <div>
                        <a href="{% url 'Home_page' %}" class="logo logo-admin">
                            <img src="{% static 'assets/images/logo_dark.png' %}" height="28" alt="logo"></a>
                    </div>
                </div>

                <div class="p-2">
                    <form class="form-horizontal m-t-20" href="{% url 'Home_page' %}" method="post"
                          action="{% url 'login_page' %}">
                        {% csrf_token %}
                        {{ login_form.username.label }}
                        {{ login_form.username }}
                        {{ login_form.password.label }}
                        {{ login_form.password }}
                        {% if wrong_pass_username %}
                            <div class="notification-list table-danger ">
                                <hr>
                                <p>{{ wrong_pass_username }}</p>
                            </div>

                        {% elif deactive_user %}
                            <div class="notification-list table-danger ">
                                <hr>
                                <p>{{ deactive_user }}</p>
                            </div>
                        {% endif %}

                        <div class="form-group row">
                            <div class="col-1">
                                {% render_field login_form.remember_me type="checkbox" class="custom-control custom-checkbox" id="customCheck1" %}
                            </div>
                            <div class="col-11">
                                {{ login_form.remember_me.label }}
                            </div>
                        </div>

                        <div class="form-group text-center row m-t-20">
                            <div class="col-12">
                                <button class="btn btn-primary btn-block waves-effect waves-light" type="submit">ورود به
                                    سایت
                                </button>
                            </div>
                        </div>

                        <div class="form-group m-t-10 mb-0 row">
                            <div class="col-sm-7 m-t-20">
                                <a href="{% url 'recover_password' %}" class="text-muted"><i class="mdi mdi-lock"></i>رمز
                                    خود را فراموش کردید؟</a>
                            </div>
                            <div class="col-sm-5 m-t-20">
                                <a href="{% url 'register_page' %}" class="text-muted"><i
                                        class="mdi mdi-account-circle"></i>
                                    حساب کاربری بسازید</a>
                            </div>
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>

{% endblock %}

Is ov.example.ir your actual DNS name for your site? I see in ALLOWED_HOSTS you’re also allowing www.ov.example.ir, which if you are, also needs to be included in CSRF_TRUSTED_ORIGINS. Do you have any other DNS names involved here? If so, they may also need to be included in both settings.

1 Like

ov is my subdomain
main domain in other host and this subdomain develope on django and on other host
403 forbidden by this way solved.but why ?

in google chrome
setting>privacy and security>add my url cookies and other site
and clear cache

I’m sorry, if there’s a still a question here, I’m not understanding what you’re asking or what the issue might be.

1 Like