How to implement simple notifications in drf + react? - reactjs

Normally in django with templates I implement basic notifications like this.
For example.
class Article(models.Model):
name = models.CharField()
owner = models.ForeignKey(User)
class Comment():
article = models.ForeignKey(Article)
txt = models.CharField()
user = models.ForeginKey()
datetime = models.DateTimeField(auto_now_add=True)
class ArticleNotification():
article = models.ForeignKey(Article)
msg = models.CharField()
is_seen = models.BooleanField(default=False)
datetime = models.DateTimeField(auto_now_add=True)
If someone commented on article the owner will see notifications.
#transaction.atomic
def post_comment(request, article_id):
comment = Comment.objects.create(article_id=article_id, txt="Nice Article", user=request.user)
ArticleNotification.objects.create(article_id=article_id, msg=f"User {request.user} commented on your post")
Now to show the notifications I normally make a context processor:
# context_processor:
def notifcations(request):
notifs = Notfication.objects.filter(article__owner=request.user).order_by("-datetime")
return {"notifs":notifs}
In this way I can normally implement basic notification system with refresh.
Now in (drf + react) what will be the preferred way for this type of task.
Instead of context processor should I have to make an get api to list notifications
And call this api on every request from react frontend ?

Instead of context processor should I have to make an get api to list notifications
Yes. You can create DRF API view like this
serializers.py
class ArticleNotificationSerializer(ModelSerializer):
class Meta:
model = ArticleNotification
fields = ["id", "article", "msg", "is_seen", "datetime"]
views.py
class ArticleNotificationListView(ListAPIView):
serializer_class = ArticleNotificationSerializer
queryset = ArticleNotification.objects.all()
urls.py
path('notification', ArticleNotificationListView.as_view()),
And call this api on every request from react frontend ?
Yes. Also you can check for Notifications for every 10 seconds with setInterval and componentDidMount hook in your react component.
componentDidMount: function() {
this.countdown = setInterval(function() {
axios.get(
'/notifications/'
).then(r =>
this.setState({ notifications: r.data }); // Changing state
)
}, 10000);
},

For real-time notification, you need something like Django channels or you can set a get api from react which runs after every defined time (say 5 minutes) and would fetch the required notifications based on user.
In your case things in context processor would be in listapiview and later you can fetch all the list.

Related

how to get new data at run time from django?

I am working on a Django project with ReactJs frontend. I have to built a simple chat application in that project where users can communicate with each other.
in django views I have following function to read messages
Views.py
class MessagesListAPI(GenericAPIView, ListModelMixin ):
def get_queryset(self):
condition1 = Q(sender=15) & Q(receiver=11)
condition2 = Q(sender=11) & Q(receiver=15)
return Messages.objects.filter(condition1 | condition2)
serializer_class = MessagesSerializer
permission_classes = (AllowAny,)
def get(self, request , *args, **kwargs):
return self.list(request, *args, **kwargs)
this gives me all the messages between user 11 and user 15.
on frontend I am getting these messages from rest Api by calling above function
frontend
const chatApi = axios.create({
baseURL: 'http://localhost:8000/chat/'
})
const getMessages = async() => {
let data = await chatApi.get(`MessageRead/`).then(({data})=>data);
setMessages(data);
}
I am calling this function in an onClick event of button. and displaying the messages by maping messages array.
problem is that at the time when these messages are open to the user. at that time if a new message(data) is added in database. I have to press that button again and call getMessages function again to display that message.
Is there a way to automatically get that new message(record) without calling this function again by pressing a button?

React and Django: Edit function of CRUD app not working

I'm working on a CRUD app (blog app basically), i sucessfully created the create, read and delete functionality, only update/edit is not working. Im a beginner with redux i really need your help guys to make my app work.
I deployed the code on bitbucket
frontend --> https://bitbucket.org/Yash-Marmat/frontend-part-of-blog-app/src/master/src/
backend --> https://bitbucket.org/Yash-Marmat/backend-part-of-block-app/src/master/
and the backend looks like this (pic below)
When edit a post you are using:
const data = {
newTitle,
newDescription
};
In your model there is:
class Blog(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
When you send data for update the DRF can not match newTitle with title, the same with description.
Your data send for update should be:
const data = {
title: newTitle,
description: newDescription
};

How to connect to Laravel Websocket with React?

I'm building an ordering app, where I do the backend with Laravel and the front end with both ReactJS and React Native
I want real-time updates whenever a customer posts an order and whenever an order gets updated.
Currently, I managed to get WebSocket running that uses the pusher API using devmarketer his tutorial.
I'm successful in echoing the order in the console, but now I want to access the channel using my react app
And at this step is where I am facing difficulties.
As I'm unsure how to create a route that is accessible to both my apps and how to access the channel through this route.
The official laravel documentation gives an example of how to access pusher but not how to connect to it with for example an outside connection (example: my react native app)
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'rapio1',
host: 'http://backend.rapio',
authEndpoint: 'http://backend.rapio/broadcasting/auth',
auth: {
headers: {
// Authorization: `Bearer ${token}`,
Accept: 'application/json',
},
}
// encrypted: true
});
window.Echo.channel('rapio.1').listen('OrderPushed', (e) =>{
console.log(e.order)
})
So my question is how can I access a broadcasting channel on my React apps?
ADDED BACKEND EVENT
class OrderPushed implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $neworder;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Order $neworder)
{
$this->neworder = $neworder;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
//return new Channel('Rapio.'.$this->neworder->id);
return new Channel('Rapio');
}
public function broadcastWith()
{
return [
'status' => $this->neworder->status,
'user' => $this->neworder->user->id,
];
}
}
Are you using the broadcastAs() method on the backend?
It's important to know this in order to answer your question properly because if you are, the Laravel echo client assumes that the namespace is App\OrderPushed.
When using broadcastAs() you need to prefix it with a dot, to tell echo not to use the namespacing so in your example, it would be:
.listen('.OrderPushed')
Also, you don't need to do any additional setup on the backend in order for each client application to connect to the socket server unless you want to have a multi-tenancy setup whereby different backend applications will make use of the WebSockets server.
I also use wsHost and wsPort instead of just host and port, not sure if that makes a difference though
If you can access the data on the frontend by simply console.log'ing to the console you should already be most of the way there.
The way you would actually get the data into your react components depends on if you're using a state management library (such as redux) or just pure react.
Basically, you would maintain a local copy of the data on the frontend and then use the Echo events to update that data. For example, you could have a list of orders in either redux, one of your react components, or somewhere else, that you could append to and modify based on creation, update, and deletion events.
I would personally create an OrderCreated, OrderUpdated, and OrderDeleted event on the backend that would contain the given order model.
class OrdersList extends React.Component {
componentDidMount() {
this.fetchInitialDataUsingHttp();
//Set up listeners when the component is being mounted
window.Echo.channel('rapio.1').listen('OrderCreated', (e) =>{
this.addNewOrder(e.order);
}).listen('OrderUpdated', (e) =>{
this.updateOrder(e.order);
}).listen('OrderDeleted', (e) =>{
this.removeOrder(e.order);
});
}
componentWillUnmount() {
//#TODO: Disconnect echo
}
}

AngularJS + django REST api

I'm attempting to build an api with DRF.
Client is a cordova app backed with AngularJS.
When I try to post some user object using $resource I'm getting a 403 forbidden response from django.
Below is some code which I think is relevant for the issue:
The API Call:
$rootScope.user =
User.get({id: response.id}).$promise.then(angular.noop, function (e) {
if (e.status == 404) { //If not found, register the user.
$rootScope.user = new User();
Object.keys(response).forEach(function (key) {
$rootScope.user[key] = response[key];
});
$rootScope.user.$save(); //Fails here! 403.
}
else
console.log(JSON.stringify(e.msg));
});
The User factory:
.factory('User', function ($resource, serverConstants) {
return $resource(serverConstants.serverUrl + '/users/:id');
})
django view:
# Users
class UserSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.CharField(max_length=100,required=True)
email = serializers.EmailField(required=False,allow_blank=True)
joined = serializers.DateField(required=False,default=datetime.date.today)
class Meta:
model = models.User
fields = ('joined', 'id', 'email')
def get_validation_exclusions(self):
exclusions = super(UserSerializer, self).get_validation_exclusions()
return exclusions + ['owner']
class UserViewSet(viewsets.ModelViewSet):
queryset = models.User.objects.all()
serializer_class = UserSerializer
PS: I've configured angular to use CSRF cookie and django to allow CORS
Thanks in advance!
Your /user/:id endpoint requires authenticated requests.
You need to authenticate your client's requests using one of the methods specified on the previous link.
Given your app runs in a WebView and then has a builtin cookies handling, SessionAuthentication is the more straightforward to implement.
If you want the endpoint to not require authentication, you can set its permission_classes attribute like so:
from rest_framework.permissions import AllowAny
class UserViewSet(viewsets.ModelViewSet):
queryset = models.User.objects.all()
serializer_class = UserSerializer
permission_classes = (AllowAny, )
I guess with DRF you mean the django-rest-framework.
If yes, have a look here:
http://www.django-rest-framework.org/api-guide/authentication/
You can make the view public but using AllowAny.
from rest_framework.permissions import AllowAny
from rest_framework import generics
restapi_permission_classes = (AllowAny,)
class MyListView(generics.ListCreateAPIView):
serializer_class = MyObjectSerializer
permission_classes = restapi_permission_classes
queryset = MyObject.objects.all()
However I'd recommend you to use proper authentication once you are done with testing. I've been using the token authentication.
Have a look at this post for more details:
Django Rest Framework Token Authentication

Can't seem to use optional foreign key relationships when creating new object using Django+AngularJS

I'm using AngularJS on the front-end with Django managing the backend and API along with the Django REST framework package. I have a Project model which belongs to User and has many (optional) Intervals and Statements. I need to be able to create a 'blank' project and add any intervals/statements later, but I'm hitting a validation error when creating the project. Below are the relevant code sections.
Django model code (simplified):
class Project(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='projects', on_delete='models.CASCADE')
project_name = models.CharField(max_length=50)
class Statement(models.Model):
project = models.ForeignKey(Project, related_name='statements', on_delete='models.CASCADE', null=True, blank=True)
class Interval(models.Model):
project = models.ForeignKey(Project, related_name='intervals', on_delete='models.CASCADE', null=True, blank=True)
Django view code (simplified):
class ProjectList(APIView):
def post(self, request, format=None):
serializer = ProjectSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Angular controller code (simplified):
$scope.createProject = function(){
var projectData = {
"user": $scope.user.id,
"project_name": $scope.newProject.project_name
};
apiSrv.request('POST', 'projects', projectData,
function(data){},
function(err){}
);
};
Angular service code (simplified):
apiSrv.request = function(method, url, args, successFn, errorFn){
return $http({
method: method,
url: '/api/' + url + ".json",
data: JSON.stringify(args)
}).success(successFn);
};
Server response:
{"intervals":["This field is required."],"statements":["This field is required."]}
Am I missing something here? I should be able to create a project without a statement or interval, but I'm not able to. Thanks for any suggestions.
Edit: Added Relevant section from ProjectSerializer
class ProjectSerializer(serializers.ModelSerializer):
intervals = IntervalSerializer(many=True)
statements = StatementSerializer(many=True)
class Meta:
model = Project
fields = (
'id',
'project_name',
[removed extraneous project fields]
'user',
'intervals',
'statements'
)
You need to set the read_only attribute on the 'interval' and 'statements' fields
class ProjectSerializer(serializers.ModelSerializer):
intervals = IntervalSerializer(many=True, read_only=True)
statements = StatementSerializer(many=True, read_only=True)
class Meta:
model = Project
fields = ('id', 'project_name', 'user', 'intervals','statements')
or you can specify the read_only fields like this,
class Meta:
model = Project
fields = ('id', 'project_name', 'user', 'intervals','statements')
read_only_fields = ('intervals','statements')

Resources