[英]How can i implement Notifications system in django
I created an app where user's can post a question and get answers from others users.我创建了一个应用程序,用户可以在其中发布问题并从其他用户那里获得答案。 Now I want to implement a notification system, so that when a user answer a question, the author of that question will receive notification.
现在我想实现一个通知系统,这样当用户回答问题时,该问题的作者会收到通知。 Like social media notifications.
就像社交媒体通知一样。
The home templates:主页模板:
<div class="container">
<div class="row justify-content-center">
<div class="row justify-content-center">
<div class="col-md-6">
<a href="{% url 'question' %}" class="btn btn-primary m-1">Ask Question</a>
<a href="{% url 'notification' %}" class="btn btn-primary m-1">Notifications</a>
<a href="{% url 'FeedBack' %}" class="btn btn-primary m-1">FeedBack</a>
<a href="{% url 'login' %}" class="btn btn-primary m-1">Log Out</a>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-center">
{% for question in list_of_question reversed %}
<div class="col-md-4">
<div class="card my-3">
<div class="card-header">
<p class="card-title">{{question.user.username.upper}}</p>
</div>
<div class="card-body">
<a href="{% url 'view-Question' question.id %}" style="text-decoration: none;">
<p class="card-title">{{question.title}}</p>
</a>
<p>Category: {{question.category}}</p>
</div>
</div>
</div>
{%endfor%}
</div>
</div>
the models:型号:
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=False, null=False)
body = RichTextField(blank=False, null=False)
category = models.CharField(max_length=50, blank=False, null=False)
def __str__(self):
return str(self.title)
class Answer(models.Model):
user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE)
answer = RichTextField(blank=False, null=False)
post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
The views:观点:
class My_Question(LoginRequiredMixin, CreateView):
model = Question
fields = ['title', 'body', 'category']
template_name = 'question.html'
success_url = reverse_lazy('index')
def form_valid(self, form):
form.instance.user = self.request.user
return super (My_Question, self).form_valid(form)
class My_Answer(LoginRequiredMixin, CreateView):
model = Answer
fields = ['answer']
template_name = 'answer.html'
success_url = reverse_lazy('index')
def form_valid(self, form):
form.instance.user = self.request.user
form.instance.post_id = self.kwargs['pk']
return super (My_Answer, self).form_valid(form)
def viewQuestion(request, pk):
question = Question.objects.get(id=pk)
answers = Answer.objects.filter(post_id=question)
context = {'question':question, 'answers':answers}
return render(request, 'viewQuestion.html', context)
the home page view:主页视图:
@login_required(login_url='login')
def index(request):
query = request.GET.get('q', None)
list_of_question = Question.objects.all()
if query is not None:
list_of_question = Question.objects.filter(
Q(title__icontains=query) |
Q(category__icontains=query)
)
context = {'list_of_question':list_of_question}
return render(request, 'index.html', context)
the urls网址
path('index/', views.index, name='index'),
path('view/<int:pk>/', views.viewQuestion, name='view-Question'),
path('question/<int:pk>/answer/', views.My_Answer.as_view(),
name='answer'),
path('question/', views.My_Question.as_view(), name='question'),
Here is an outline for a basic notification system in Django:以下是 Django 中基本通知系统的概要:
You need a model to store notifications.您需要一个模型来存储通知。 Each notification belongs to a user and has content (ie a text message).
每个通知都属于一个用户并具有内容(即文本消息)。 You also need to store whether a message has been read and a timestamp:
您还需要存储是否已读取消息和时间戳:
class Notification(models.Model):
is_read = models.BooleanField(default=False)
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
You can then create a new notification for a user when needed, eg when another user answers a question you can also create a notification for the question's owner in the view.然后,您可以在需要时为用户创建新通知,例如,当另一个用户回答问题时,您还可以在视图中为问题所有者创建通知。
class My_Answer(LoginRequiredMixin, CreateView):
...
def form_valid(self, form):
...
form.instance.user = self.request.user
question_author = form.instance.post.user
Notification.objects.create(user=question_author, text="New answer!")
...
return super().form_valid(form)
Then you need a page that lists all notifications for the current user.然后,您需要一个列出当前用户的所有通知的页面。 That can be implemented with a standard list view.
这可以通过标准列表视图来实现。
The query would look something like this:查询看起来像这样:
class NotificationListView(ListView):
model = Notification
def get_queryset(self):
return Notifications.objects.filter(user=self.request.user).order_by("-timestamp")
You of course also need to define a URL and a template for this new view.当然,您还需要为这个新视图定义一个 URL 和一个模板。 We will define the URL name as
notifications
.我们将 URL 名称定义为
notifications
。
Finally, you need to inform users about new notifications.最后,您需要通知用户有关新通知的信息。 This can be done by checking how many unread notifications the current user has and showing a badge on the web badge.
这可以通过检查当前用户有多少未读通知并在网络徽章上显示一个徽章来完成。 This would be part of the index view.
这将是索引视图的一部分。
@login_required(login_url='login')
def index(request):
...
unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count()
context["unread_notifications"] = unread_notifications
...
Then on your home page you need a link to a page that shows all notifications and a badge that shows how many unread notifications the current user has.然后在您的主页上,您需要一个指向显示所有通知的页面的链接和一个显示当前用户有多少未读通知的徽章。 Something like this:
像这样的东西:
<a href="{% url "notifications" %}">
Notifications
{% if unread_notifications %}
<span class="badge bg-secondary">{{ unread_notifications }}</span>
{% endif %}
</a>
If you want to see how this is implemented in a real project, here is the link to an open source project called "Alliance Auth" that implements a portal web page and has a very similar notification architecture.如果你想看看这是如何在一个真实的项目中实现的,这里是一个名为“Alliance Auth”的开源项目的链接,它实现了一个门户网页并具有非常相似的通知架构。 The link is to the notification app within that portal: https://gitlab.com/allianceauth/allianceauth/-/tree/master/allianceauth/notifications
该链接指向该门户中的通知应用程序: https ://gitlab.com/allianceauth/allianceauth/-/tree/master/allianceauth/notifications
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.