Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How to implement CheckboxSelectMultiple form widget correctly?

Here I have a model: models.py

class NodeConfigLog(models.Model):
    nodes = models.CharField(max_length=255)
    command_logs = models.TextField()
    log_time = models.DateTimeField(auto_now_add=True, auto_now=False)

And forms.py:

from django import forms
from . import models
class NodeConfigForm(forms.ModelForm):
    class Meta:
        model = models.NodeConfigLog
        fields = ['nodes', 'command_logs', 'log_time']
        widgets = {'nodes': CheckboxSelectMultiple} 

views.py file:

def node_config(request):
    form = forms.NodeConfigForm
    if request.method == 'POST':
        form = forms.NodeConfigForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "Configuration successfully submitted")
            return HttpResponseRedirect('courses: config')
    return render(request, 'nodes/nodeconfig.html', {'form': form})

But it shows error that name 'CheckboxSelectMultiple' is not defined. What am I doing wrong? In the end I want to get something like that: On website I will have a list of nodes and user can choose (checkbox) to which nodes to send commands.

1 Answer

At first glance when I see this code:

class Meta: model = models.NodeConfigLog fields = ['nodes', 'command_logs', 'log_time'] widgets = {'nodes': CheckboxSelectMultiple}

All the variables used by model & fields are all pre-defined, but for widgets I dont see checkboxSelectMultiple predefined...??

U mean I have to separately assign form to nodes like this?: forms.py

from django import forms
from . import models
class NodeConfigForm(forms.ModelForm):
    nodes = forms.MultipleChoiceField()
    class Meta:
        model = models.NodeConfigLog
        fields = ['command_logs',
                      'log_time']
        widgets = {'nodes': CheckboxSelectMultiple}

If yes, then do I have to add choices in Model?