简体   繁体   English

安装 django 主机后,带有 ajax 的 POST 请求不起作用

[英]POST request with ajax not working after installing django hosts

Hello I am just getting acquainted with django hosts which I am trying to set up on an ecommerce website I am building.您好,我刚刚熟悉 django 主机,我正在尝试在我正在构建的电子商务网站上设置它。

So basically I will have the main website - www.shop.com所以基本上我会有主网站 - www.shop.com

And I want to have a subdomain - sell.shop.com - which will be where sellers can register and access their dashboard.我想要一个子域 - sell.shop.com - 卖家可以在其中注册和访问他们的仪表板。

Previously I set the seller website on www.shop.com/sell which is wrong in my opinion.以前我在www.shop.com/sell上设置了卖家网站,我认为这是错误的。

When the seller would register, I was handling the form validation using AJAX.当卖家注册时,我正在使用 AJAX 处理表单验证。 And everything was working properly.一切正常。

Once I installed django hosts and reconfigured the application, I noticed that the AJAX POST request is no longer getting detected.安装 django 主机并重新配置应用程序后,我注意到不再检测到 AJAX POST 请求。 And so, no data is being stored in the DB nor is the validation on the form working.因此,没有数据存储在数据库中,表单的验证也没有工作。

settings.py设置.py

ALLOWED_HOSTS = ['127.0.0.1', 'www.shop.com', '.shop.com',]

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

# Third Party
'django_hosts',
'corsheaders',

# Custom
'pages',
'users',
'vendors',
]

MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_hosts.middleware.HostsResponseMiddleware'
]

ROOT_URLCONF = 'sns.urls'
ROOT_HOSTCONF = 'sns.hosts'
DEFAULT_HOST= 'www'
PARENT_HOST = 'shop.com'
HOST_PORT = '8009'

CORS_ALLOWED_ORIGINS = [
    "http://shop.com:8009",
    "http://sell.shop.com:8009"
]

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

SECURE_CROSS_ORIGIN_OPENER_POLICY = None

Registration Form (html)登记表 (html)

<form id="vendorRegForm1" action="{% host_url 'create_vendor_account' host 'sell' %}" method="POST" data-url="{% url 'create_vendor_account' %}">
                {% csrf_token %}
                <div class="row">
                    <div class="col-md-12">
                        <label for="first_name">First Name:</label>
                        <input type="text" name="first_name" class="form-control" required>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-12">
                        <label for="last_name">Last Name:</label>
                        <input type="text" name="last_name" class="form-control" required>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-12">
                        <label for="email">Email:</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-12">
                        <label for="password">Password:</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-12">
                        <label for="password2">Confirm Password:</label>
                        <input type="password" name="password2" class="form-control" required>
                    </div>
                </div>

                <div class="text-center mt-3">
                    <button id="vendorRegForm1Btn" type="button" class="btn btn-sm btn-blue">
                        <span id="CreateVendorAccount">Create Account</span>
                    </button>
                </div>
                
            </form>

Views.py视图.py

def createVendorAccount(request):

    form = RegisterVendorForm()
    if request.method == "POST":
        password2 = request.POST.get('password2')
        form = RegisterVendorForm(request.POST)
        if form.is_valid():
        
            form.first_name = form.cleaned_data['first_name']
            form.last_name = form.cleaned_data['last_name']
            form.email = form.cleaned_data['email']
            form.password = form.cleaned_data['password']

            if len(form.first_name) == 0:
                return JsonResponse({'status': 'FIRST NAME MISSING',}, safe=False)
            if len(form.last_name) == 0:
                return JsonResponse({'status': 'LAST NAME MISSING',}, safe=False)
            if len(form.email) == 0:
                return JsonResponse({'status': 'EMAIL MISSING',}, safe=False)
            if len(form.email) !=0 and User.objects.filter(email=form.email).exists():
                return JsonResponse({'status': 'EMAIL ALREADY EXISTS',}, safe=False)
            if len(form.password) == 0:
                return JsonResponse({'status': 'PASSWORD MISSING',}, safe=False)
            if len(form.password) < 8:
                return JsonResponse({'status': 'PASSWORD LENGTH'}, safe=False)
            if len(password2) == 0:
                return JsonResponse({'status':'PASSWORD2 MISSING'}, safe=False)
            if form.password != password2:
                return JsonResponse({'status':'PASSWORDS DO NOT MATCH'}, safe=False)

            form1 = form.save(commit=False)
            form1.is_supplier = True
            form1.is_active = True
            form1.save()

            # Redirect
            success_url = current_site.domain + '/register/verify/'
            return JsonResponse({'status':'OK', 'success_url': success_url,}, safe=False)

    return render(request, 'vendors/registration/create_account.html')

scripts.js脚本.js

            // Create Vendor
            $(document).ready(function () {
                var csrf = $("input[name=csrfmiddlewaretoken]").val();

                $('#vendorRegForm1Btn').click(function () {
                    var serializedData = $('#vendorRegForm1').serialize();
                    // $("#CreateVendorAccount").remove();
                    // $(this).html("<span id='CreateVendorAccountSpinner' class='spinner-border spinner-border-sm'></span>");

                    $.ajax({
                    url: $('#vendorRegForm1').data('url'),
                    data: {
                        serializedData,
                        csrfmiddlewaretoken: csrf,
                    },
                    type: 'post',
                    success: function(resp){
                        if (resp.status == 'FIRST NAME MISSING'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                        console.log('Please enter your First Name')
                        toastr.error('Please enter your First Name', 'Error');
                        }
                        else if (resp.status == 'LAST NAME MISSING'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                        toastr.error('Please enter your Last Name', 'Error');
                        }
                        else if (resp.status == 'EMAIL MISSING'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                            toastr.error('Please enter your email address', 'Error');
                        }
                        else if (resp.status == 'EMAIL EXISTS'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                            toastr.error('A user with this email address already exists', 'Error');
                        }
                        else if (resp.status == 'PASSWORD MISSING'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                        toastr.error('Please enter a password', 'Error');
                        }
                        else if (resp.status == 'PASSWORD LENGTH'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                        toastr.error('Password must be at least 8 characters in length', 'Error');
                        }
                        else if (resp.status == 'PASSWORD2 MISSING'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                            toastr.error('Please confirm your password', 'Error');
                        }
                        else if (resp.status == 'PASSWORDS DO NOT MATCH'){
                        // $("#CreateVendorAccountSpinner").remove();
                        // $('#vendorRegForm1Btn').html("<span id='CreateVendorAccount'>Create Account</span>");
                        toastr.error('The passwords do not match', 'Error');
                        }
                        else if (resp.status == 'OK'){
                        setTimeout(function(){
                            window.location.replace(resp.success_url);
                        }, 1500);
                        toastr.success('Account created', 'Success');
                        }
                    }
                    })
                });
            });

urls.py网址.py

from django.urls import path
from . import views

urlpatterns = [
    # Sell page & Vendor login
    path('', views.sell, name="sell"),

    # Auth
    path('login/', views.vendorLogin, name="vendor_login"),
    path('logout/', views.vendorLogout, name="vendor_logout"),

    # Registration steps
    path('register/', views.createVendorAccount, name="create_vendor_account"),
    path('register/verify/', views.verifyVendor, name="verify_vendor"),
    path('register/verify/resend_otp/', views.resendOTP, name="resend_otp"),
    path('register/success/', views.verifyVendorSuccess, name="verify_vendor_success"),

    # Vendor portal
    path('dashboard/', views.vendorDashboard, name="vendor_dashboard"),
]

hosts.py主机.py

from django_hosts import patterns, host
from django.conf import settings
from . import admin_urls

host_patterns = patterns('',
    host(r'www', 'pages.urls', name='www'),
    host(r'sell', 'vendors.urls', name='sell'),
    host(r'admin', admin_urls, name='admin'),
)

The issue here is the validation is not working anymore.这里的问题是验证不再起作用。 When I click on Register with the fields left blank, I get a successful POST request with status 200.当我在字段留空的情况下单击注册时,我收到一个成功的 POST 请求,状态为 200。

However the validation is not working, even if the form is correctly filled, the POST request is not actually storing in the DB.但是验证不起作用,即使正确填写了表单,POST 请求实际上也没有存储在数据库中。

Any help is much appreciated.任何帮助深表感谢。 I have trying to figure this out for weeks now.几周以来,我一直试图弄清楚这一点。

Could this have anything to do with cross domain?这可能与跨域有关吗?

I'm not sure if my answer will solve your problem, because you didn't provide any real error, but give it a try, it once helped me with ajax:我不确定我的回答是否能解决您的问题,因为您没有提供任何真正的错误,但试一试,它曾经帮助我解决了 ajax:

modifed_settings.py : modifed_settings.py

ALLOWED_HOSTS = ['127.0.0.1', 'www.shop.com', '.shop.com',]

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

# Third Party
'django_hosts',
'corsheaders',

# Custom
'pages',
'users',
'vendors',
]

MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_hosts.middleware.HostsResponseMiddleware'
]

ROOT_URLCONF = 'sns.urls'
ROOT_HOSTCONF = 'sns.hosts'
DEFAULT_HOST= 'www'
PARENT_HOST = 'surfnshop.mu'
HOST_PORT = '8009'

CSRF_TRUSTED_ORIGINS = ['127.0.0.1', 'www.shop.com', 'shop.com']
CORS_ORIGIN_ALLOW_ALL=True
CORS_ORIGIN_WHITELIST = [
    "http://surfnshop.mu:8009",
    "http://sell.surfnshop.mu:8009",
    'http://localhost:8000',
    'http://127.0.0.1:8000',
    'http://shop.com'
]

i guess if it worked before you added django-hosts, the problem is in settings but not in code itself我想如果它在你添加 django-hosts 之前有效,问题出在settings而不是代码本身

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

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