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 = '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):
<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')
scripts.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:
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.
Before the form was on www.shop.com/sell. Now with django-hosts, I set it up so that the form is now on sell.shop.com.
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.
Could this have anything to do with cross domain?