0

EDITS AVAILABLE BELOW!

My goal:

Category1

----Option1

----Option2

--Option3

Category2

----Option1

----Option2

etc.

I have a parent model (Venue) and a child model (Amenity). A venue can have many amenities.

while configuring my initial data and presenting it with {{form.as_p}} everything works as expected.

But when I try to render my own custom form, so that I can apply a loop, It doesn't pre-populate them.

Here is my template:

<form method="POST" class="ui form">
    {% csrf_token %}
    {% for category in categories %}
    <h4 class="ui horizontal divider header">
        <i class="list icon"></i>
        {{category.category}}
    </h4>
    <p class="ui center aligned text"><u>{{category.description}}</u></p>

    {% for amenity in category.amenity_set.all %}

    <div class="inline field">
        <label for="choices_{{amenity.id}}"></label>
        <div class="ui checkbox">
            <input id="choices_{{amenity.id}}" type="checkbox" value="{{amenity.id}}" name="choices">

            <label><span data-tooltip="{{amenity.description}}" data-position="top left">{{amenity}}</span></label>
        </div>

    </div>
    {% endfor %}
    {% endfor %}
    <button type="submit" name="submit" class="ui button primary">Next</button>
</form>

my ModelForm:

class AmenitiesForm(ModelForm):
    class Meta:
        model = Venue
        fields = ('choices',)


    choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=forms.CheckboxSelectMultiple,)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if kwargs.get('instance'):
            initial = kwargs.setdefault('initial', {})
            initial['choices'] = [c.pk for c in kwargs['instance'].amenity_set.all()]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self)
        instance.amenity_set.clear()
        instance.amenity_set.add(*self.cleaned_data['choices'])
        return instance

and my views.py:

class AddAmenitiesView(LoginRequiredMixin, CreateView):
    """
    AddAmenitiesView is the view that prompts the user to select the amenities of their venue.
    """
    model = Venue
    form_class = AmenitiesForm
    template_name = 'venues/add_amenities.html'

    def parent_venue(self):
        """
        returns the parent_venue based on the kwargs
        :return:
        """
        parent_venue = Venue.objects.get(id=self.kwargs["venue_id"])
        return parent_venue

    def get_initial(self):
        initial = super().get_initial()
        initial['choices'] = self.parent_venue().amenity_set.all()
        return initial

    def form_valid(self, form):
        venue = Venue.objects.get(id=self.kwargs['venue_id'])
        form.instance = venue
        # form.instance.owner = self.request.user
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["parent_venue"] = self.parent_venue()
        context["categories"] = AmenitiesCategory.objects.all()
        return context

    def get_success_url(self):
        return reverse('add-amenities', kwargs={'venue_id': self.object.id,})

I suppose it has to do with my template since rendering the form normally, it does prepopulate the model.

Thank you for taking the time!

EDIT: With Raydel Miranda's answer below I managed to edit the templates for how the form gets presented:

forms.py:

class CustomAmenitiesSelectMultiple(CheckboxSelectMultiple):
    """
    CheckboxSelectMultiple Parent: https://docs.djangoproject.com/en/2.1/_modules/django/forms/widgets/#CheckboxSelectMultiple
    checkbox_select.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_select.html
    multiple_input.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/multiple_input.html
    checkbox_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_option.html
    input_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html

    """
    template_name = "forms/widgets/custom_checkbox_select.html"
    option_template_name = 'forms/widgets/custom_checkbox_option.html'


class AmenitiesForm(ModelForm):
    class Meta:
        model = Venue
        fields = ('choices',)

    choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=CustomAmenitiesSelectMultiple,)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if kwargs.get('instance'):
            initial = kwargs.setdefault('initial', {})
            initial['choices'] = [c.pk for c in kwargs['instance'].amenity_set.all()]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self)
        instance.amenity_set.clear()
        instance.amenity_set.add(*self.cleaned_data['choices'])
        return instance

custom_checkbox_select.html:

{% with id=widget.attrs.id %}
<div class="inline field">
    <div {% if id %} id="{{ id }}" {% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}" {% endif %}>
        {% for group, options, index in widget.optgroups %}{% if group %}
        <div>
            {{ group }}
            <div>
                {% if id %} id="{{ id }}_{{ index }}" {% endif %}>{% endif %}{% for option in options %}
                <div class="checkbox">{% include option.template_name with widget=option %}</div>
                {% endfor %}{% if group %}
            </div>

        </div>
        {% endif %}{% endfor %}
    </div>
</div>

{% endwith %}

custom_checkbox_option.html :

<label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %}>{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} {{ widget.label }}</label>

As requested, also my models.py:

class TimeStampedModel(models.Model):
    """
    An abstract base class model that provides self-updating
    "created" and "modified" fields.
    """

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class VenueType(TimeStampedModel):
    type = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.type


class Venue(TimeStampedModel):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    type = models.ForeignKey(VenueType, on_delete=models.CASCADE)
    total_capacity = models.PositiveIntegerField(default=0)
    description = models.TextField(blank=False)
    contact_number = PhoneNumberField(blank=True)
    contact_email = models.EmailField(blank=True)
    published = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class AmenitiesCategory(TimeStampedModel):
    category = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.category


class Amenity(TimeStampedModel):
    category = models.ForeignKey(AmenitiesCategory, on_delete=models.CASCADE)
    venues = models.ManyToManyField(Venue, blank=True)
    space = models.ManyToManyField(Space, blank=True)
    name = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['category']
Tony
  • 2,382
  • 7
  • 32
  • 51

1 Answers1

0

You said while configuring my initial data and presenting it with {{form.as_p}} everything works as expected, if so, use {{ form.choices }} in order to render that field.

<form method="POST" class="ui form">
    {% csrf_token %}  
    {{form.choices}}
   <button type="submit" name="submit" class="ui button primary">Next</button>
</form>

Then, what you need is have a custom CheckboxSelectMultiple with its own template (in case you want a custom presentation to the user), and use it in your form:

Custom CheckboxSelectMultiple could be:

class MyCustomCheckboxSelectMultiple(CheckboxSelectMultiple):
    template_name = "project/template/custom/my_checkbox_select_multiple.html"

And in the form:

class AmenitiesForm(ModelForm):
    # ... 
    choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=forms.MyCustomCheckboxSelectMultiple)
    # ...

How to implement the template my_checkbox_select_multiple.html, is up to you.

If you're using some Django prior to 1.11, visit this link to learn about a others things you've to do in order to customize a widget template.

Django widget override template

Hope this help!

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • Thank you, ill try things out now and will let you know! – Tony Jan 20 '19 at 21:19
  • @TonyKyriakidis, it is nothing, in my experience, it is always better to overwrite the widget template, it is not only data you can tell how to render, errors too. Othe the other hand, the custom widget becomes a more reusable piece of code. – Raydel Miranda Jan 20 '19 at 21:23
  • I haven't managed to get it to work yet. looping through categories and presenting their amenities is the part thats tricking me – Tony Jan 21 '19 at 13:29
  • I would like to see your models. – Raydel Miranda Jan 21 '19 at 13:52