I'm trying to retrieve the session data after login but it doesn't seem to be saving the information
.
class getSession(View):
def post(self, request):
print('====================>')
print(request.session.get('usuario'))
sesion = request.session.get('usuario')
return JsonResponse({'nombre': sesion.nombre, 'rut':sesion.rut})
class Login(View):
def post(self, request):
data = json.loads(request.body)
try:
usuario = Usuario.objects.get(rut=data['rut'], password=data['password'])
request.session['usuario'] = {'nombre': usuario.idpersona.name, 'rut': usuario.rut}
request.session.modified = True
#print(self.request.session['usuario'])
return JsonResponse({'usuario':usuario.rut})
except:
return JsonResponse({'usuario':'no existe'})
I'm get this error.
AttributeError: 'NoneType' object has no attribute 'nombre'
I'am using fetch with react.
async login() {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
rut: this.state.rut,
password: this.state.password,
}),
};
const response = await fetch("http://127.0.0.1:8000/test", requestOptions);
const data = await response.json();
if (data.usuario == "no existe") {
mensajeError("RUT o contraseña inválidos.");
} else {
mensajeExitoso("Usuario validado correctamente.");
setTimeout(() => {
window.location.href = "/Inicio";
}, 2000);
}
console.log(data.usuario);
}
try setting SESSION_SAVE_EVERY_REQUEST = True in settings.py
Related
Hello I am getting the mentioned error above in my python flask website
here is the code for adding expenses in my auth.py file
#auth.route('/add_expenses', methods=['GET', 'POST'] )
def adding_new_expenses():
name_user = request.args.get("user")
user = None
if name_user is None:
return redirect (url_for("auth.home"))
else:
form = AddExpense(request.form)
if request.method == 'GET':
return render_template("add_expenses.html", form=form)
else:
user = User.query.filter_by(id=name_user).first()
if user is not None:
if form.validate_on_submit():
new_expense = Expenses(expense_category_name=form.expense_category_name.data,
description_expense=form.description_expense.data,
date_purchase=form.date_purchase.data,
amount=form.amount.data,
user_id=user.id)
db.session.add(new_expense)
db.session.commit()
flash("Expense added successfully.")
return redirect(url_for("auth.home", user = name_user))
and my views.py:
#views.route('/add_expenses', methods=['POST'])
def adding_new_expenses():
data = request.json
name_user = data.get("user")
expense_category_name = data.get('expense_category_name')
description = data.get('description_expense')
date = data.get('date_purchase')
amount = data.get('amount')
if name_user is None or expense_category_name is None or description is None or date is None or amount is None:
return jsonify({"error": "Missing required fields"}), 400
user = session.query(User).filter_by(id=name_user).first()
if user is None:
return jsonify({"error": "User not found"}), 400
new_expense = Expenses(expense_category_name=expense_category_name, description_expense=description,
date_purchase=date,
amount=amount, user_id=user.id)
db.session.add(new_expense)
db.session.commit()
return jsonify({"message": "Expense added successfully."}), 200
and my javascript code:
function adding_new_expenses(name_user, type, description, date, amount) {
fetch("/add_expenses", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name_user: name_user,
expense_category_name: type,
description_expense: description,
date_purchase: date,
amount: amount
})
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("An error occurred while adding the expense.");
}
})
.then(data => {
if (data.message === "Expense added successfully.") {
console.log("Expense added successfully.");
window.location.href = '/home?user=' + name_user;
} else {
console.log(data.error)
}
})
.catch(error => {
console.error(error);
})
}
i can't seem to figure out this error, maybe someone can help me out here.
i am using python flask as my framework, slqalchemy as my database, jinja2 template, bootstrap, and a javascript code
Cannot to sign in, i run localy in docker my container, i can sign-in on my machine and docker no error, but on my remote server i cannot to login, it doesn't write cookie in reponse, have no error, just don't write response. It just redirect me on my page which i setted,and after that i got error, cause i have no my cookie authorization key inside cookie.
video
My SignIn method
#auth_router.post('/signin')
async def sign_in(response: Response, username: str = Form(...), password: str = Form(...), recaptchav3: str = Form(...)) -> dict:
is_human = await verify_recaptcha(recaptchav3)
if is_human['success']:
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid username or password',
)
user_obj = await User_Pydantic.from_tortoise_orm(user)
user_token = await generate_token(user_obj)
response.set_cookie(key="Authorization", value=user_token, httponly=True, secure=True, expires=(8*60*60))
response.headers["Authorization"] = user_token
user.jwt_token = user_token
await user.save()
return {
'access_token': user_token,
'token_type': 'bearer'
}
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid captcha',
)
How i submit my form js
const request = (method, url, data = null, redirectPage) => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(method, url, true)
// xhr.setRequestHeader('Content-Type', 'multipart/form-data')
xhr.onerror = function (event) {
alert(event)
console.log(event);
};
xhr.onload = () => {
if (xhr.status === 200) {
return window.location.href = redirectPage;
return resolve(JSON.parse(xhr.responseText || '{}'))
} else {
alert(`Request failed with status ${xhr.status}`)
reject(new Error(`Request failed with status ${xhr.status}`))
return window.location.reload();
}
}
if (data) {
if (typeof data === 'string' || data instanceof String || typeof data.constructor == Object){
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
}
} else {
xhr.send()
}
})
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData, 'dashboard');
} else{
alert('Перезагрузите страницу');
}
}
})
I cannot understand why using the built-in method in fastapi it does not write on the remote server, it worked on the local one, but I solved the problem by writing. token via js.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(cookieValue) {
var user = getCookie("Authorization");
if (user == "") {
if (cookieValue != "" && cookieValue != null) {
setCookie("Authorization", cookieValue, 365);
}
}
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData);//, 'dashboard');
isLogened.then(result => {
checkCookie(result.access_token);
return window.location.href = 'dashboard';
}, result => {
log('Cant get response')
});
} else{
alert('Перезагрузите страницу');
}
}
})
I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new r (https://js.stripe.com/v3/:1:6143)
at Js (https://js.stripe.com/v3/:1:165350)
at $s (https://js.stripe.com/v3/:1:165646)
at https://js.stripe.com/v3/:1:166758
at Qs (https://js.stripe.com/v3/:1:166769)
at nc (https://js.stripe.com/v3/:1:167275)
at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030)
at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39
Here's the Vue.js method responsible for this:
<script src="https://js.stripe.com/v3/"></script>
<script>
const PlansApp = {
data() {
return {
}
},
delimiters: ['[[', ']]'],
methods: {
subscribe(plan) {
console.log('Subscribe:', plan);
const stripe = Stripe('{{ stripe_pub_key }}');
fetch('/dashboard/myaccount/teams/api/create_checkout_session/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({
'plan': plan
})
})
.then(function(response) {
return response.json()
})
.then(function(session) {
console.log(session)
return stripe.redirectToCheckout({ sessionId: session.sessionId })
})
.then(function(result) {
if (result.error) {
console.log('Error:', result.error.message)
}
})
.catch(function(error) {
console.log('Error:', error);
});
}
}
}
Vue.createApp(PlansApp).mount('#plans-app')
</script>
And here's the Django code that creates the session on the backend:
#login_required
def create_checkout_session(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
data = json.loads(request.body)
plan = data['plan']
if plan == 'basic':
price_id = settings.STRIPE_BASIC_PRICE_ID
else:
price_id = settings.STRIPE_PRO_PRICE_ID
try:
checkout_session = stripe.checkout.Session.create(
client_reference_id = request.user.userprofile.active_team_id,
success_url = '%s%s?session_id={CHECKOUT_SESSION_ID}' % (settings.WEBSITE_URL, reverse('team:plans_thankyou')),
cancel_url = '%s%s' % (settings.WEBSITE_URL, reverse('team:plans')),
payment_method_types = ['card'],
mode = 'subscription',
line_items = [
{
'price': price_id,
'quantity': 1
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
I'm struggling to find out why I'm getting the error that I'm getting and would be grateful for any help!
I guest the problem come from the 'success_url' and the 'cancel_url'.
Try to add http:// or https:// in your url
Cordially
how I can modify my code that be check login&password without refreshing? Ajax call function in django to check login and password then send .json with result. Next one I want display error in js if result is failed or play animation if it's true.
js code:
function CheckBeforeSend()
{
var LoginInput = document.getElementById('flogin');
if(LoginInput.value.match(/^[a-zA-Z]+['.']+[a-zA-Z]+[0-9]+$/) == null)
{
if(document.getElementById('Windows').childElementCount > 2)
{
document.getElementById('Windows').children[0].remove();
}
AddPicture("paperJsConn");
}
else
{
document.getElementById("button").type = "submit";
$.ajax({
url: 'http://127.0.0.1:8000/',
data: $('#login_form').serialize(),
type: "POST",
async:false,
success: function(response) {
var CheckingCorrect = response['result'];
//if checkingcorrect play func animation.
},
error: function(error){
alert('No Connection!');
}
});
}
}
$('#login_form').submit(function(e){
e.preventDefault();
$.post('view-url', $(this).serialize());
}); // this event dont work.
views.py:
def Logget(request):
if request.method == 'POST':
login = request.POST.get('flogin')
response_data = {}
response_data['result'] = 'Failed'
lengthBase = UsersLog.objects.count()
for i in range(lengthBase):
if login == str(UsersLog.objects.get(id=i+1)):
password = request.POST.get('lpass', False)
if str(password) == str(UsersLog.objects.get(id=i+1).password):
response_data['result'] = 'Succes'
break
return JsonResponse(response_data)
return render(request, 'index.html')
I'm trying to upload a picture to my server with some additional data. My angularJs code is that:
function create_question(question, callback){
var form = new FormData()
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"processData": false,
"data": form
}
$cordovaFile.readAsDataURL(cordova.file.dataDirectory, question.name)
.then(function (success) {
form.append("file", success)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(Utf8Decode(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}
In my server, I have that view:
#parser_classes((MultiPartParser, ))
class CreateQuestion(APIView):
def post(self, request, format=None):
picture = request.data['file']
question_id = request.data['question_id']
project_id = request.data['project_id']
options = request.data['options']
title = request.data['title']
correct_option = request.data['correct_option']
username = request.user.username
project = Project.objects.get(project_id=project_id)
if project.owner_user.username == username:
ext = '.jpg'
aws = AWSClient()
picture_name = question_id + ext
picture_url = aws.put(picture, 'question_pictures', picture_name)
question = Question.objects.create(question_id=question_id, title=title,
picture_url=picture_url, options=options, owner_project=project,
correct_option=correct_option)
project.question_count += 1
project.picture_url = picture_url
project.save()
serializer = QuestionSerializer(question, context={"request": request})
return JsonResponse(serializer.data)
else:
return JsonResponse({"result": "fail"})
After I made the request, question was created and the picture file was uploaded to Amazon S3. However, I could not open the resulting file in my pc. Where am I doing mistake?
After a long search on the internet, I found the answer. First, I read file with
$cordovaFile.readAsArrayBuffer(directory,filename)
After that, I created a Blob object with the file:
var imgBlob = new Blob([success], { type: "image/jpeg" } );
My final angularJS code is:
function create_question(question, callback){
var form = new FormData()
$cordovaFile.readAsArrayBuffer(cordova.file.dataDirectory, question.name)
.then(function (success) {
var imgBlob = new Blob([success], { type: "image/jpeg" } );
form.append("file", imgBlob)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"filename": question.id,
"processData": false,
"data": form,
"file": success,
"filename": "file"
}
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(JSON.stringify(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}