Django - 用户限制访问相同的值

时间:2017-03-29 11:45:29

标签: javascript jquery python django calendar

我有一个日历,假设它连接到当前的admins-association。管理员在日历中选择日期并注册表单以便设置事件。但是当我使用另一个管理员关联登录时,我仍然可以看到上一个管理员发生的事件:

enter image description here

我想让他们彼此分开。

enter image description here

enter image description here

enter image description here

这些数据对我来说似乎是正确的,因为没有其他管理员没有相同的association_id会看到该事件。

仍然是一个新手,所以以正确的方式引导我,感谢你的帮助,伙计们!

models.py

class Administrator(AbstractUser):
        # inherits the standard User-model
        ...
        association = models.ForeignKey(Association)


class Event(models.Model):
      name = models.CharField(max_length=50)
      location = models.CharField(max_length=100)
      start = models.DateTimeField(blank=False)
      end = models.DateTimeField(blank=False)
      allday = models.BooleanField()
      description = models.TextField(max_length=200)
      synced = models.BooleanField(default=False)
      gid = models.CharField(default='', max_length=100)
      association = models.ForeignKey(Association)


class Association(models.Model):
        asoc_name = models.CharField(max_length=50, null=True, blank=True)

views.py

class calendar(ListView):

   template_name = 'calapp/calendar.html'

   def get_queryset(self):
       queryset =  Event.objects.filter(association=self.request.user.association)
       return queryset


def event_add_edit(request):
   if request.method == 'POST':
       res = {'success': False}

       action = request.POST['action']
       name = request.POST['name']
       location = request.POST['location']
       start = request.POST['start']
       end = request.POST['end']
       allday = request.POST['allday'] == 'true'
       description = request.POST['description']
       synced = request.POST['synced'] == 'true'
       association = Association.objects.filter(asoc_name=request.user.association)
       asoc = Association.objects.get(id=association)

       if action == 'add':
           Event.objects.create(
              name=name,
              location=location,
              start=start,
              end=end,
              allday=allday,
              description=description,
              synced=synced,
              association=asoc
           )

           res['success'] = True
           res['message'] = 'added'
           eid = Event.objects.latest('id').id
           res['eid'] = eid
           res['data'] = Event.objects.values().get(id=eid)
       elif action == 'edit':


           eid = request.POST['eid']
           event = Event.objects.get(id=eid)
           event.name = name
           event.location = location
           event.start = start
           event.end = end
           event.allday = allday
           event.description = description
           event.synced = synced
           event.save()

           res['success'] = True
           res['message'] = 'edited'
           res['eid'] = eid
           res['data'] = Event.objects.values().get(id=eid)

       return JsonResponse(res)
   else:
       raise Http404


def event_get(request, start, end):
   res = {'success': False}
   try:
       datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ')
       datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%fZ')
   except ValueError:
       res['message'] = \
           'Invalid params: ISO format start end dates expected'
       return JsonResponse(res)
   result = Event.objects.filter(start__range=(start,
                                            end)).order_by('start').values()

   res['data'] = list(result)
   res['success'] = True
   return JsonResponse(res)

urls.py

urlpatterns = [
url(r'^calendar/event/get/(?P<start>.+)/(?P<end>.+)/', views.event_get),
url(r'^calendar/event/addedit/', views.event_add_edit),
url(r'^calendar/', views.calendar.as_view(), name='calendar'),

calendar.js(部分内容)

这显示上面日历图片中的值,我怀疑这可能是根据当前用户没有过滤的问题。

    //generate event li
getEventli: function (event) {
    var $li = $("<li class='event-li'>");

    var $ename = $("<span class='event-li-name'>");
    $ename.text(event.name);

    $li.append($ename);

    var $etime = $("<span class='event-li-time'>");
    var start = new Date(event.start),
        h = cal.getHourStr(start.getHours());

    $etime.text(h);
    $li.append($etime);

    // add data-eid attribute for detail show
    $li.data("eid", event.id);
    $li.click(cal.showDetailForm);

    cal.eventsById[event.id].eventli.push($li);

    return $li;
}

calendar.html

<div id="cal-content">
        <div id="cal-content-top">
            <span id="cal-content-top-month">
                <span class="btn-fa" id="cal-content-month-up">
                    <i class="fa fa-chevron-up"></i>
                </span>
            <span class="btn-fa" id="cal-content-month-dn">
                    <i class="fa fa-chevron-down"></i>
                </span>
            <span class="month-long">November</span>
            <span class="year">2015</span>
            </span>
            <span id="cal-content-top-icon">
                <span class="btn-fa" id="btn-sync" id="icon-sync">
                    <i class="fa fa-refresh"></i>
                </span>

        <div id="cal-content-grid">
            <div id="week-days">
                <ul>
                    <li class="week-day">Sunday</li>
                    <li class="week-day">Monday</li>
                    <li class="week-day selected">Tuesday</li>
                    <li class="week-day">Wednesday</li>
                    <li class="week-day">Thursday</li>
                    <li class="week-day">Friday</li>
                    <li class="week-day">Saturday</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell disabled">1</li>
                    <li class="week-row-cell disabled">2</li>
                    <li class="week-row-cell disabled">3</li>
                    <li class="week-row-cell disabled">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell selected">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row last">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
        </div>
    </div>
</div>

calendar.js(大多数可能需要帮助的代码)

// object to manage calendar

var cal = {
   //today's date
   currDate: new Date(),
   //current calendar grid month date
   gridDate: new Date(),
   //stores event with event.id as key
   eventsById: {},
   //stores current month day-cells
   dayCells: [],
   $weekdays: $("#week-days li.week-day"),
   $monthLong: $(".month-long"),
   $year: $(".year"),
   $calThumb: $("#cal-thumb-content-grid"),
   $calContentGrid: $("#cal-content-grid"),
   $monthup: $("#cal-content-month-up"),
   $monthdn: $("#cal-content-month-dn"),


   //select cuurent date week

   selectWeekDay: function () {
       cal.$weekdays
           .removeClass("selected");
       cal.$weekdays
           .eq(cal.currDate.getDay())
           .addClass("selected");
   },

   // generate the calendar grid and thumb

   render: function () {
       //update grid month name and year
       cal.$monthLong
               .html(cal.gridDate.toLocaleDateString("en-us", {
               month: "long"
           }));
       cal.$year.html(cal.gridDate.getFullYear());

       //remove previous days from grid and thumb grid

       cal.dayCells = [];
       $(".week-row").remove();
       $(".thumb-week-row").remove();

       //shift date to first cell date

       var date = new Date(cal.gridDate.getFullYear(), cal.gridDate.getMonth(), 1);
       date.shiftDay(-date.getDay());

       for (var r = 1; r <= 6; ++r) {
           var $weekrow = $("<div class='week-row'><ul></ul></div>"),
               $weekrowul = $weekrow.find("ul:first");

           var $thumbweekrow = $("<div class='thumb-week-row'><ul></ul></div>"),
               $thumbweekrowul = $thumbweekrow.find("ul:first");

           for (var c = 1; c <= 7; ++c) {
               var cls = "week-row-cell",
                   thumbcls = "";
               if (date.getMonth() != cal.gridDate.getMonth()) {
                   cls += " disabled";
                   thumbcls += "disabled";
               }

               if (c == 7) {
                   cls += " last";
               }

               if (date.toDateString() == cal.currDate.toDateString()) {
                   cls += " selected";
                   thumbcls += " selected";
               }
               // append to thumb cal and cal grid
               $thumbweekrowul.append(cal.getThumbWeekCell(date.getDate(), thumbcls));
               var $dayCell = cal.getWeekCell(date, cls);
               $weekrowul.append($dayCell);

               if (date.getMonth() == cal.gridDate.getMonth())
                   cal.dayCells.push($dayCell);

               // date.shiftDay(1);
               date.shiftDay(1);
           }

           if (r == 6) {
               $weekrow.addClass("last");
           }

           cal.$calContentGrid.append($weekrow);
           cal.$calThumb.append($thumbweekrow);
       }

       cal.getMonthEvents();
  },

   //generate cell li of week row of calendar grid

   getWeekCell: function (date, cls) {
       var $li = $("<li>", {
           class: cls
       });

    var $litop = $("<div class='cell-top'>");

    var $dayno = $("<span class='cell-dayno'>");
    $dayno.text(date.getDate());
    $litop.append($dayno);

    var $weather = $("<span class='cell-weather'>");
    $litop.append($weather);

    var $addevent = $("<span class='btn-fa btn-add'>");
    $addevent.data("date", date.toISOString());
    $addevent.html("<i class='fa fa-calendar-plus-o'></i>");
    $addevent.click(cal.showAddForm);

    $litop.append($addevent);

    $li.append($litop);

    var $celllist = $("<div class='cell-list'><ul></ul></div>");
    $li.append($celllist);

    return $li;
},

//generate cell li of thumb calendar

getThumbWeekCell: function (dayno, cls) {
    var $li = $("<li>", {
        class: cls
    });
    $li.html(dayno);
    return $li;
},

// get current month events form db

getMonthEvents: function () {
    var start = new Date(cal.gridDate.getTime());
    start.setDate(1);
    var end = new Date(start.getTime());
    end.shiftMonth(1);

    cal.getEvents(start, end, function (response) {
        if (response.success) {
            response.data.forEach(function (event) {
                //console.log(event);
                cal.addEventLi(event);
            });

            sync.syncEvents();
        }
    })
},

// gets events with start date within [start,end)

getEvents: function (start, end, callback) {
    if (callback === undefined)
        return;

    var url = "/calendar/event/get/";
    url += start.toISOString() + "/";
    url += end.toISOString() + "/";
    console.log(url);

    $.get({
        url: url,
        success: function (response) {
            callback(response);
        }
    })
},

//generate event li

getEventli: function (event) {
    var $li = $("<li class='event-li'>");

    var $ename = $("<span class='event-li-name'>");
    $ename.text(event.name);

    $li.append($ename);

    var $etime = $("<span class='event-li-time'>");
    var start = new Date(event.start),
        h = cal.getHourStr(start.getHours());

    $etime.text(h);
    $li.append($etime);

    // add data-eid attribute for detail show
    $li.data("eid", event.id);
    $li.click(cal.showDetailForm);

    cal.eventsById[event.id].eventli.push($li);

    return $li;
},

//get events to fill today ul

getTodayEvents: function () {
    var start = new Date(cal.currDate.getTime());
    var end = new Date(start.getTime());
    end.shiftHour(5);

    var $lis={};
    var $ul = cal.$todayEvents.find("ul:first");
    $ul.children().remove();
    for (var x = new Date(start.getTime()), i = 0; i < 5; ++i) {
        var h=x.getHours(),
            hstr = cal.getHourStr(h),
            $li = $("<li>" + hstr + "</li>");

        $ul.append($li);
        $lis[h] = $li;

        x.shiftHour(1);
    }

    cal.getEvents(start, end, function (response) {
        if (response.success) {
            console.log("today events", response);
            response.data.forEach(function(event){
                var h = new Date(event.start).getHours();
                $lis[h].append(" - "+event.name);
            })
        }
    });
},

//go to previous month

prevMonth: function () {
    cal.gridDate.shiftMonth(-1);
    cal.render();
},

//go to next month

nextMonth: function () {
    cal.gridDate.shiftMonth(1);
    cal.render();
},

$formwrappers: $(".form-wrapper"),
$formclose: $(".form-close"),

$addEventForm: $("#add-event-form"),
$addEventAction: $("#add-event-action"),
$addEventEid: $("#add-event-eid"),
$addEventSynced: $("#add-event-synced"),
$addEventTop: $("#add-event-top"),
$addEventName: $("#add-event-name"),
$addEventLocation: $("#add-event-location"),
$addEventSdate: $("#add-event-sdate"),
$addEventStime: $("#add-event-stime"),
$addEventEdate: $("#add-event-edate"),
$addEventEtime: $("#add-event-etime"),
$addEventAllday: $("#add-event-allday"),
$addEventDesc: $("#add-event-desc"),

$detailEventForm: $("#detail-event-form"),
$detailEventName: $("#detail-event-name"),
$detailEventLocation: $("#detail-event-location"),
$detailEventDate: $("#detail-event-date"),
$detailEventDescription: $("#detail-event-desc"),
$btnEdit: $("#btn-edit"),
$btnDelete: $("#btn-delete"),

//to show add event form

showAddForm: function () {
    cal.$addEventAction.val("add");
    cal.$addEventSynced.val("false");

    //init inputs

    cal.$addEventName.val("");
    cal.$addEventLocation.val("");
    cal.$addEventAllday[0].checked = false;
    cal.$addEventDesc.val("");
    var date = new Date($(this).data("date"));
    cal.$addEventTop.text(date.toDateString());

    date.setHours(cal.currDate.getHours());
    date.setMinutes(cal.currDate.getMinutes());

    cal.$addEventSdate.val(date.toDateInput());
    cal.$addEventStime.val(date.toTimeInput());
    date.shiftHour(1);
    cal.$addEventEdate.val(date.toDateInput());
    cal.$addEventEtime.val(date.toTimeInput());

    cal.$addEventForm.addClass("visible");
},

//to show details form

showDetailForm: function () {
    var eid = $(this).data("eid"),
        event = cal.eventsById[eid];

    cal.$detailEventName.text(event.name);
    cal.$detailEventLocation.text(event.location);

    var date = new Date(event.start),
        datestr = date.toTimeInput() + ", " + date.toDateString();
    cal.$detailEventDate.text(datestr);

    cal.$detailEventDescription.text(event.description);
    cal.$btnEdit.data("eid", event.id);
    cal.$btnDelete.data("eid", event.id);

    cal.$detailEventForm.addClass("visible");
},

//add event li

addEventLi: function (event) {
    cal.syncedGids[event.gid] = event.id;
    cal.eventsById[event.id] = event;
    cal.eventsById[event.id].eventli = [];

    var start = new Date(event.start),
        end = new Date(event.end);

    if (event.allday) {
        end.shiftDay(-1);
    }

    for (var d = start.getDate(); d <= end.getDate(); ++d) {
        cal.dayCells[d - 1]
            .find("ul:first")
            .append(cal.getEventli(event));
    }
},

1 个答案:

答案 0 :(得分:1)

也许我不明白你想要什么。但我会告诉你有关你的代码的事。

request.user.association是asoc。

# before ---------
association = Association.objects.filter(asoc_name=request.user.association)
asoc = Association.objects.get(id=association)

# after -----------
asoc = request.user.association

Event.objects.create返回事件对象。

# before -------
Event.objects.create(
# omit
)
# omit
eid = Event.objects.latest('id').id
res['eid'] = eid
res['data'] = Event.objects.values().get(id=eid)

# after -------
event = Event.objects.create(
# omit
)
# omit
res['eid'] = event.id
res['data'] = event

更新

您应该按如下方式更改event_get视图

def event_get(request, start, end):
   res = {'success': False}
   try:
       datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ')
       datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%fZ')
   except ValueError:
       res['message'] = \
           'Invalid params: ISO format start end dates expected'
       return JsonResponse(res)

   result = Event.objects.filter(
        association=request.user.association,  # Add filter
        start__range=(start, end)
   ).order_by('start').values()


   res['data'] = list(result)
   res['success'] = True
   return JsonResponse(res)

此外,您应该使用login_required保护此视图。 https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-login-required-decorator