Render Foreign Key in template as Checkboxes instead of Select in Django

Viewed 835

Say we have this Model:

class Event(models.Model):
    name = models.CharField('Nome do evento', max_length=50)
    code = models.CharField('Código de entrada', max_length=10)
    artists_list = models.ForeignKey(ListGroup, on_delete=None, 
    related_name='lists_names', null=True)

and this View

class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['form'] = CreateEventForm(self.request.POST or None)
        context['defaultTitle'] = 'Novo Evento'
        context['formTitle'] = 'Criar'
        return context

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        form = context['form']
        print(form)
        if form.is_valid():
            form.save()
        return self.render_to_response(context)

and this Form

class CreateEventForm(forms.ModelForm):

    class Meta:
        model = Event
        fields = ('name', 'code', 'artists_list',)

Everything works great, but I would like to be able to select multiple entries that my Foreign key will retrieve. So I would like to render each entry as a checkbox instead of a select. How can I achieve that? I already searched a lot and only found about general charfields, nothing about Foreing Key Here's how its rendering

1 Answers

A foreign key can't point to multiple entries. If you want that, you should use a ManyToManyField.

Related