Django投票基础模型和视图

django-vote-base的Python项目详细描述


安装

$ [sudo] pip install django-vote-base
settings.py
^{pr2}$
models.py
fromdjango.dbimportmodelsfromdjango_vote_base.modelsimportVoteModelclassCollectionVote(VoteModel):obj=models.ForeignKey('Collection',related_name="vote_set",on_delete=models.CASCADE)classMeta:unique_together=[('obj','created_by')]classCollection(models.Model):votes_up_count=models.IntegerField(null=True)votes_down_count=models.IntegerField(null=True)votes_score=models.IntegerField(null=True)defget_vote_down_url(self):return'/vote/collection/down/%s'%(self.pk,)defget_vote_up_url(self):return'/vote/collection/up/%s'%(self.pk,)
urls.py
fromdjango.urlsimportinclude,pathimportviewsurlpatterns=[path('vote/collection/down/<int:pk>',views.VoteDownView.as_view(),name='down'),path('vote/collection/up/<int:pk>',views.VoteUpView.as_view(),name='up')]
views.py

DetailView-上下文变量{{ vote_obj }}和{}

fromapps.collections.modelsimportCollection,CollectionVotefromdjango_vote_base.viewsimportVoteViewMixinclassVoteDetailView(BookmarkViewMixin):vote_model=CollectionVote

XMLHttpRequest视图

fromdjango_vote_base.viewsimportVoteDownView,VoteUpViewfromapps.core.collections.modelsimportCollection,CollectionVoteclassCollectionVoteViewMixin:vote_model=CollectionVotedefget_data(self):collection=Collection.objects.get(pk=self.kwargs['pk'])return{'vote':self.vote,'votes_up_count':collection.votes_up_count,'votes_down_count':collection.votes_down_count,'votes_score':collection.votes_score}classVoteDownView(CollectionVoteViewMixin,VoteDownView):passclassVoteUpView(CollectionVoteViewMixin,VoteUpView):pass

ListView预取用户书签

fromdjango.db.modelsimportPrefetchfromdjango.views.generic.listimportListViewfromapps.collections.modelsimportCollection,CollectionVoteclassCollectionListView(ListView):defget_queryset(self,**kwargs):qs=Collection.objects.all()ifself.request.user.is_authenticated:qs=qs.prefetch_related(Prefetch("vote_set",queryset=CollectionVote.objects.filter(created_by=self.request.user),to_attr='votes'))returnqs
模板
<adata-id="{{ vote_obj.pk }}"class="vote-up-btn {% if vote and vote.vote > 0 %}selected{% endif %}"{%ifrequest.user.is_authenticated%}data-href="{{ vote_obj.get_vote_up_url }}"{%else%}href="{% url 'login' %}?next={{ request.path }}"{%endif%}></a><adata-id="{{ vote_obj.pk }}"class="votes-score">{{ vote_obj.votes_score|default:"0" }}</a><adata-id="{{ vote_obj.pk }}"class="vote-down-btn {% if vote and vote.vote < 0 %}selected{% endif %}"{%ifrequest.user.is_authenticated%}data-href="{{ vote_obj.get_vote_down_url }}"{%else%}href="{% url 'login' %}?next={{ request.path }}"{%endif%}></a>
JavaScript
constvote_buttons=document.querySelectorAll("a.vote-up-btn, a.vote-down-btn");for(constbuttonofvote_buttons){button.addEventListener('click',function(event){event.preventDefault();data_id=button.getAttribute('data-id');varvote_down_btn=document.querySelector(".vote-down-btn[data-id='"+data_id+"']");varvote_up_btn=document.querySelector(".vote-up-btn[data-id='"+data_id+"']");varvotes_score=document.querySelector(".votes-score[data-id='"+data_id+"']");varxhr=newXMLHttpRequest();xhr.open('GET',button.getAttribute('data-href'));xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');xhr.responseType='json';xhr.onload=function(){if(xhr.status!=200){console.error(`Error ${xhr.status}: ${xhr.statusText}`);}if(xhr.status==200){votes_score.innerHTML=xhr.response.votes_score;}};xhr.send();})}

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java不兼容类型:MainActivity无法转换为LifecycleOwner   java安卓是一种更有效的读取大文本文件的方法   java导出LWJGL本地人与项目?(IntelliJ IDEA)   JDK更新后,JavaJShell不再在下一行打印输出   父类对象上的继承Java比较子属性   Java:有没有一个容器可以有效地结合HashMap和ArrayList?   安卓 Java对象指针   java在annotationdriven Spring MVC应用程序中实现大气   java 安卓源代码构建应用找不到安卓supportv4。罐子   文件系统上的抽象层和Java中的jar/zip   java在水平滚动视图中添加多个图像?   java如何从firebase实时数据库中获取字符串数组   WIndows 10工作站上的java未满足链接错误   java命令在终端中工作,但在使用过程中出现“无结束引号”错误。执行官