I wanted to pass a file along with other text data from react to django and so I used the FormData() class and axios to post the request to DRF. The React code :
import React, { useEffect, useState } from "react";
import "../styling/AptitudeTest.css";
import Timer from "../components/Timer";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";
function AptitudeTest() {
const navigate = useNavigate();
const [lkdn, setLkdn] = useState("");
const [selectedFile, setSelectedFile] = useState();
const location = useLocation();
const [qs, setQs] = useState([]);
const onFileChange = (event) => {
setSelectedFile(event.target.files[0]);
};
useEffect(() => {
const data = async () =>
await axios
.get(`http://127.0.0.1:8000/comp/test/${location.state.id}`)
.then((res) => {
setQs(res.data.jsonData);
})
.catch((e) => console.log(e));
data();
}, []);
function submitHandler(e) {
e.preventDefault();
let c = 0,
total = 0;
var checkboxes = document.querySelectorAll("input[type=radio]:checked");
for (var i = 0; i < checkboxes.length; i++) {
c = c + parseInt(checkboxes[i].value);
total = total + 2;
}
let formData1 = new FormData();
formData1.append("Content-Type","multipart/form-data")
formData1.append(
"cid",
JSON.parse(localStorage.getItem("uData"))["cand_email"]
);
formData1.append("testid", location.state.id);
formData1.append("linkedin", "asasdads");
formData1.append("score", Math.ceil((c * 100) / total));
formData1.append("cv", selectedFile);
formData1.append("compid", location.state.compid);
axios
.post("http://localhost:8000/cand/response/",formData1)
.then((res) => {
navigate("/records2");
})
.catch((err) => {
console.log(err);
});
}
return (
<div className="container">
<h4 className="tit">J.P Stan and Co. - Data Analyst</h4>
<Timer hours="0" minutes="60" />
<form onSubmit={submitHandler}>
{qs.map((q) => {
return (
<div className="c card">
<div className="ch card-header">{q.question}</div>
<div className="card-body">
<input
type="radio"
id={"option1"}
name={q.question}
value={q.option1.marks}
/>
<label htmlFor={q.question}> {q.option1.title} </label>
</div>
<div className="card-body">
<input
type="radio"
id={"option2"}
name={q.question}
value={q.option2.marks}
/>
<label htmlFor={q.question}> {q.option2.title} </label>
</div>
<div className="card-body">
<input
type="radio"
id={"option3"}
name={q.question}
value={q.option3.marks}
/>
<label htmlFor={q.question}> {q.option3.title} </label>
</div>
<div className="card-body">
<input
type="radio"
id={"option4"}
name={q.question}
value={q.option4.marks}
/>
<label htmlFor={q.question}> {q.option4.title} </label>
</div>
</div>
);
})}
<div className="card">
<div className="card-header">Upload your CV.</div>
<div className="card-body">
<input name="cv" type="file" onChange={onFileChange} />
</div>
</div>
<div className="card">
<div className="card-header">Add your Linkedin.</div>
<div className="card-body">
<input
type="text"
name="op"
className="form-control"
id="op"
placeholder="https://www.linkedin.com/in/bhoomika-valani-695b22199/"
/>
</div>
</div>
<input
onClick={submitHandler}
type="submit"
value="Submit"
className="btn btn-primary btn-lg btn-block"
/>
</form>
</div>
);
}
export default AptitudeTest;
The request being sent is an XMLHTTPRequest which I cannot figure out how to parse it. The django code:
class ResponseAction(APIView):
parser_classes = [FormParser, MultiPartParser]
#csrf_exempt
def get(self, request, *args, **kwargs):
resp_objs = Response1.objects.filter(**request.data)
list0 = []
for resp_obj in resp_objs:
dict1 = model_to_dict(resp_obj)
candname = Candidate.objects.get(cand_email = resp_obj.cid)
dict1['cand_name'] = candname
list0.append(dict1)
return JsonResponse(list0,safe=False)
#csrf_exempt
def post(self, request, *args, **kwargs):
serializer1 = ResponseSerializer(data = request.data)
if serializer1.is_valid():
resp_obj = Response1.objects.filter(cid=request.data['cid'],testid=request.data['testid'])
if not resp_obj.exists():
serializer1.save()
print("stored")
else:
print(serializer1.errors)
return Response(serializer1.data)
When I tried printing the request.data the output is such
<QueryDict: {'------WebKitFormBoundarywCHXwKecZPVgYxxN\r\nContent-Disposition: form-data; name': ['"Content-Type"\r\n\r\nmultipart/form-data\r\n------WebKitFormBoundarywCHXwKecZPVgYxxN\r\nContent-Disposition: form-data; name="cid"\r\n\r\nb#gmail.com\r\n------WebKitFormBoundarywCHXwKecZPVgYxxN\r\nContent-Disposition: form-data; name="testid"\r\n\r\n1\r\n------WebKitFormBoundarywCHXwKecZPVgYxxN\r\nContent-Disposition: form-data; name="linkedin"\r\n\r\nasasdads\r\n------WebKitFormBoundarywCHXwKecZPVgYxxN\r\nContent-Disposition: form-data; name="score"\r\n\r\n0\r\n------WebKitFormBoundarywCHXwKecZPVgYxxN\r\nContent-Disposition: form-data; name="cv"; filename="zs.docx"\r\nContent-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document\r\n\r\nPK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x002\x91oWf\x01\x00\x00¥\x05\x00\x00\x13\x00\x08\x02[Content_Types].xml ¢\x04\x02(\xa0\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.....
.. represents more xml data. Can anyone help me or suggest me an alternative method to sent files and text from react to DRF. Thanks in advance
Related
I am working on this problem and somehow resolved it to a very great extent and almost everything is done. But the Django is rendering my template but not the Context.
I don't know why I have checked it by debugging and my context is rendering but not showing in frontend.
On this template, there is a form with 4 fieldset , I am submitting data in 1st fieldset and the dynamically show o/p accordingly on the second fieldset.
I am attaching screenshot to show what is rendering in template(2nd fieldset)
edit:
I have debugged this and in code all is working fine but it is not showing up in fornt-end, I dont know why
#views.py
def createQuotePage(request):
if request.method == "POST":
# Getting all the value
# saving in Table
saveInUnitsTable(-------some code, removed to shorten question ------)
saveInCustomerTable(-------some code, removed to shorten question ------)
saveInInquiryTable(-------some code, removed to shorten question ------)
flight_suggestions =Flight.objects.filter(sourceairportid=1,destinationairportid=51)
context = {'flight_suggestions':flight_suggestions,"test":"99999999999999999999999999999999999999"}
return render(request,"Freight/create_quote.html",context=context) # <-- here is the PROBLEM
if request.method == "GET":
print("========================GET=======================")
context = {'airport_data' : list(Airport.objects.all()),
'commodity_data':list(Commodity.objects.all()),
'customerType_data':list(Entity.objects.all()),
}
return render(request,"Freight/create_quote.html",context=context)
#scripts.js
(function($) {
"use strict";
$.backstretch;
$('#top-navbar-1').on('shown.bs.collapse', function(){
$.backstretch("resize");
});
$('#top-navbar-1').on('hidden.bs.collapse', function(){
$.backstretch("resize");
});
$('.f1 fieldset:first').fadeIn('slow');
$('.f1 .btn-next').on('click', function() {
//
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('.f1').find('.f1-step.active');
var progress_line = $(this).parents('.f1').find('.f1-progress-line');
//
var formData1 = $("#total-shipment-form").serialize();
var formData2 = $("#units-form").serialize();
var formData3 = $("#customerDetailForm").serialize();
var formData4 = $("#firstFieldset").serialize();
var formData = formData1 + '&' +
formData2 + '&' +
formData3 + '&' +
formData4
$.post("",formData)
.done(function(){
//
console.log('Success : ');
// var parent_fieldset = $(this).parents('fieldset');
// var next_step = true;
// var current_active_step = $(this).parents('.f1').find('.f1-step.active');
// var progress_line = $(this).parents('.f1').find('.f1-progress-line');
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('.f1'), 20 );
});
}
//
})
.fail(function(){
console.log('Error : ');
});
});
Edited:-
Html template
<fieldset id="secondFieldset">
<div class="form-group select_all_style">
<input class="form-check-input" type="checkbox" value=""
id="select_all">
<label for="select_all" class="font-bold lh-26 fs-14">Select All</label>
</div>
{{test}}
<div class="airline_wrapper check_box_wrapper">
{{test}}
{% for flight in flight_suggestions %}
<div class="col_2 text-center dhl_text ">
<div class="aviation_wrapper">
<div class="aviation_checkbox">
<input class="form-check-input" type="checkbox" value=""
id="flexCheckDefault">
</div>
<div class="d-inline pl_10">
<!-- <p>Expiry Date <span><b>6 Sep 2022</b></span></p> -->
<h4 class="fw-400 fs-28">{{flight.flightcompany}}</h4>
<p>Air Freight</p>
</div>
</div>
</div>
<div class="col_6">
<div class="flight_container text-center">
<i class="fa-solid fa-plane plane_style"></i>
<div class="flight_details"></div>
<div class="flight_content">
<div>
<h4>{{flight.sourceairportid.airportname}}</h4>
<p>{{flight.sourceairportid.cityid.cityname}}</p>
</div>
<div>
<h4>{{flight.destinationairportid.airportname}}</h4>
<p>{{flight.destinationairportid.cityid.cityname}}</p>
</div>
</div>
<hr>
<div class="d-flex">
<div class="flight_sub_text text-left">
<label for="">Transit Time</label>
<h5>-- Hrs</h5>
<h5>{{flight.trasittime}} Hrs</h5>
</div>
</div>
</div>
</div>
<div class="col_3">
<h4 class="text-center reference_text">Past Reference</h4>
<div class="buy_text_wrapper">
<p>Buy Rate</p>
<p>Sell Rate</p>
</div>
<div class="buy_text_wrapper">
<p>USD 5,500.00</p>
<p>USD 7,000.00</p>
</div>
<h5 class="probabilty_text text-center pt-4"><span><i
class="fa-solid fa-arrow-trend-up"></i> 70%</span>
Winnning Probabilty</h5>
</div>
{% endfor %}
</div>
<div class="f1-buttons">
<button class="btn btn-primary btn-next" type="button">Request Better
Rates</button>
</div>
</fieldset>
form.html
<form>
{% csrf_token %}
<table>
<tr>
<td>
<label for="name">NAME: </label>
<input type="text" data-bind="value: $data.name" name="name" class="form-control" id="name" placeholder="name of product">
</td>
</tr>
<tr>
<td>
<label for="price">PRICE </label>
<input type="text" name="price" data-bind="value:$data.price" class="form-control" id="price" placeholder="price">
</td>
</tr>
<tr>
<td>
<label for="description">DESCRIPTION: </label>
<textarea cols="10" rows="5" name="description" data-bind="value:$data.description" class="form-control" id="description" placeholder="product description"></textarea>
</td>
</tr>
<tr>
<td>
<label for="image">IMAGE: </label>
<input type="file" class="form-control-file" id="image" name="image" required>
</td>
</tr>
<tr><td><button type="button" id="submit" data-bind="click : save" class="btn btn-success">Submit</button></td></tr>
</table>
</form></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
<!-- <script type="application/javascript" src="static/js/knockout-file-bind.js"></script> -->
<script>
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
</script>
<script>
var ViewModel = function () {
var self = this;
self.save = function () {
var formdata = new FormData();
formdata.append('image', $('#image').get(0).files[0]);
formdata.append('name', ko.observable(""));
formdata.append('price', ko.observable(""));
formdata.append('description', ko.observable(""));
console.log(formdata)
$.ajax({
type: 'POST',
url: "{% url 'addProduct' %}",
data: formdata,
headers: {'X-CSRFToken': csrftoken},
processData: false,
contentType: false,
success: function (){
alert('The post has been created!')
},
error: function () {
alert("fail");
}
});
};
};
ko.applyBindings(new ViewModel())
</script>
</body>
</html>
views.py
def productform(request):
return render(request, 'app/product_form.html')
class ProductCreateView(CreateView):
model = Product
fields = ['name', 'price', 'description', 'image']
success_url=reverse_lazy('create-form')
def addProduct(request):
if request.method == "POST":
product=Product()
product.name = request.POST['name']
product.description = request.POST['description']
product.price = request.POST['price']
if len(request.FILES) != 0:
if len(product.image) > 0:
os.remove(product.image.path)
product.image = request.FILES['image']
product.save()
return render(request, 'app/product_form.html')
else:
return render(request, 'app/product_form.html')
# def get_success_url(self):
# return reverse('successlist')
def detail_view(request, id):
context ={}
context["data"] = Product.objects.get(id = id)
return render(request, "detail_view.html", context)
Image is not saving in database django I don't know what is the issue but image file name is displaying in console.log in ajax. Issue is image is not saving to database
When i try to print(request.FILES) it shows multidict is empty
I have given html code views code please check
Please help me to solve this
Thanks in advance
in your form.html try adding
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
# the rest of your code
</form>
If you're using a formdata object in an $.ajax request you must set the data field to that formdata object.
Also all the fields must be in it, append all to fields into it when you're making the ajax request not before.
self.save = function () {
var formdata = new FormData();
formdata.append('image', $('#image').get(0).files[0]);
formdata.append('name', ko.observable(""));
formdata.append('price', ko.observable(""));
formdata.append('description', ko.observable(""));
$.ajax({
type: 'POST',
url: "{% url 'addProduct' %}",
data: formdata,
headers: {'X-CSRFToken': csrftoken},
processData: false,
contentType: false,
success: function (){
alert('The post has been created!')
},
error: function () {
alert("fail");
}
});
};
I am using django with VueJS. The data is updating properly in my database.
I need to accomplish two things:
Post the correct content to the field image_file.
Get the downloaded image file pasted onto the servers folder which is media/shop/images
My attempted code is as below:
models.py
...
image_file = models.ImageField(upload_to='shop/images/', blank=True, null=True)
urls.py
...
urlpatterns += [
url(r'^Post-Items-Axios$', myviews.Post_Items_Axios, name='Post-Items-Axios'),
]
views.py
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
def Post_Items_Axios(request):
if request.method == 'POST':
data_itemfullhd = request.data['Item Name']
data_image_file = request.data['Item Image File']
td_items, created = Md_Items.objects.get_or_create(
itemfullhd = data_itemfullhd)
td_items.imagefl = data_imagefl
td_items.image_file = data_image_file
td_items.save()
data = { 'data_itemfullhd': data_itemfullhd }
return Response(data)
bm_home.html
<template id="product-edit">
<div>
<h2>Product details</h2>
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="form-group">
<label for="edit-name">Item Name</label>
<input class="form-control" id="edit-name" v-model="product.itemfullhd" required/>
</div>
<!-- Upload single Image files -->
<div class="form-group">
<label for="edit-imagefile">Image</label>
<input type="file" id="edit-imagefile" #change="onFileChanged" required/>
</div>
<button type="submit" class="btn btn-primary" #click.prevent="updateProduct">Save</button>
<a class="btn btn-dark"><router-link to="/product-list">Cancel</router-link></a>
</form>
</div>
</template>
Vue template
var ProductEdit = Vue.extend({
template: '#product-edit',
data: function () {
return {
product: findProduct(this.$route.params.product_id),
selectedImage: null,
};
},
methods: {
onFileChanged (event) {
this.selectedImage = event.target.files[0]
this.product.image_file = this.selectedImage.name
},
updateProduct: function () {
let product = this.product;
products[findProductKey(product.id)] = {
id: product.id,
itemfullhd: product.itemfullhd,
image_file: product.image_file,
};
const data = {
"Item Name": product.itemfullhd,
"Item Image File": product.image_file,
}
// const formData = new FormData()
// formData.append('image_file', this.selectedImage, this.selectedImage.name)
// axios.post('/biggmount_home/Post-Items-Axios', formData, data)
axios.post('/biggmount_home/Post-Items-Axios', data)
router.push('/product-list');
},
}
});
The changes below have given me the result that I was looking to achieve:
Vue template
var ProductEdit = Vue.extend({
template: '#product-edit',
data: function () {
return {
product: findProduct(this.$route.params.product_id),
selectedImage: null,
};
},
methods: {
onFileChanged (event) {
this.selectedImage = event.target.files[0]
},
updateProduct: function () {
let product = this.product;
const formData = new FormData()
formData.append('Item Image', this.selectedImage, this.selectedImage.name)
formData.append('Item Name', product.itemfullhd)
axios.post('/biggmount_home/Post-Items-Axios', formData)
router.push('/product-list');
},
}
});
views.py
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
def Post_Items_Axios(request):
if request.method == 'POST':
data_itemfullhd = request.data['Item Name']
td_items, created = Md_Items.objects.get_or_create(
itemfullhd = request.data['Item Name'],
)
td_items.image_file = request.data['Item Image']
td_items.save()
return HttpResponse('Success!')
I'm sharing my main.js, controller.js, home_page.html, index.html file below. Please some one help me fix the issue which is, when i was in the home page ('127.0.0.1:8000/home/') and try to refresh the page im getting only the html page and all the contents in the rootScope or scope disappears. But this is usual but i don't know how to again gain the data from the controller.
main.js
$stateProvider
.state("base", {
url : "/",
views : {
"main-content" : {
controller : "baseController",
template : "<div ui-view='content'></div>"
}
}
})
.state("base.login", {
url : "account/login/",
views : {
"content" : {
controller : "loginController",
templateUrl : "/account/login/"
}
}
})
.state("base.register", {
url : "account/register/",
views : {
"content" : {
controller : "registerController",
templateUrl : "/account/register/"
}
}
})
.state("base.home", {
url : "home/",
views : {
"content" : {
controller : "homeController",
templateUrl : "/home/"
}
}
})
.state("base.changepassword", {
url : "settings/",
views : {
"content" : {
controller : "changePasswordController",
templateUrl : "/settings/"
}
}
})
controller.js
myApp.controller('homeController', ['$http', '$scope', '$window', '$rootScope', function($http, $scope, $window, $rootScope) {
// debugger;
if (! $rootScope.currentUser.first_name) {
var search_payload = {
"email": $rootScope.currentUser.email
};
$http({
url: '/api/current/user/',
method: "POST",
data : search_payload,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then(function(response) {
$rootScope.currentUser = response.data;
console.log("Current User - ", $rootScope.currentUser);
});
}
$scope.clear_cookie = function ($event) {
$event.preventDefault();
console.log("Clear Cookie");
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 21 Jun 2018 12:00:00 GMT";
}
$http({
url: '/api/logout/',
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then(function(response) {
console.log(response);
if (response.data.status == 'success') {
window.location = '/';
}
});
};
$scope.submit = function ($event, currentUser, isValid) {
$event.preventDefault();
if (isValid) {
var search_payload = {
"update": "true",
"username": currentUser.username,
"first_name": currentUser.first_name,
"last_name": currentUser.last_name,
"age": currentUser.age,
"email": currentUser.email,
"mobile": currentUser.mobile,
"address": currentUser.address
};
console.log(search_payload);
$http({
url: '/api/current/user/',
method: "POST",
data : search_payload,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then(function(response) {
$rootScope.currentUser = response.data;
console.log("Current User - ", $rootScope.currentUser);
if(response.data.status == 'success') {
swal({
title: "Success",
text: "Successfully updated your profile.",
icon: "success",
button: "Okay!",
});
} else {
swal({
title: "Failed",
text: "Something went wrong sorry please try again after sometime.",
icon: "error",
button: "Okay!",
});
}
});
} else {
swal({
title: "Failed",
text: "Please correct the errors and submit the form.",
icon: "error",
button: "Okay!",
});
}
}
}]);
home_page.html
<div class="login_form_class" ng-if="currentUser.username">
<form name="updateForm">
{% csrf_token %}
<div name="login_form" class="login_form col-md-4">
<div class="header">PROFILE</div>
<hr/>
<label class="input_label col-md-5" for="username">USERNAME</label>
<input class="input_box col-md-7" type="text" id="username" name="username" ng-init="username='{$ currentUser.username $}'" ng-model="currentUser.username" placeholder="{$ currentUser.username $}" value="{$ currentUser.username $}" pattern="[a-zA-Z0-9]+"/>
<div role="alert">
<span class="error error_msg pull-right" ng-show="updateForm.username.$error.pattern">Must contain only alphanumeric Special characters are not allowed</span>
</div>
<br/>
<label class="input_label col-md-5" for="first_name">FIRST NAME</label>
<input class="input_box col-md-7" type="text" id="first_name" name="first_name" ng-init="first_name='{$ currentUser.first_name $}'" ng-model="currentUser.first_name" placeholder="{$ currentUser.first_name $}" value="{$ currentUser.first_name $}" pattern="[A-Za-z]+"/>
<div role="alert">
<span class="error error_msg pull-right" ng-show="updateForm.first_name.$error.pattern">Must contain only alphabets</span>
</div>
<br/>
<label class="input_label col-md-5" for="last_name">LAST NAME</label>
<input class="input_box col-md-7" type="text" id="last_name" name="last_name" ng-init="last_name='{$ currentUser.last_name $}'" ng-model="currentUser.last_name" placeholder="{$ currentUser.last_name $}" value="{$ currentUser.last_name $}" pattern="[a-zA-Z]+"/>
<div role="alert">
<span class="error error_msg pull-right" ng-show="updateForm.last_name.$error.pattern">Must contain only alphabets</span>
</div>
<br/>
<label class="input_label col-md-5" for="age">AGE</label>
<input class="input_box col-md-7" type="text" id="age" name="age" ng-init="age='{$ currentUser.age $}'" ng-model="currentUser.age" placeholder="{$ currentUser.age $}" value="{$ currentUser.age $}" ng-minlength="2" ng-maxlength="2" pattern="[0-9]{2}"/>
<div role="alert">
<span class="error error_msg pull-right" ng-show="updateForm.age.$error.minlength">Must have a number</span>
<span class="error error_msg pull-right" ng-show="updateForm.age.$error.maxlength">Must be two digit</span>
<span class="error error_msg pull-right" ng-show="updateForm.age.$error.pattern">Must be an integer</span>
</div>
<br/>
<label class="input_label col-md-5" for="email">EMAIL</label>
<input class="input_box col-md-7" type="email" id="email" ng-init="email='{$ currentUser.email $}'" ng-model="currentUser.email" placeholder="{$ currentUser.email $}" value="{$ currentUser.email $}" disabled/>
<br/>
<label class="input_label col-md-5" for="mobile">MOBILE</label>
<input class="input_box col-md-7" type="text" id="mobile" name="mobile" ng-init="mobile='{$ currentUser.mobile $}'" ng-model="currentUser.mobile" placeholder="{$ currentUser.mobile $}" value="{$ currentUser.mobile $}" ng-minlength="10" ng-maxlength="10" pattern="[0-9]{10}" />
<div role="alert">
<span class="error error_msg pull-right" ng-show="updateForm.mobile.$error.minlength">Must contain 10 digits</span>
<span class="error error_msg pull-right" ng-show="updateForm.mobile.$error.maxlength">Must contain only 10 digits</span>
<span class="error error_msg pull-right" ng-show="updateForm.mobile.$error.pattern">Must contain only numbers</span>
</div>
<br/>
<label class="input_label col-md-5" for="address">ADDRESS</label>
<textarea class="input_box col-md-7" id="address" ng-init="address='{$ currentUser.address $}'" ng-model="currentUser.address" placeholder="{$ currentUser.address $}">{$ currentUser.address $}</textarea>
<br/>
<button type="submit" class="btn btn-info update_btn" ng-click="submit($event, currentUser, updateForm.$valid)">SAVE CHANGES</button>
</div>
</form>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
var cookie = document.cookie.split('=')[1];
var search_payload = {
"email": cookie.split(';')[0]
};
var promise = $.ajax({
url: '/api/current/user/',
method: 'POST',
data: search_payload
});
promise.done(function(response) {
// $rootScope.currentUser = response;
console.log(response);
});
</script>
</div>
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<body>
<div class="content_panel" ui-view="main-content"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-animate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-aria.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-messages.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.6/angular-material.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.18/angular-ui-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-resource.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-sanitize.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
var csrftoken = Cookies.get('csrftoken');
var myApp = angular.module('myApp', ['ngRoute', 'ngResource', 'ngMaterial', 'ngMessages', 'ngSanitize', 'ui.router']);
</script>
<script src="{% static 'main.js' %}"></script>
<script src="{% static 'controllers.js' %}"></script>
</html>
hope all is well. I am trying to install Opencart (2.0.3) into a subdirectory (Ie. www.website.com/shop/) I want the root URL www.website.com to go to a Login page, where once a user logs in. It will redirect them to the /shop/ portion of the site and allow them to continue their business. I was wondering what the easiest way was to accomplish this. Would I install everything in the root folder, and then modify the .htaccess file along with the config files? Then how would i Make the login files work in the root folder? I tried installing everything first into the subdirectory /shop/... but then I get issues trying to figure out how to get files in the root folder to work.
Thanks in advance!
Yes, need to work with ajax functionality as below. In the index.php insert the following code and replace URL_WITH_SHOP with your urlshop. Then I have taken "shop" as sub-folder installation if it is different then replace "shop" with your sub-folder name:
<script src="shop/catalog/view/javascript/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="shop/catalog/view/javascript/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div id="content" class="col-sm-12 ">
<div class="row ">
<div class="col-sm-6" style="margin: 0px auto; float: none;">
<div class="well">
<h2>Returning Customer</h2>
<p><strong>I am a returning customer</strong></p>
<form method="post" enctype="multipart/form-data">
<div class="error"></div>
<div class="form-group">
<label class="control-label" for="input-email">E-Mail Address</label>
<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control" />
</div>
<div class="form-group">
<label class="control-label" for="input-password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="input-password" class="form-control" />
</div>
<button type="button" id="button-cart" data-loading-text="Checking login" class="btn btn-primary ">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript"><!--
$('#button-cart').on('click', function() {
$.ajax({
url: 'shop/index.php?route=account/loginajax',
type: 'post',
data: $('input[type=\'text\'], input[type=\'password\']'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
$('.error').after('<div class="alert alert-danger has-error">' + json['error'] + '</div>');
}
if (json['success']) {
$('.error').after('<div class="alert alert-success">' + json['success'] + '</div>');
window.location = "URL_WITH_SHOP";
}
}
});
});
//--></script>
Above is the presentation layer, now let's make the logical layer, go to shop/catalog/controller/account and create loginajax.php and paste following code:
<?php
class ControllerAccountLoginAjax extends Controller
{
private $error = array();
public function index()
{
$this->load->model('account/customer');
$json = array();
// Login override for admin users
if (!empty($this->request->get['token'])) {
$this->event->trigger('pre.customer.login');
$this->customer->logout();
$this->cart->clear();
unset($this->session->data['wishlist']);
unset($this->session->data['payment_address']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['shipping_address']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
$customer_info = $this->model_account_customer->getCustomerByToken($this->request->get['token']);
if ($customer_info && $this->customer->login($customer_info['email'], '', true)) {
// Default Addresses
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
$this->event->trigger('post.customer.login');
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
}
if ($this->customer->isLogged()) {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
if (!$json) {
$this->load->language('account/login');
$this->document->setTitle($this->language->get('heading_title'));
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$json['success'] = "Successfully logging in! ";
unset($this->session->data['guest']);
// Default Shipping Address
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
// Add to activity log
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $this->customer->getId(),
'name' => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
);
$this->model_account_activity->addActivity('login', $activity_data);
}
else{
$json['error'] = $this->language->get('error_login');
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('account/account', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_login'),
'href' => $this->url->link('account/login', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_new_customer'] = $this->language->get('text_new_customer');
$data['text_register'] = $this->language->get('text_register');
$data['text_register_account'] = $this->language->get('text_register_account');
$data['text_returning_customer'] = $this->language->get('text_returning_customer');
$data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
$data['text_forgotten'] = $this->language->get('text_forgotten');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_password'] = $this->language->get('entry_password');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_login'] = $this->language->get('button_login');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = $this->url->link('account/login', '', 'SSL');
$data['register'] = $this->url->link('account/register', '', 'SSL');
$data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
} else {
$data['email'] = '';
}
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
} else {
$json['error'] = $this->language->get('error_login');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
protected function validate() {
$this->event->trigger('pre.customer.login');
// Check how many login attempts have been made.
$login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']);
if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
$this->error['warning'] = $this->language->get('error_attempts');
}
// Check if customer has been approved.
$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
if ($customer_info && !$customer_info['approved']) {
$this->error['warning'] = $this->language->get('error_approved');
}
if (!$this->error) {
if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
$this->error['warning'] = $this->language->get('error_login');
$this->model_account_customer->addLoginAttempt($this->request->post['email']);
} else {
$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
$this->event->trigger('post.customer.login');
}
}
return !$this->error;
}
}
This will help you.
Download files and folders for above codes
Hope it also help you
If you just want the login page then here is the tricks, create index.php or index.html at root folder then paste the following code and change URL_WITH_SHOP in the code with your url with shop like "http://www.example.com/shop" :
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div id="content" class="col-sm-12 ">
<div class="row ">
<div class="col-sm-6" style="margin: 0px auto; float: none;">
<div class="well">
<h2>Returning Customer</h2>
<p><strong>I am a returning customer</strong></p>
<form action="URL_WITH_SHOP/index.php?route=account/login" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="input-email">E-Mail Address</label>
<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control" />
</div>
<div class="form-group">
<label class="control-label" for="input-password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="input-password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn btn-primary" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
The issue will be if the customer enters wrong username and password then it redirects to the actual login page.