everyone !
I'm learning React by myself, and I'm stuck here where I'm doing a REST API for a Chat APP, when I POST a new message, the component don't refresh by itself, I have to refresh the page.
I managed to refresh it putting the idmessage and vmessage in the useEffect array, but it kept hitting the API, and I'm pretty sure this wasn't supposed to happen.
There may be a lot of wrong code here and a lot of different ways to do a better project, so I'm sorry if it's bad written.
P.S: Everything is mocked for the first and second contact
My MessagePage:
const MessagesPage = () => {
let [idmessage, setIdmessage] = useState([])
let [vmessage, setVmessage] = useState([])
useEffect(() => {
getIdMessage()
getVMessage()
}, [])
let url = 'http://127.0.0.1:8000'
let getIdMessage = async () => {
let response = await fetch(`${url}/api/messages/1/2/`)
let data = await response.json()
setIdmessage(data)
}
let getIdName = (idmessage) => {
return idmessage.map((m) => (
m.contact.name
))
}
let getVName = (vmessage) => {
return vmessage.map((m) => (
m.contact.name
))
}
let getVMessage = async () => {
let response = await fetch(`${url}/api/messages/2/1/`)
let data = await response.json()
setVmessage(data)
}
const messages = idmessage.concat(vmessage).sort((a,b) => {
return a.time.localeCompare(b.time);
}) // This is the way I found to make it like a real chat and not two different groups in a chat
return (
<>
<MessageHeader/>
<div className="card bg-dark card-body messages">
{messages.map((m, index) => (
m.contact.name === getIdName(idmessage)[0] ?
<MessageDetail messages={m} key={index} c={1}/>
: m.contact.name === getVName(vmessage)[0] ?
<MessageDetail messages={m} key={index} c={2}/>
: null
))
}
<SendMessage/>
</div>
</>
)
}
export default MessagesPage
Then my SendMessage Component:
const SendMessage = () => {
let [text, setText] = useState('')
let url = 'http://127.0.0.1:8000'
const handleChange = (e) =>{
setText(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault()
sendText()
setText('')
}
let sendText = async () => {
fetch(`${url}/api/messages/1/2/`, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"text": (text),
"contact": 1,
"other_contact": 2,
"state": false
})
})
}
return (
<div className="w-100 card-footer border bg-light textWrite">
<form className='m-0 p-0' onSubmit={handleSubmit} method="POST" autoComplete='off'>
<div className="row m-0 p-0">
<div className="col-11 m-0 p-1">
<input id="text" onChange={handleChange} className="mw-100 border rounded form-control" type="text" name="text" title="Send a Message" placeholder="Send a Message..." value={text} required/>
</div>
<div className="col-1 m-0 p-1">
<button id='sendText' className="btn btn-outline-secondary rounded border w-100" type='submit'><BsChatDots/></button>
</div>
</div>
</form>
</div>
)
}
export default SendMessage
The Serializer:
#api_view(['GET', 'POST'])
def detailMessages(request, pk, o_pk):
message = Message.objects.filter(contact=pk, other_contact=o_pk)
serializer = MessageSerial(message, many=True)
if request.method == 'GET':
return Response(serializer.data)
if request.method == 'POST':
data = request.data
contact = Contact.objects.get(id=data['contact'])
other_contact = Contact.objects.get(id=data['other_contact'])
message = Message.objects.create(
contact=contact,
other_contact=other_contact,
text=data['text'],
state=data['state']
)
serializer = MessageSerial(message, many=False)
return Response(serializer.data)
If you want to make real time messages system without hitting the database each time, you should read about WebSocket in a simple word it is opening pool connection between multiple devices to send and receive data without closing the connection after send for example like http request and this data will always pass throw this connection(channel) without reloading or database hitting, you should read more about it to better understanding.
And if you want to use it in your project you can search about: react websocket and Django Channels
Best of luck
Related
To create a post, the user must go through the form for creating posts and upload an image, but I don’t know how to do this.
I tried to send file event.target.files[0] but I received "POST /api/tests/ HTTP/1.1" 400 91
it didn't help, I tried to send event.target.files[0].name but that didn't help either.
TestForm.jsx:
import React, {useState} from 'react';
import axios from "axios";
function TestForm() {
const [testInputs, setTestInputs] = useState({title: '', title_image: '', test_type: ''});
console.log(testInputs);
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
const handleClick = () => {
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/tests/',
data: {
author: 1,
title: 'sad',
title_image: testInputs.title_image.name,
test_type: 2,
question: [1, 3, 4],
result: [1, 2]
}
})
}
return (
<div>
<form>
<input onChange={(event) => {setTestInputs({...testInputs, title_image: event.target.files[0]}); console.log(event.target)}} type="file" placeholder='upload'/>
</form>
<button onClick={handleClick}>asd</button>
</div>
);
}
export default TestForm;
models.py
class Test(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
title_image = models.ImageField(default="images/IMG_1270.JPG/", null=True, blank=True, upload_to='titleImages/')
test_type = models.ForeignKey(TestType, on_delete=models.CASCADE)
question = models.ManyToManyField(TestQuestionBlok)
result = models.ManyToManyField(TestResult, blank=True)
def __str__(self):
return self.title
views.py
class TestList(APIView):
def post(self, request, format=None):
serializer1 = TestSerializers(data=request.data)
if serializer1.is_valid():
print(serializer1.data)
return Response(serializer1.data, status=status.HTTP_200_OK)
return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST)
#Api
import axios;
const avatarupload = (data, uuid) => {
return axios.post(`endpoint/`, data).then(
(res) => res,
(error) => error.response
);
};
#Store
getAvatar = async (data, cb) => {
const uuid = LocalStorageService.getUuid();
const resp = await avatarupload(data, uuid);
if (resp.status === 200) {
this.setMessage('Successfully Updated');
this.setUser(resp.data);
cb();
} else {
cb(resp.data.error);
}
this.setPicLoading(false);
};
#web page
const handleFileChange = async (event) => {
const data = new FormData();
data.append('avatar', event.target.files[0]);
getAvatar(data, (error) => {
setError(error);
});
setFader(1);
};
<Form.Group controlId='formBasicText'>
<button
className='primary'
type='button'
onClick={handleChangeAvatarClick}
>
CHANGE AVATAR
</button>
<Form.Control
style={{ display: 'none' }}
type='file'
ref={hiddenFileInput}
onChange={handleFileChange}
accept='image/*'
/>
</Form.Group>
I'm using Django and React for a project that consumes Trello's API. I created functions in django views.py that will get user's boards, lists and cards. The problem is, to get a list, I need that the user select a board, because the list's endpoint requires a board id (and so on). I can show the user's boards on my react page and storage the board's id on a variable in Index.js (on pages folder), but I have no ideia how I can send the selected board id to views.py to consume Trello's api according to the user's selected board. Here's my code.
Django views.py:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from dotenv import load_dotenv
from treegia.settings import TRELLO_URL
import os
import requests
load_dotenv()
TRELLO_KEY = os.getenv('TRELLO_KEY')
TRELLO_TOKEN = os.getenv('TRELLO_TOKEN')
#api_view(['GET'])
def get_boards(request):
if request.method == 'GET':
board_endpoint = TRELLO_URL+'members/me/boards'
jsonObj = {'fields':'name,id', 'key':TRELLO_KEY, 'token':TRELLO_TOKEN}
boards = requests.get(board_endpoint, json=jsonObj).json()
return Response(boards)
#api_view(['GET'])
def get_lists(request):
if request.method == 'GET':
list_endpoint = TRELLO_URL+ 'boards/' + id_board + '/lists'
jsonObj = {'fields':'name,id', 'id':id_board, 'key':TRELLO_KEY, 'token':TRELLO_TOKEN}
lists = requests.get(list_endpoint, json=jsonObj).json()
return Response(lists)
#api_view(['GET'])
def get_cards(request):
if request.method == 'GET':
card_endpoint = TRELLO_URL+ 'lists/' + id_list + '/cards'
jsonObj = {'fields':'name,id', 'id':id_list, 'key':TRELLO_KEY, 'token':TRELLO_TOKEN}
cards = requests.get(card_endpoint, json=jsonObj).json()
return Response(cards)
React Index.js:
import React from 'react';
import Navbar from '../components/Navbar';
import '../styles/index.css'
const Index = () => {
const [boards, setBoards] = React.useState([]);
const [boardId, setBoardId] = React.useState([]);
const [lists, setLists] = React.useState([]);
const [listId, setListId] = React.useState([]);
React.useEffect(() => {
getBoards();
}, []);
React.useEffect(() => {
getLists();
}, []);
async function getBoards() {
await fetch('http://localhost:8000/boards/')
.then(resp => resp.json())
.then(data => {
console.log(data);
if(data) setBoards(data);
})
}
async function getLists() {
await fetch('http://127.0.0.1:8000/lists/')
.then(resp => resp.json())
.then(data => {
console.log(data);
if(data) setLists(data);
})
}
return (
<div id='index-page'>
<Navbar />
<div className='boards'>
<h1>Your boards</h1>
<div className='boards-container'>
{boards.map(board => (
<button key={board.id} onClick={() => {
setBoardId(board.id)
}}>{board.name}</button>
))}
</div>
</div>
<div className='lists'>
<h1>Your lists</h1>
<div className='lists-container'>
{lists.map(list => (
<button key={list.id} onClick={() => {
setListId(list.id)
}}>{list.name}</button>
))}
</div>
</div>
{boardId ? <p>{boardId}</p> : ''}
{listId ? <p>{listId}</p> : ''}
</div>
);
}
export default Index;
Basically, when the user selects a board, I what to send the id to get_lists function. Is this possible to do?
In the view
def get_lists(request):
print(request.query_params['id_list']) # 'id_list being the variable you want to pass from the front end
this sets that we are expecting a parameter from the front end get request.
Remember to add a try catch arround it..cos if that query_param doesnt exist it will throw and erroe.
Non in the FE.. while making a request, set request parameter 'id_list = '
var url = new URL('http://127.0.0.1:8000/lists')
var params = {id_list:'3'} // or whatever the params
url.search = new URLSearchParams(params).toString();
fetch(url);
Essentially you add the query params to the request url like
http://127.0.0.1:8000/lists/?id_list=3&another_param=2..
test the backend using postman or smthn before integration..to make sure the correct url and stuff.
I can make the simple button or default button work but as there is no option to custom css I need to use "Custom" stripe button. Following is the simple and custom form I am using where simple one works fine but don't know how to make custom work. Currently it is doing nothing when I click and enter information. But Default button works just fine.
View:
#app.route('/monthly', methods=['GET', 'POST'])
def monthly_charged():
if not user_authorized():
return redirect('/')
amount = 1495
# customer
key = stripe_keys['publishable_key']
print key
charge_all = stripe.Charge.list(limit=10000)
charge_dic = {}
charge_list = []
for charge_data in charge_all:
charge_dic['Amount'] = "$" + str(float(charge_data.amount) / 100) + " " + charge_data.currency.upper()
charge_dic['Description'] = charge_data.description
charge_dic['Name'] = charge_data.receipt_email
charge_dic['Date'] = str(datetime.datetime.fromtimestamp(charge_data.created))
charge_list.append(charge_dic)
charge_dic = {}
data = get_profile_data(session['auth_token'])
profile_data = data['StudentProfile']
student_id = profile_data.id
student = get_profile_data(session['auth_token'])['StudentProfile']
pkg = Package.query.filter_by(student_id=profile_data.id).first()
if pkg:
flash('You already have an active subscription.')
else:
stripe_token = request.form['stripeToken']
email = request.form['stripeEmail']
try:
customer = stripe.Customer.create(
email=email,
source=request.form['stripeToken']
)
subscription = stripe.Subscription.create(
customer=customer.id,
plan="monthly",
)
student_id = profile_data.id
student.stripe_customer_id = customer.id
student.stripe_subscription_id = subscription.id
package = Package(
student_id=student_id,
stripe_id = customer.id,
student_email=request.form['stripeEmail'],
is_active=True,
package_type='monthly',
subscription_id=subscription.id
)
dbase.session.add(package)
flash("You've successfylly subscribed for monthly package.")
dbase.session.commit()
except stripe.error.CardError as e:
# The card has been declined
body = e.json_body
err = body['error']
return redirect(url_for('packages', key=key, amount=amount))
Simple or Default Stripe Button:
<form action="/monthly" method="post" >
<div class="form-group">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_YgHVTCLIMQLW4NV6ntnJPAXs"
data-description="Monthly Package"
data-name="Monthly"
data-amount="10000"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</div>
</form>
Custom Stripe Button:
<form action="/monthlycharged" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Enroll</button>
<style>
#customButton{
width:100px;
height:30px;
background-color:red;
color:white;
border:2px solid red;
}
</style>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Monthly',
description: 'monthly',
amount: 10000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
</form>
You need to submit your form in the token: function() {} of StripeCheckout.configure.
Here's an example of how to do that: https://jsfiddle.net/osrLsc8m/
I realised from my appengine log that the same cursor is being generated each time, the call to the Homehandler is made.
Please any idea what i am doing wrong, below is a snippet of my code:
class HomeHandler(webapp2.RequestHandler):
def get(self):
#page=self.request.get("page", default_value="1");
q = Allnews.query().order(-Allnews.date_added)
cursor = ndb.Cursor(urlsafe=self.request.get('cursor',default_value=None))
items, next_curs, more = q.fetch_page(30, start_cursor=cursor)
if more:
next_c = next_curs.urlsafe()
else:
next_c = None
context = { "news":items,"cursor":next_c}
# context["headlines"]=Feed.query(Feed.feed_cat.title == 'Headlines')
# context["gossip"] = Feed.query(Feed.feed_cat.title == 'Gossip')
# context["sports"] = Feed.query(Feed.feed_cat.title == 'Sports')
self.response.out.write(template.render('templates/homefeed.html',context))
this is the section of my homefeed.html template, I m using 'infinite scrolling' technique to fetch more results
<script>
{% if cursor %}
$(window).scroll(function()
{
var src=$("#src_val").val();
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$('div#loadmoreajaxloader').show();
$.ajax({
url:"/home",
type:'GET',
data: {cursor: '{{cursor}}',feed_id:src },
success: function(news)
{
if(news)
{
$("#wrapper").append(news);
$('div#loadmoreajaxloader').hide();
}else
{
$('div#loadmoreajaxloader').html('No more posts to show.');
}
}
});
}
});
{% endif %}
</script>
It looks like you're using the get() method for both displaying a page and to handle an AJAX request. It's correctly generating a page with an initial cursor, but your $.ajax() method is expecting it to return JSON data.
Split the page request and AJAX request into two methods. Try adding a post() method to your HomeHandler that returns JSON data like this:
import json
def post(self):
q = Allnews.query().order(-Allnews.date_added)
cursor = ndb.Cursor(urlsafe=self.request.get('cursor',default_value=None))
items, next_curs, more = q.fetch_page(30, start_cursor=cursor)
if more:
next_c = next_curs.urlsafe()
else:
next_c = None
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps({'news': items, 'cursor': next_c))
Now you have a method that returns JSON data to the AJAX request:
<script>
var cursor = null;
$(window).scroll(function()
{
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$.ajax({
url:"/home",
type:'POST',
data: {cursor: cursor},
success: function(data)
{
$("#wrapper").append(data['news']);
cursor = data['cursor'];
if ( !cursor )
$('div#loadmoreajaxloader').show().html('No more posts to show.');
}
});
}
});
</script>
Notice how the cursor value is updated on each AJAX request. This is how you will get a new cursor on the next request.
(This code was not tested, you may need to debug it.)
form.html
<form action='/login/' method = 'post'>
{% csrf_token %}
<label>Email: (*)</label><input type='text' name='email' value='' /><br />
<label>Password: </label><input type='password' name='password' value='' /><br />
<input type='submit' name='submit' value='Log in' />
</form>
and views.py i use HttpResponse not render_to_response
def login(request):
success = False
message = ''
try:
emp = Employee.objects.get(email = request.POST['email'])
if emp.password == md5.new(request.POST['password']).hexdigest() :
emp.token = md5.new(request.POST['email'] + str(datetime.now().microsecond)).hexdigest()
emp.save()
info = serializers.serialize('json', Employee.objects.filter(email = request.POST['email']))
success = True
return HttpResponse(json.dumps({'success':str(success).lower(), 'info':info}))
else:
message = 'Password wrong!'
return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}), status = 401)
except:
message = 'Email not found!'
return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}), status = 401)
if use render_to_response, i just add RequestContext but HttpResponse, i don't know what to do.
i use Django 1.4
Where's my problem
=========================
My problem is sloved when I change the function that render the HTML :
def homepage(request):
return render_to_response('index.html')
to
def homepage(request):
return render_to_response('index.html', context_instance=RequestContext(request))
That's a stupid mistake... thanks...
If you are using ajax to send the form and have included jQuery, you have two possibilities:
Manually add the csrfmiddlewaretoken data to your POST request
Automate CSRF token handling by modifying jQuery ajax request headers
1. Manually add csrfmiddlewaretoken
var data = {
csrfmiddlewaretoken: $('#myForm input[name=csrfmiddlewaretoken]').val(),
foo: 'bar',
};
$.ajax({
type: 'POST',
url: 'url/to/ajax/',
data: data,
dataType: 'json',
success: function(result, textStatus, jqXHR) {
// do something with result
},
});
2. Automate CSRF token handling
jQuery(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
But: It is said that modifying the ajax request headers is bad practice. Therefore i'd go with solution number one.
Source: Cross Site Request Forgery protection: AJAX
The Django Documentations (CSRF DOC LINK) clearly explains how to enable it.
This should be the basic way of writing view with csrf token enabled..
from django.views.decorators.csrf import csrf_protect
#csrf_protect
def form(request):
if request.method == 'GET':
#your code
context = {}
return render (request, "page.html", context )