给出以下模型
class Camp(models.Model):
camp_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=45)
LEVEL_CHOICES = (
("junior", "Junior"),
("adventure", "Adventure"),
)
level = models.CharField(choices=LEVEL_CHOICES, max_length=9)
CAPACITY_CHOICES = [(i, i) for i in range(1, 101, 1)]
capacity = models.IntegerField(choices=CAPACITY_CHOICES)
start_date = models.DateField()
end_date = models.DateField()
open_date = models.DateField()
closed_date = models.DateField()
fee = models.FloatField()
def size(self):
"""Returns the number of registrations for this camp"""
size = Camp.objects
.filter(registration__camp_id=self.camp_id)
.count()
return size
def is_full(self):
"""Returns False if size of this camp is less than its capacity,
otherwise returns True"""
is_full = False if self.size() < self.capacity else True
return is_full
def is_open(self):
"""Returns True if the camp is open for registration,
otherwise returns False"""
is_open = True if self.open_date
<= timezone.now().date()
< self.closed_date
else False
return is_open
def is_active(self):
"""Returns True if the camp is currently in session,
otherwise returns False"""
is_active = True if self.start_date
<= timezone.now().date()
<= self.end_date
else False
return is_active
def __str__(self):
name = self.name + " " + self.level
return name
class Registration(models.Model):
registration_id = models.AutoField(primary_key=True)
# other fields omitted
camp = models.ForeignKey(Camp)
creation_date = models.DateTimeField(auto_now_add=True, editable=False)
def __str__(self):
return str(self.registration_id)
以下表格
class RegistrationForm(forms.ModelForm):
class Meta:
model = Registration
fields = ['camp']
是否可以使用各种Camp模型方法(例如is_full,is_open等)来选择在RegisterForm实例所在的模板中呈现哪些复选框?有没有办法通过视图的上下文或模板中的RegistrationForm对象访问这些方法?
理想情况下,我想隐藏is_open()返回false的任何Camp实例。 我还想为Camp实例上的输入标记呈现HTML类属性“waitlisted”,为is_full()返回true。像
这样的东西<input type="checkbox" class="waitlisted" ...>Camp Week 10</input>
答案 0 :(得分:0)
知道了!
您可以使用表单字段的.field.queryset
属性访问模型实例的QuerySet和方法,如下所示。
{% for camp in registration_form.camp.field.queryset %}
<p{% if camp.is_full %} class="waitlisted"{% endif %}>
<label>{{ camp }}</label>
<input type="checkbox" name="camps" />
</p>
{% endfor %}
我相信这只适用于需要零参数的模型方法,但足以满足我的需求。