Django:仅在符合条件的情况下删除/更新模型

时间:2019-07-13 09:36:58

标签: django forms model crud preconditions

我是python / django的新手,在这种情况下我需要帮助:

WeeklyCheck =开始日期>>>结束日期- 活动周

  • 用户检查中某一日期的出勤率,因为该周有效

  • 用户可以 删除/更新检查自己所做的检查,但前提是该周处于活动状态。

然后:

周=开始日期->结束日期- 周不活动

  • 现在用户不能 删除/更新以检查由于周未激活而进行的出勤。

models.py

class WeeklyCheck(models.Model):
start_date = models.DateField(blank=False, null=True, verbose_name='Start date')
end_date = models.DateField(blank=False, null=True, verbose_name='End Date')
active = models.BooleanField(default=True, verbose_name='Active?')

def __str__(self):
    return '{} to {} - {}'.format(self.start_date, self.end_date, self.active)

class Attendance(models.Model):
user = models.ForeignKey(User, related_name='attendance_user', on_delete=models.CASCADE)
date = models.DateField(blank=False, null=True, verbose_name='Date')
check = models.BooleanField(default=True, verbose_name='Check')

def __str__(self):
    return '{} / {} / {}'.format(self.user, self.date, self.check)

forms.py

class WeeklyCheckForm(forms.ModelForm):
class Meta:
    model = WeeklyCheck
    fields = [
        'start_date',
        'end_date',
        'enable',
    ]

class AttendanceForm(forms.ModelForm):
class Meta:
    model = Attendance
    fields = [
        'user',
        'date',
        'check',
    ]

views.py

def check_edit(request, pk=None, pkk=None):
    weeks = WeeklyCkeck.objects.all()
    user = get_object_or_404(User, id=pk)
    check = get_object_or_404(Attendance, id=pkk)
    form = AttendanceForm(request.POST or None, request.FILES or None, instance=check)

    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect(reverse("check_list", kwargs={'pk': pk}))

    context = {
        "user": user,
        "check": check,
        "form": form,
        "weeks": weeks,
    }

    return render(request, 'check_edit.html', context)


def check_delete(request, pk=None, pkk=None):
    user = get_object_or_404(User, id=pk)
    check = get_object_or_404(Attendance, id=pkk)

    if request.method == 'POST':
        check.delete()

        return HttpResponseRedirect(reverse("check_list", kwargs={'pk': pk}))
    else:
        context = {
            "user": user,
            "check": check,
        }
    return render(request, 'check_delete.html', context)

有人可以帮助我做到这一点或为我指明正确的方向吗?谢谢!

0 个答案:

没有答案