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.
So basically I will have the main website - www.shop.com
And I want to have a subdomain - sell.shop.com - which will be where sellers can register and access their dashboard.
Previously I set the seller website on www.shop.com/sell which is wrong in my opinion.
When the seller would register, I was handling the form validation using 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. And so, no data is being stored in the DB nor is the validation on the form working.
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'
CORS_ALLOWED_ORIGINS = [
"http://surfnshop.mu:8009",
"http://sell.surfnshop.mu: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)
<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
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')
urls.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
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.
However the validation is not working, even if the form is correctly filled, the POST request is not actually storing in the DB.
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:
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