我是Django的新手,到目前为止,我已经掌握了基础知识,但我正在努力做一些我从天堂学到的教程并没有教会我的东西,基本上我想要做的是,我在models.py中有一个名为delegates_num
的字段,该字段是注册特定课程的代表人数的计数器。每当有人报名参加特定课程时,我希望能够将该字段增加1,课程为[ITIL, Change Management, Management of Risk, Programme Management, PRINCE2]
因此,例如,如果用户预订了ITIL课程,该课程的计数器将增加1.每个课程的空间限制为15个,所以某个地方的条件如下:
if course.name = 'ITIL' && if delegates_num > 15
redirect user to 'course is full page'
else submit registration form and increment delegates_num by 1
对于任何帮助我都非常感激,到目前为止这里是代码:
class Course(models.Model):
MY_CHOICES = (
('Open', 'Open'),
('Closed', 'Closed'),
('Fully Booked', 'Fully Booked'),
)
course_name = models.CharField(max_length=40)
course_code = models.CharField(max_length=40)
price = models.CharField(max_length=40, default='add price')
topic_details = models.TextField(max_length=200)
start_date = models.DateField('start date')
end_date = models.DateField('end date')
status = models.CharField(max_length=20, choices=MY_CHOICES)
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
room = models.CharField(max_length=20)
delegates_num=models.IntegerField()
def add_delegate(self):
#for count, thing in enumerate(args):
self.delegates_num+=1
def __str__(self):
return self.course_name
models.py
<h1>Registration</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
{% if course.course_name = 'ITIL' %}
{{ course.delegates_num|inc }}
{% if course.delegates_num > 15 %}
<meta http-equiv="refresh" content="1;url=http://example.com">
<script type="text/javascript">
window.location.href = "https://yr4-group-project-mfblack.c9users.io/sorry_full/"
</script>
{% endif %}
{% endif %}
<button type="submit" class="save btn btn-default">Save</button>
</form>
book_course.html
def book_course(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
student = form.save(commit=False)
student.save()
student.course.add_delegate()
return redirect('registration_complete')
else:
form = StudentForm()
return render(request, 'website/book_course.html', {'form': form})
views.py
答案 0 :(得分:0)
创建房产可能要容易得多,因为我猜测你没有考虑到人们离开课程 - 或者是用户错误的可能性。
检索计数的属性通常是一个小型数据库操作,并且有一些保证是准确的
@property
def delegates_num(self)
return self.user_set.count()
我假设你有一个fk到用户模型或模拟..