Django CBV将产品链接到用户,并仅允许修改其数据

时间:2019-07-02 21:54:43

标签: python django django-models django-views

您好,例如,我不了解django CBV的原理,我想创建一个匿名投票系统,并且想确保例如用户只能投票一次,并且我希望也加密投票并进行一些操作在场上。另外,我想知道如何将创建的对象连接到用户,从而允许它仅更改这些对象(选择)

我的模特


#model 

from datetime import datetime

from django.http import Http404
from django.db import models, connection
from django.db.models import Q
from dzstudent import settings

from django.contrib.auth import get_user_model
User = get_user_model()


class VotingNotAllowedException(Exception):
    pass


class Election(models.Model):
    """
    Represents elections. which can be composed of one or more ballots.
    Voting only allowed between vote_start and vote_end dates.
    """

    userElec = models.ForeignKey(
        User, related_name="election", on_delete=models.CASCADE)
    name = models.CharField(max_length=255, blank=False, unique=True,
                            help_text="Used to uniquely identify elections. Will be shown " +
                            "with ' Election' appended to it on all publicly-visible pages.")
    introduction = models.TextField(blank=True,
                                    help_text="This is printed at the top of the voting page below " +
                                    "the header. Enter the text as HTML.")
    vote_start = models.DateTimeField(help_text="Start of voting")
    vote_end = models.DateTimeField(help_text="End of voting")

    def __str__(self):
        return self.name

    def voting_allowed_for_user(self, user):
        """
        Returns True if not is between vote_start and vote_end, inclusive,
        and given user is in allowed_voters and user hasn't already voted.
        """
        return (self.voting_allowed() and not self.has_voted(user))

    def voting_allowed(self):
        """
        Returns True if now is between vote_start and vote_end, inclusive.
        """
        return self.vote_start <= datetime.now() <= self.vote_end

    def create_vote(self, user):
        """
        Checks that the given account can vote in this election, and if so,
        creates and returns a Vote object.
        """
        if not self.voting_allowed_for_user(user):
            msg = 'The account %s is not allowed to vote in this election.'
            raise VotingNotAllowedException(msg % unicode(user))
        return self.votes.create(account=user, election=self)

    def has_voted(self, account):
        """ Returns True if given account has voted for this election """
        return self.votes.filter(account=account).count() != 0

    @staticmethod
    def get_latest_or_404():
        """
        Similar to the get_object_or_404() function, except returns the
        latest Election instead.
        """
        try:
            return Election.objects.latest()
        except Election.DoesNotExist:
            raise Http404("No elections have been entered yet.")

    class Meta:
        ordering = ['vote_start']
        get_latest_by = "vote_start"


class Vote(models.Model):
    """
    Vote associates individual candidate selections with an account and
    an election.
    """

    TYPES = (
        ("P", "yes"),
        ("C", "No"),
        ("N", "Neutre"),
    )
    vote = models.ForeignKey(
        Election, related_name="votes", on_delete=models.CASCADE)

    type_vote = models.CharField(max_length=2, blank=False, choices=TYPES,
                                 default="P")

    secretKey = models.CharField(max_length=255, blank=False, unique=False,)

    def __unicode__(self):
        return unicode(self.account) + " - " + unicode(self.election)

我的观点

from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy

from .models import Election


class ElectionsList(ListView):
    model = Election
    template_name = 'index2.html'


class ElectionsCreate(CreateView):
    model = Election
    fields = ['name', 'introduction', 'vote_start', 'vote_end']
    template_name = 'create_election.html'
    success_url = reverse_lazy('vote: movies_list')


class ElectionsUpdate(UpdateView):
    model = Election
    fields = ['name', 'introduction', 'vote_start', 'vote_end']
    template_name = 'edit_election.html'
    success_url = reverse_lazy('vote: movies_list')


class ElectionsDelete(DeleteView):
    model = Election
    template_name = 'delete_election.html'
    success_url = reverse_lazy('vote: movies_list')

0 个答案:

没有答案