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 am new to Django and Javascript. I would like to create an edit section on a site, where people can edit a post that already exists. Similar to Facebook or Twitter.
When I click 'edit' on my post, in the console I am getting:
network.js:28 POST http://127.0.0.1:8000/edit_post/ 404 (Not Found)
I've tried many things but cannot get it to work. Any help is appreciated.
I think the issue might have to do with the use of 'post' and 'text.'
'text' is in my model, used to signify the text of the actual post.
views.py:
#login_required
#csrf_exempt
def edit_post(request):
if request.method == "POST":
post_id = request.POST.get('id')
new_post = request.POST.get('text')
try:
post = Post.objects.get(id=post_id)
if post.user == request.user:
post.text = new_post.strip()
post.save()
return JsonResponse({}, status=201)
except:
return JsonResponse({}, status=404)
return JsonResponse({}, status=400)
models.py
class User(AbstractUser):
pass
class Post(models.Model):
text = models.TextField(max_length=500, blank=True,
null=True)
username = models.ForeignKey('User',
on_delete=models.CASCADE, related_name='author',
null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(
User, blank=True, related_name="liked_user")
def __str__(self):
return self.user.username
Javascript file:
edit = document.querySelectorAll(".edit");
text_area = document.querySelectorAll(".textarea");
edit.forEach((element) => {
element.addEventListener("click", () => {
edit_handeler(element);
});
});
text_area.forEach((element) => {
element.addEventListener("keyup", (e) => {
if (e.keyCode == 13 && e.shiftKey) return;
if (e.keyCode === 13) edit_handeler(element);
});
});
function edit_post(id, post) {
form = new FormData();
form.append("id", id);
form.append("text", text.trim());
fetch("/edit_post/", {
method: "POST",
body: form,
}).then((res) => {
document.querySelector(`#post-content-${id}`).textContent = post;
document.querySelector(`#post-content-${id}`).style.display =
"block";
document.querySelector(`#post-edit-${id}`).style.display = "none";
document.querySelector(`#post-edit-${id}`).value = text.trim();
});
}
function edit_handeler(element) {
id = element.getAttribute("data-id");
edit_btn = document.querySelector(`#edit-btn-${id}`);
if (edit_btn.textContent == "Edit") {
document.querySelector(`#post-content-${id}`).style.display =
"none";
document.querySelector(`#post-edit-${id}`).style.display =
"block";
edit_btn.textContent = "Save";
edit_btn.setAttribute("class", "text-success edit");
} else if (edit_btn.textContent == "Save") {
edit_post(id, document.querySelector(`#post-edit-${id}`).value);
edit_btn.textContent = "Edit";
edit_btn.setAttribute("class", "text-primary edit");
}
}
Part of html file:
{% if user1 == user2 %}
<span class="text-primary edit" data-id="{{i.id}}"
id="edit-btn-{{i.id}}">Edit</span>
<br><br>
{% endif %}
<span id="post-content-{{i.id}}" class="post"
{{i.post}}</span>
<textarea data-id="{{i.id}}" id="post-edit-{{i.id}}"
style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea>
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("make_post", views.make_post, name="make_post"),
path("fol/<str:user>", views.fol, name="fol"),
path("following_list/<str:username>", views.following_list,
name='following_list'),
path('like/', views.like),
path('edit_post/', views.edit_post),
path("profile/<str:username>", views.profile, name="profile"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
]
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.
i am struggling with getting my User ID after i log in. The token is and already stored in localstorage
working on Django as backend and Vue.js as frontend
so a user is able to login and out but I can't seem to find the userId of the logged in user
in able to retrieve more data linked to the user.
Therefore i cannot post an product properly related to a user. besides that, if i manage to post and check via console on chrome, it says my category section null/empty
Whenever I try to link my category foreignfield in the product model
i keep getting this error below
{category: ["Invalid hyperlink - No URL match."]}
category: ["Invalid hyperlink - No URL match."]
0: "Invalid hyperlink - No URL match.
Thanks in advance
my model.py
from django.db import models
from django.contrib.auth.models import User
# class User(models.Model):
# id_user = models.DecimalField(max_digits=10, decimal_places=2, null=True)
# def __str__(self):
# return self.id_user
class Category(models.Model):
name = models.CharField(max_length = 200, null = True,)
def __str__(self):
return self.name
class State(models.Model):
STATE_CHOICES = [('Ordered', 'Ordered'), ('Pending', 'Pending'),
('Placed', 'Placed'), ('Reserved', 'Reserved')
]
state = models.CharField(max_length = 200, null = True,
choices = STATE_CHOICES)
def __str__(self):
return self.state
class Product(models.Model):
user = models.ForeignKey(User,null=True, on_delete=models.SET_NULL)
state = models.ForeignKey(State, null=True, on_delete=models.SET_NULL)
category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
description = models.TextField(max_length=800, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
#image = models.ImageField(upload_to='post_image', blank=True, width_field=None, height_field=None, max_length=100,)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
unique_together = (('user','title'),)
index_together = (('user','title'),)
# CATEGORY_CHOICES = (
# ('Books', 'Books'),
# ('eBooks','eBooks'),
# ('Writing material','Writing material'),
# )
# category = models.CharField(max_length=200, null=True, choices=CATEGORY_CHOICES)
SCHOOL_CHOICES = (
('Erasmushogeschool | EHB',(
('Campus Kaai', 'Campus Kaai'),
('Campus Bloemberg', 'Campus Bloemberg'),
)),
('Vrije Universiteit Brussel | VUB',(
('Campus Jette', 'Campus Jette'),
('Campus Schaarbeek', 'Campus Schaarbeek'),
)),
('Katholieke universiteit leuven | KUL',(
('KUL Gent', 'KUL Gent'),
('Campus Antwerpen', 'Campus Antwerpen'),
)),
)
school = models.CharField(max_length=50, choices=SCHOOL_CHOICES, null=True)
MAJOR_CHOICES = (
('IT','IT'),
('Marketing','Marketing'),
('DIFF','DIFF'),
)
major = models.CharField(max_length=200,choices=MAJOR_CHOICES, null=True)
SUBJECT_CHOICES = [
('Mathematics','Mathematics'),
('Algoritmes','Algoritmes'),
('Analyses','Analyses'),
]
subject = models.CharField(max_length=200,choices=SUBJECT_CHOICES, null=True)
CONDITION_CHOICES = [
('New','New'),
('Used','Used'),
]
condition = models.CharField(max_length=200,choices=CONDITION_CHOICES, null=True)
LOCATION_CHOICES = [
('Brussel','Brussel'),
('Leuven','Leuven'),
('Gent','Gent'),
('Antwerpen','Antwerpen'),
]
location = models.CharField(max_length=200,choices=LOCATION_CHOICES, null=True)
def __str__(self):
return self.title
serializer.py
from rest_framework import serializers
from .models import Product, State, Category
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')
extra_kwargs = {'password':{'write_only':True,'required':True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
print(user)
Token.objects.create(user=user)
return user
class ProductSerializer(serializers.HyperlinkedModelSerializer):
category_name = serializers.CharField(source='category.name', read_only=True)
class Meta:
model = Product
fields = '__all__'
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ('id', 'url', 'name')
class StateSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = State
fields = '__all__'
urls.py
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from django.urls import path
from restapi.views import ProductViewSet, StateViewSet, UserViewSet, CategoryViewSet
# class UserSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = User
# fields = ['id', 'url', 'username', 'email', 'is_staff']
# # ViewSets define the view behavior.
# class UserViewSet(viewsets.ModelViewSet):
# queryset = User.objects.all()
# serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register('users', UserViewSet)
router.register('product', ProductViewSet)
router.register('category', CategoryViewSet)
router.register('state', StateViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
views.py
from django.shortcuts import render
from rest_framework import viewsets, status
from .models import Product, State, Category
from django.contrib.auth.models import User
from .serializer import ProductSerializer, UserSerializer, StateSerializer, CategorySerializer
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework.authentication import TokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
authentication_classes = (TokenAuthentication,)
permission_calsses = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('title', 'price', 'category__name')
# def delete(self,request,*args,**kwargs):
# response = {'message':'product cannot be updated like this'}
# return Response(response, status = statu.HTTP_400_BAD_REQUEST)
# def create(self,request,*args,**kwargs):
# response = {'message':'product cannot be created like this'}
# return Response(response, status = status.HTTP_400_BAD_REQUEST)
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_calsses = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('name', 'id')
class StateViewSet(viewsets.ModelViewSet):
queryset = State.objects.all()
serializer_class = StateSerializer
permission_calsses = (IsAuthenticated,)
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny, )
# class CustomObtainAuthToken(ObtainAuthToken):
# def post(self, request, args, *kwargs):
# response = super(CustomObtainAuthToken, self).post(request, args, *kwargs)
# token = Token.objects.get(key=response.data['token'])
# return Response({'token': token.key, 'id': token.user_id})
my front end Vue.js login
<template>
<div class="login-form">
<b-form #submit.prevent="login" v-if="token==null">
<div class="sign-in-htm">
<div class="group">
<label for="user" class="label">Username</label>
<input id="user" type="text" class="input" required v-model="username">
</div>
<div class="group">
<label for="pass" class="label">Password</label>
<input
id="pass"
type="password"
class="input"
data-type="password"
v-model="password"
required>
</div>
some more code...
</template>
<script>
export default {
name: "login",
data() {
return {
username: '',
user_id : 0,
password: '',
repeat: '',
submitted: false,
token: null,
log_status: ''
}
},
methods: {
login() {
axios
.post("http://127.0.0.1:8000/auth/", {
username: this.username,
password: this.password
})
.then(res => {
this.token = res.data.token;
this.log_status = "Log out";
this.$root.$emit("logAndToken", this.log_status, this.token);
console.log(
"Login data:",
res,
this.username,
this.password,
this.token
);
localStorage.setItem("logAndToken", this.token);
localStorage.setItem("user_id", this.user_id);
});
this.$router.push({ name: "homepage" }).catch(err => {
localStorage.removeItem("logAndToken");
localStorage.removeItem("user_id");
console.log("error loginn", err);
});
},
register() {
console.log(this.username);
axios
.post("http://127.0.0.1:8000/auth/", {
username: this.username,
password: this.password
})
.then(res => console.log(res))
.catch(err => console.log(err));
this.submitted = true;
this.$validate()
.then(function(success) {
if (success) {
alert('Validation succeeded!');
}
});
this.$router.push({ name: "useradmin" });
},
submit: function () {
this.submitted = true;
this.$validate()
.then(function(success) {
if (success) {
alert('Validation succeeded!');
}
});
}
</script>
my navbar at the top | in this component i check whether i have an token or not with the v-for
<template>
<li class="nav-item dash">
<a class="nav-link pr-2 h5 font-weight-bold" type="button" #click.prevent="$router.push({ name: 'useradmin' }).catch(err => {})" v-if="this.token!=null">Dasboard</a>
</li>
<li class="nav-item">
<a class="nav-link pr-2 h5" type="button" #click.prevent="$router.push({ name: 'sdf' }).catch(err => {})" v-if="this.token!=null" v-on:click="logout()" >{{this.log_status}}</a>
</li>
<li class="nav-item">
<a class="nav-link pr-2 h5" type="button" #click.prevent="$router.push({ name: 'sdf' }).catch(err => {})" v-if="this.token==null">{{this.log_status}}</a>
</li>
// more code
</template>
<script>
var url_category = 'http://127.0.0.1:8000/category/'
export default {
name: "Menu",
components: {},
props: [],
data() {
return {
categories:[],
title: '',
token: null,
log_status: this.token?'log out':'log in',
};
},
mounted() {
this.$root.$on('logAndToken', (log_status, token) => {
this.token = token
this.log_status = log_status
console.log('message received from login + token' ,log_status, token);
})
},
methods: {
sendCategoryName(category_name){
this.$root.$emit('message', category_name)
},
logout(){
localStorage.removeItem('logAndToken');
this.token = null;
this.log_status = "Log in"
this.$root.$emit('logAndToken', this.log_status, this.token)
}
},
created() {
axios.get(url_category).then(res => (this.categories = res.data))
.catch(err => console.log("error", err));
/* To check if anything is coming trough, i console log the result:
.then(res => console.log(res))
My records were in the array 'results'
*/
// get the Records form the API use Vue detected tool extention via chrome.
}
};
</script>
You can fetch user_id from request object. request.user.id
If you want to store additional information, it's a good idea to utilize JWT tokens. When you send the token from the server you can encode additional information into the response payload.
For example your payload might look like this when its encoded.
{
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
When you decode it from your frontend app
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
Take a look at https://jwt.io/
Right now, it seems like you don't encode any other additional information into your response.
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".