简体   繁体   English

如何在 django 中正确实现通知视图?

[英]How to implement Notification view in django correctly?

I have implemented Django notification in my index view.我已经在我的索引视图中实现了 Django 通知。 But I have more view like create a view, update view delete view etc. When the user first login to my application, I show the number of notification and links but when the user switches to another view then number of notification changes to zero.但是我有更多的视图,比如创建视图、更新视图、删除视图等。当用户第一次登录我的应用程序时,我会显示通知和链接的数量,但是当用户切换到另一个视图时,通知数量会更改为零。 Is there any way to retain all the notification in every view of Django.有没有办法在Django的每个视图中保留所有通知。 This is my views.py file这是我的 views.py 文件

 from django.shortcuts import render, redirect, render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.views.generic.edit import FormMixin from .models import Report_item, ClaimForm, UserNotification from django.views import generic from django.db.models import Q from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.utils import timezone from django.views.generic import View, UpdateView, DeleteView from .forms import SignUpForm, LoginForm from django.contrib.auth import logout from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.core.urlresolvers import reverse_lazy from django.db.models import Q def IndexView(request): if request.user.is_anonymous: print("Hello") query_list = Report_item.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(title__icontains=query) | Q(item_type__icontains=query) | Q(city__icontains=query) | Q(Description__icontains=query)).distinct() context = { "object_list": query_list, } return render(request, "feed/index.html", context) else: query_list = Report_item.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(title__icontains=query) | Q(item_type__icontains=query) | Q(city__icontains=query) | Q(location__icontains=query) | Q(Description__icontains=query)).distinct() n = UserNotification.objects.filter(user=request.user, viewed=False) context = { "object_list": query_list, 'notification': n, 'count': n.count(), } return render(request, "feed/index.html", context) class SearchCtaegoryView(generic.ListView): template_name = "feed/index.html" def get_queryset(self): query_list = Report_item.objects.all() slug = self.kwargs.get("slug") if slug: query_list = query_list.filter(Q(category__icontains=slug) | Q(category__iexact=slug)) return query_list class ReportCreate(generic.CreateView): model = Report_item fields = ['title', 'item_type', 'location', 'city', 'image', 'Description'] def form_valid(self, form): self.object = form.save(commit=False) self.object.owner = self.request.user self.object.save() return FormMixin.form_valid(self, form) class ReportDetail(generic.DetailView): model = Report_item template_name = 'feed/detail.html' class ClaimForm(generic.CreateView): model = ClaimForm fields = ['Your_name', 'Your_mobile_number', 'Detail_proof'] class SignUpForm(generic.CreateView): form_class = SignUpForm template_name = "feed/SignUp.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): print("form valid") user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user.set_password(password) form.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('feed:index') else: print(form.errors) return render(request, self.template_name, {'form': form}) class LoginForm(generic.CreateView): print("login") form_class = LoginForm template_name = "feed/SignUp.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): UserModel = get_user_model() email = request.POST['email'] password = request.POST['password'] username = UserModel.objects.get(email=email) user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('') else: print(form.errors) def logout_view(request): logout(request) query_list = Report_item.objects.all() return render(request, "feed/index.html", {'object_list': query_list}) def Profile(request, username): print(username) qs = Report_item.objects.filter(owner__username=username) context = { "object_list": qs, } return render(request, "feed/profile.html", context) class ReportUpdate(UpdateView): model = Report_item fields = ['title', 'item_type', 'location', 'city', 'image', 'Description'] class ReportDelete(DeleteView): model = Report_item success_url = reverse_lazy('feed:index') class RequestItem(generic.CreateView): model = UserNotification fields = ['Name', 'Mobile_No', 'Proof'] def form_valid(self, form): print(self.kwargs) self.object = form.save(commit=False) qs = Report_item.objects.filter(id=self.kwargs.get("pk")) self.object.user = qs[0].owner self.object.save() return HttpResponse("<h1>Hello Friends </h1>") def show_notification(request, notification_id): n = UserNotification.objects.get(id=notification_id) context = { "n": n, } n.viewed = True n.save() return render(request, "feed/notification.html", context) def read_notification(request, notification_id): n = UserNotification.objects.get(id=notification_id) n.viewed = True n.save() return HttpResponse("<h1>Hello Friends chai pee lo</h1>") def mynotification(request): n = UserNotification.objects.filter(user=request.user, viewed=False) print(type(n)) return render_to_response("feed/loggedin.html", {'full_name': request.user.first_name, 'notification': n, }) def read_Notification(request): n = UserNotification.objects.filter(user=request.user) print(type(n)) return render_to_response("feed/loggedin.html", {'full_name': request.user.first_name, 'notification': n, })

Fancy web sites use websockets/AJAX for this.花哨的网站为此使用 websockets/AJAX。 But if you just want it to update on every page load, use a Django context processor.但是,如果您只是希望它在每次页面加载时更新,请使用 Django 上下文处理器。

A context processor is a function that runs every time any template is rendered.. and it doesn't matter which view is being accessed.上下文处理器是每次渲染任何模板时运行的函数......并且访问哪个视图并不重要。 The context processor can add additional template variables that are available in every template.上下文处理器可以添加每个模板中可用的附加模板变量。

So, first write the function.. this function returns a dictionary containing object_list , notification , and count for the current user if they are logged in, or nothing if they are not.因此,首先编写函数。如果当前用户已登录,此函数将返回一个包含object_listnotificationcount的字典,如果未登录则不返回任何内容。

def notification_context(request):
    # Most of the code below is simply copied from the question, it
    # would be different for different applications.  The important thing
    # is that we have to figure out the values to be placed in the template
    # context.

    # If the user is not logged in, we don't know who they are so we return an empty.
    # dictionary which results in nothing new being added to the template context.
    if request.user.is_anonymous:
        return {}

    # look up the notifications for the current user
    query_list = Report_item.objects.all()
    query = request.GET.get('q', None)
    if query:
        query_list = query_list.filter(
            Q(title__icontains=query) |
            Q(item_type__icontains=query) |
            Q(city__icontains=query) |
            Q(location__icontains=query) | 
            Q(Description__icontains=query)
        ).distinct()

    n = UserNotification.objects.filter(user=request.user, viewed=False)

    # The return value must be a dict, and any values in that dict
    # are added to the template context for all templates.        
    # You might want to use more unique names here, to avoid having these
    # variables clash with variables added by a view.  For example, `count` could easily
    # be used elsewhere.
    return {
        'object_list': query_list,
        'notification': n,
        'count': n.count(),
    }

Now tell django to use this processor.现在告诉 django 使用这个处理器。 In your settings.py, find the TEMPLATES section, and under OPTIONS , you'll see context_processors .在您的 settings.py 中,找到TEMPLATES部分,在OPTIONS下,您将看到context_processors Add yours, eg:添加你的,例如:

TEMPLATES = [{
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            # fill in the correct appname.  Also, normally context processor functions go in 
            # context_processors.py, but if you only have one then it doesn't matter much.
            'your_appname.views.notification_context',
        ],
    },
},]

And that's it!就是这样! Now, when the user is logged in, you should get your variables in the template every time.现在,当用户登录时,您应该每次都在模板中获取变量。 And if you want your heading to be in every template with these variables displayed, you should place the heading in a master site template and then all your other templates should extend that one.如果您希望标题在每个显示这些变量的模板中,您应该将标题放在主站点模板中,然后所有其他模板都应该扩展该模板。 That way, you don't duplicate your heading template code 100 times...这样,您就不会重复标题模板代码 100 次...

PS: I'll add one more suggestion. PS:我再补充一个建议​​。 Rather than directly returning your variables, nest them to avoid cluttering up your template namespace.与其直接返回变量,不如嵌套它们以避免弄乱模板命名空间。 Like so:像这样:

return { 'notifications': {
        'object_list': query_list,
        'notification': n,
        'count': n.count(),
    }
}

Then, in your template, it will look like this:然后,在您的模板中,它将如下所示:

{{ notifications.count }}
{{ notifications.query_list }}

Etc etc.. much nicer.等等等等。好多了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Django 视图中正确序列化 API 响应 - How to correctly serialize API response in Django view 如何正确实施“工人” - How to implement 'workers' correctly 如何正确实现memoization? - How to correctly implement memoization? 如何从Django视图中提取新对象以实现无限滚动? - How to pull new objects from Django view to implement endless scrolling? Django抽象模型-如何在抽象视图方法中实现特定的访问? - Django abstract models - how to implement specific access in abstract view method? 如何在 django 视图中实现更新和删除? - How can I implement update and delete in django view? 如何在 Django 3 中为 Post 和 Category 模型实现视图和 url 模式 - How to implement view and url patterns for Post and Category models in Django 3 如何实现同时包含TemplateView和FormView的基于Django类的视图? - How to implement a Django class-based view that is both TemplateView and FormView? Django:如何在基于类的视图中实现 request.session - Django: How to implement request.session in a class based view 如何正确地从联系人表单到Django SQLITe DB实现save()输入数据方法? - How to correctly implement save() input data method from a contact form to Django SQLITe DB?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM