I am getting error while creating customer
AuthenticationError at /vissa/assign-plan/
My js
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
{% if cust %}
$(document).ready(function() {
braintree.setup("{{ client_token }}", "dropin", {
container: "checkout",
form: "checkoutForm"
});
$("#submitPayment").on("click", function () {
$("button").off("click");
$("a").off("click");
$('body').off("click");
var btn = $(this).button("loading")
setTimeout(function () {
btn.button('reset');
}, 3500)
});
});
</script>
{% endif %}
And client token i am trying to get in context processor.
def payment_data(request):
try:
userone = UserProfile.objects.get(user=request.user)
indi_user = IndividualUser.objects.get(user_profile=userone)
plan = int(indi_user.selected_plan)
amount = int(plan)
except:
plan = None
amount = None
try:
merchant_obj = UserMerchantId.objects.get(user=request.user)
cust = True
merchant_customer_id = merchant_obj.customer_id
print merchant_customer_id
client_token = braintree.ClientToken.generate({
"customer_id": merchant_customer_id
})
except:
cust = False
client_token = None
try:
custom = Transaction.objects.filter(user=request.user)[0]
paid = custom.success
except:
paid = False
return {'cust':cust, "plan":plan,"amount": amount, "paid": paid,"client_token":client_token} #"plan": plan}
but i am getting above error.
if i tried
client_token = braintree.ClientToken.generate()
getting authentication error.
I am not getting how to create client token in django.
is there a way to create client token without customer_id?
Creating customer.
def new_user_receiver( instance, *args, **kwargs):
try:
merchant_obj = UserMerchantId.objects.get(user=instance)
except:
new_customer_result = braintree.Customer.create({
"first_name": instance.first_name,
"last_name": instance.last_name,
"email": instance.email,
"phone": instance.get_profile().telephone_number
})
if new_customer_result.is_success:
merchant_obj, created = UserMerchantId.objects.get_or_create(user=instance)
merchant_obj.customer_id = new_customer_result.customer.id
merchant_obj.save()
print """Customer created with id = {0}""".format(new_customer_result.customer.id)
else:
print "Error: {0}".format(new_customer_result.message)
It worked after making the change
import braintree
braintree.Configuration.configure(braintree.Environment.Production,
merchant_id=settings.BRAINTREE_MERCHANT_ID,
public_key=settings.BRAINTREE_PUBLIC_KEY,
private_key=settings.BRAINTREE_PRIVATE_KEY)
in production instead of "Sandbox" need to use "Production".
Related
I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it without refreshing the page. I am using Ajax for this. Let me show you the codes
html
<label for="landacq" class="civil-label">Land Acquisation Cases</label>
<input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden>
<label for="sc" class="civil-label">Supreme Court</label>
<input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden>
<label for="limitation" class="civil-label">Limitation</label>
<input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden>
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (query) {
showCivilQ(query);
// console.log(data);
},
error: function (error) {
console.log(error);
},
});
});
}
function showCivilQ(query) {
q.textContent = query;
console.log(query);
}
So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these values are use to filter the database and return the objects like this
views.py
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
return HttpResponse(query)
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
This is the result I am getting which is correct.
My Question is these objects contain attributes having some values in for eg, title, headnote etc. How can I display these attributes in the html rather than displaying the object names returned as shown in the Image like title of the citation, headnote of the citation etc
A solution could be to return a json object instead of the query resultset; because Ajax works well with json
You need a function that translates a Citation object into a dictionary (change it based on your real attributes). All elements must be translated into strings (see date example)
def citation_as_dict(item):
return {
"attribute1": item.attribute1,
"attribute2": item.attribute2,
"date1": item.date.strftime('%d/%m/%Y')
}
This dictionary must be translated into a json through import json package
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
response_dict = [citation_as_dict(obj) for obj in query]
response_json = json.dumps({"data": response_dict})
return HttpResponse(response_json, content_type='application/json')
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
In your HTML page you should be able to parse the response as a normal JSON object
I figured out another way to do it, which is giving me the required results too.
Here I am filtering the values of the query, and then converting it to a list and passing it as a JsonResponse
views.py
def civil_home(request):
if request.method == "POST" and request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.values().filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
result = list(query)
return JsonResponse({"status": "success", "result": result})
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
And then I am recieving the reponse here and iterrating over it to print the attributes in the html
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (response) {
console.log(response.result);
civilData = response.result;
if ((response.status = "success")) {
$("#queryResult").empty();
for (i = 0; i < civilData.length; i++) {
$("#queryResult").append(
`
${civilData[i].title}
<p>${civilData[i].headnote}</p>
`
);
}
} else {
$("#queryResult").empty();
$("#queryResult").append(
`
<p>No Citations Found</p>
`
);
}
},
error: function (error) {
console.log(error);
},
});
});
}
A csrf_token can be mentioned at the top of the html page and then it can be passed in the header to avoid any conflict.
I’m a beginner. I have tried everything in the Django E-commerce website course, but it does not work for me. I also tried documentation but I didn’t get any solution. I have this error when I go to /update_item/ and the data is not showing up in the terminal:
Expecting value: line 1 column 1 (char 0)
error screenshot
tutorial link
tutorial link
https://youtu.be/woORrr3QNh8
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
views.py
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action",action)
print("Pordutcs:",productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer , complete=False)
orderitem, created = Orderitem.objects.get_or_create(order= order,product=product)
if action == 'add':
orderitem.quantity = (orderitem.quantitiy +1)
elif action == 'remove':
orderitem.quantity = (orderitem.quantity -1)
orderitem.save()
if orderitem.quantity <= 0:
orderitem.delete()
return JsonResponse("Item was added", safe=False)
store.html
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
{%for i in products %}
<!-- {{i.image.url}} -->
<div class="col-lg-4">
<!-- <img class="thumbnail" src="{{i.image.url}}" alt="sorry"> -->
<img class="thumbnail" src="static{{i.imageURL}}">
<!-- {% static 'my_app/example.jpg' %} -->
<div class="box-element product">
<h6><strong>{{i.name}}</strong></h6>
<hr>
<button data-product="{{i.id}}" data-action='add' class="btn btn-outline-secondary add-btn updatecart">Add
to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float:right"><strong>Rs {{i.price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
<!-- <img src="static/images/robot.jpg"> -->
</div>
{% endblock content %}
I tried making a dummy django project with the code you provided to see if I counter such error.
Following JS code I used:
function updateUserOrder(){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
},
body:JSON.stringify({'productId':5, 'action':'Add'})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
I gave dummy data to productId and action.
Then my views.py goes like this:
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action",action)
print("Pordutcs:",productId)
return JsonResponse("Item was added", safe=False)
Not much with html part, it was just a click button to call the js code.
<button onclick="updateUserOrder()">Add</button>
And worked like a charm, following is the screenshot of my output in django server:
I would suggest you to try running with the same code.
If error is still there, try giving dummy data to productId and action in js code to make sure if there is a problem with the data in productId and action.
I assume you've solved this issue otherwise,...
if you're using Django version 4.0
change the url for the cart.js to update_item, cart.js should look like this
cart.js:
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = 'update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
then import csrf_exempt decorator , your views should look like this
views.py(after adding "from django.views.decorators.csrf import csrf_exempt" to the top of your file)
#csrf_exempt
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action",action)
print("Pordutcs:",productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer , complete=False)
orderitem, created = Orderitem.objects.get_or_create(order= order,product=product)
if action == 'add':
orderitem.quantity = (orderitem.quantitiy +1)
elif action == 'remove':
orderitem.quantity = (orderitem.quantity -1)
orderitem.save()
if orderitem.quantity <= 0:
orderitem.delete()
return JsonResponse("Item was added", safe=False)
Then Clear Your Cache and try adding the item to cart again...it should work this time
I'm trying to build a follow and unfollow button, I want to show the button only For any other user who is signed in, a user should not be able to follow themselves.
How can I return from my views.py the currently logged-in user as a JSON format to my JS file?
I'm building the button in the JavaScript file and not in the template, I tried to return as JSON format but didn't succeed
views.py
def display_profile(request, profile):
try:
profile_to_display = User.objects.get(username=profile)
profile_to_display_id = User.objects.get(pk=profile_to_display.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
# Return profile contents
if request.method == "GET":
return JsonResponse(profile_to_display.profile.serialize(), safe=False)
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class NewPost(models.Model):
poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted")
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
likes = models.IntegerField(default=0)
def serialize(self):
return {
"id": self.id,
"poster": self.poster.username,
"description": self.description,
"date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"),
"likes": self.likes
}
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
following = models.ManyToManyField(User, blank=True, related_name="following")
followers = models.ManyToManyField(User, blank=True, related_name="followers")
def serialize(self):
return {
"profileID": self.user.id,
"following": int(self.following.all().count()),
"followers": int(self.followers.all().count()),
}
index.js
function load_user_info(user_clicked_on){
document.querySelector('#page-view').style.display = 'none';
document.querySelector('#posts-view').style.display = 'none';
document.querySelector('#show-posts').style.display = 'none';
document.querySelector('#load-profile').style.display = 'block';
fetch(`/profile/${user_clicked_on}`)
.then(response => response.json())
.then(profile => {
const profile_element = document.createElement('div');
const followers = document.createElement('div');
const following = document.createElement('div');
const follow_button = document.createElement('button');
followers.innerHTML = 'Followers: ' + profile.followers;
following.innerHTML = 'Following: ' + profile.following;
if (profile.profileID == ?? ){
follow_button.innerHTML = 'Sameuser';
}else{
follow_button.innerHTML = 'Not same user';
}
profile_element.appendChild(followers);
profile_element.appendChild(following);
profile_element.appendChild(follow_button);
profile_element.classList.add('profile_element');
document.querySelector('#user-profile').appendChild(profile_element);
});
document.querySelector('#user-profile').innerHTML = `<h3>${user_clicked_on.charAt(0).toUpperCase() + user_clicked_on.slice(1)} Profile</h3>`;
}
I think all you need is the detail of the logged in user right?
may be you can get it from the request object by using
{{request.user}}
this returns the logged user instance
{{request.user.username}} {{request.user.email}}
this returns username and email
I dont know if you can directly use it in javascript , but you can kind of save this in template using a hidden field lik
<input type="hidden" value="{{request.user.username}}" id='user_detail'>
and grab it using id selector (getElementById, or jquery)
$('#user_detail').val()
I'm working on an assignment to use the fetch API to do some of the normal things we would have Python do in our views with JavaScript such as adding records or querying the database. One issue I'm running across is passing the normal properties we would see in Django, say a user or username, where it just shows up as a literal user id when I pull it from the sql database with the fetch API. With the views, html and JavaScript I have written now, how would I go about pulling the username with fetch in JavaScript that I can normally grab with a variable or view with a print statement in the Django console, instead of just viewing the user id from the database. I feel like I'm missing a step and I'm just not seeing it.
urls
app_name = "network"
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("addpost", views.post, name="post"),
path("<str:navbar_item>", views.viewposts, name="viewposts"),
]
models.py
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField(null=True, blank=True)
# pics
website = models.CharField(max_length=225, null=True, blank=True)
follower = models.ManyToManyField(
User, blank=True, related_name="followed_user") # user following this profile
# profile user that follows this profile
following = models.ManyToManyField(
User, blank=True, related_name="following_user")
def __str__(self):
return f"{self.user}'s' profile id is {self.id}"
def following_users(self):
for username in self.following:
return username
def get_absolute_url(self):
return reverse("network:profile-detail", args=[str(self.id)])
class Post(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_user")
body = models.TextField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, blank=True, related_name="post_likes")
def __str__(self):
return f"{self.created_by} posted {self.body}"
def get_absolute_url(self):
return reverse("network:post-detail", args=[str(self.id)])
def total_likes(self):
return self.likes.count()
class Meta:
ordering = ["-timestamp"]
views.py
def index(request):
if request.user.is_authenticated:
return render(request, "network/index.html", {})
else:
return HttpResponseRedirect(reverse("network:login"))
#login_required
def post(request):
# Composing a new post must be done via POST
if request.method != "POST":
return JsonResponse({"error": "You must POST your request."}, status=404)
try:
data = json.loads(request.body)
body = data.get("body", "")
user = request.user
print(user)
post = Post(created_by=user, body=body)
# post = Post(created_by=Profile.objects.get(user=user), body=body)
post.save()
except AttributeError:
return JsonResponse({"error": "AttributeError thrown."}, status=500)
return JsonResponse({"message": "Post created."}, status=201)
#login_required
def viewposts(request, navbar_item):
if navbar_item == "viewposts":
posts = Post.objects.all()
posts = posts.order_by("-timestamp")
json_post = serialize("json", posts)
print(posts)
return HttpResponse(json_post, content_type="application/json")
else:
return JsonResponse({"error": "Invalid page."}, status=400)
index.html
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
<div class="container p-5">
{% if error %}
{{ error }}
{% endif %}
<h1 class="display-4">All Posts</h1>
<div class="form-group border rounded p-4">
<h2 class="diplay-3">New Post</h2>
<form id="addpost" class="form-group pt-5">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" id="body" placeholder="Add post here..."></textarea>
</div>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
<div id="all-posts" class="all-posts">
</div>
</div>
{% endblock %}
{% block script %}
<script src="{% static 'network/main.js' %}"></script>
{% endblock %}
JavaScript
// Post on index page # API Routes /addpost
const addPost = () => {
const addPostUrl = '/addpost';
const csrftoken = getCookie('csrftoken');
const body = document.querySelector('#body').value;
// body needs to be passed into an object before using the stringify method
const bodyObject = { body };
fetch(addPostUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify(bodyObject)
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
return false;
};
// Load posts in index page # API Routes /navbar_item
function loadPosts(navItem, event) {
preventPageLoad(event);
const postUrl = `/${navItem}`;
// Send a GET request to the URL to retrieve all posts
fetch(postUrl)
.then(response => response.json())
.then(data => {
data.forEach(post => {
const { fields } = post;
const allPostsContainer = document.querySelector("#all-posts");
const element = document.createElement('div');
const postId = `#post-${fields.id}`;
element.style.textDecoration = 'none';
element.classList.add('HoverClass1');
element.setAttribute('id', `post-${fields.id}`);
element.classList.add('d-flex', 'flex-column' ,'justify-content-between', 'p-4', 'm-3', 'lead', 'border', 'rounded');
element.style.color = '#000000';
element.innerHTML =
// This is returning an id
`<div class="bd-highlight font-weight-bolder mr-5">${fields.created_by}</div>
<div class="bd-highlight">${fields.timestamp}</div>
<div class="flex-fill bd-highlight">${fields.body}</div>`;
console.log(fields);
allPostsContainer.append(element);
const linePost = document.querySelector(postId);
linePost.addEventListener('click', (event) => {
console.log(event);
});
});
})
.catch(error => {
console.log(error);
});
return false;
}
Images showing my admin console in Django versus the browser console and what fetch is pulling in JavaScript. You'll see in the admin console we can view the username, but in the browser console all I'm getting is the user id with fetch.
I figured out how to do this. I added a serialize method to the Post model to convert these properties to JSON.
def serialize(self):
return {
'id': self.id,
'created_by': self.created_by.username,
'body': self.body,
'timestamp': self.timestamp.strftime('%b %-d %Y, %-I:%M %p'),
'likes': self.total_likes()
}
Then in views.py, in my viewposts function, instead of my the HttpResponse, I used JsonResponse and passed the model's serialize method as an argument.
#login_required
def viewposts(request, navbar_item):
if navbar_item == "viewposts":
posts = Post.objects.all()
posts = posts.order_by("-timestamp")
return JsonResponse([post.serialize() for post in posts], safe=False)
else:
return JsonResponse({"error": "Invalid page."}, status=400)
This allowed me to not have to deconstruct anything in my JavaScript file. So I could pull any attributes from my query using dot notation directly off of the data model in fetch.
Please forgive me if i posted it in bad way, but i dont have any idea where is the mistake.
Im doing a small chat with five rooms using Flask-Socket and SocketIO. I set rooms like this:
ROOMS = ["waiting room", "food", "news", "games", "coding"]
Then i put them to html:
#app.route("/chat", methods=['GET', 'POST'])
#login_required
def chat():
return render_template('chat.html', username=current_user.username, rooms=ROOMS)
And on template:
{%for room in rooms%}
<p class="select-room"> {{ room }}</p>
{% endfor %}
The problem is when i try to send message only to room where i am by:
#socketio.on('message')
def message(data):
time_stamp = time.strftime('%b-%d %I:%M%p', time.localtime())
send({'msg': data['msg'], 'username': data['username'], 'time_stamp':time_stamp}, room=data['room'])
and from client:
document.querySelector('#send-message').onclick = () =>{
socket.send({'msg': document.querySelector('#user_message').value,
'username': username, 'room': room});
}
It makes me key error:
send({'msg': data['msg'], 'username': data['username'], 'time_stamp':time_stamp}, room=data['room'])
KeyError: 'room'
it also happens when i trying to switch rooms(leave one and connect other using this):
function leaveRoom(room) {
socket.emit('leave', {'username': username, 'room': room});
document.querySelectorAll('.select-room').forEach(p => {
p.style.color = "black";
});
}
function joinRoom(room) {
socket.emit('join', {'username' : username, 'room' : room});
// Clear message area
document.querySelector('#display-message-section').innerHTML = '';
};
For room select i use:
document.querySelectorAll('.select-room').forEach(p => {
p.onclick = () => {
let newRoom = p.innerHTML
// Check if user already in the room
if (newRoom == room) {
msg = `You are already in ${room} room.`;
printSysMsg(msg);
} else {
leaveRoom(room);
joinRoom(newRoom);
room = newRoom;
};
};
});
Where im making a mistake?
The full code is here:
https://pastebin.com/QXiBQG2u
https://pastebin.com/zfEtV4ZX
https://pastebin.com/wfkqNjf9