django - Can I render model properties in a form which uses that model as a foreign key? -
given following models
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) 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 number of registrations camp""" size = camp.objects .filter(registration__camp_id=self.camp_id) .count() return size def is_full(self): """returns false if size of camp less capacity, otherwise returns true""" is_full = false if self.size() < self.capacity else true return is_full def is_open(self): """returns true if camp open 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 camp 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)
and following form
class registrationform(forms.modelform): class meta: model = registration fields = ['camp']
is possible make use of various camp model methods (for example is_full, is_open, etc) choose checkboxes rendered in template registrationform instance in context of? there way access these methods via registrationform object in view's context or template?
ideally hide camp instances is_open() returns false. render html class attribute "waitlisted" input tags on camp instances return true is_full(). like
<input type="checkbox" class="waitlisted" ...>camp week 10</input>
got it!
you can access queryset , methods model instances using .field.queryset
attribute of form field shown below.
{% 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 %}
i believe work model methods require 0 arguments, sufficient needs.
Comments
Post a Comment