form-check-input initially checked

I have a boolean value in a model. I have a FormModel class setup to render the form which works fine, however, I am trying to set the initial state of the check box to “checked” when the form is presented. I have been looking through many questions in a variety of forums and have found all kinds of suggestions but none of them have worked. Here is the declaration of the check box field in my ModelForm.

self.fields['installed'].widget.attrs.update({'class': 'form-check-input'})
        self.fields['installed'].initial = True

However, when the form is rendered, the check box is not checked.

I have added validation so that when the form is posted, it alerts the user that the check box needs to be checked, but it should default to checked.

I have seen suggestions to set the default value in the model to True, but in this case it cannot be true. It must be checked as part of an update process as it represents a change in state to this model.

Any ideas on how I can set the initial value of this check box to True/Checked? It should be fairly simple, but apparently it is more difficult than I expected.


I’m assuming that these self.fields... statements are in the __init__ method?

You identify this as a model form, when you’re rendering this form, are you rendering it with an instance of a model? If so, the model’s current state is going to take precedence over the initial value.

Otherwise, please post the model and the view here.

Yes, this is based on a model.

Here is the model definition:

class ChangeLogEntries(models.Model):
    change_date = models.DateField()
    change_note = models.TextField()
    form_name = models.CharField(max_length=100)
    datetimestamp = models.DateTimeField(auto_now=True)
    module_code = models.CharField(max_length=5)
    binary_only = models.BooleanField(default=False)
    installed = models.BooleanField(default=False)
    dateinstalled = models.DateField(blank=True, null=True)

Here is the view:

def editlogentry(request, logentry_id=None):
    log_entry = get_object_or_404(ChangeLogEntries, id=logentry_id)
    error_msg = ""
    heading = "Update Installed Status"
    if request.method == 'POST':
            form = UpdateLogEntryForm(request.POST, instance=log_entry)
            if form.is_valid():
                log_entries = ChangeLogEntries.objects.raw(
                    "select, a.change_date, a.change_note, a.form_name, a.binary_only, b.module_name " +
                    "from changelogx_changelogentries a " +
                    "INNER JOIN changelogx_modules b ON b.module_code = a.module_code " +
                "where a.installed = 0 ")
                return render(request, 'main/updatestatus.html', {"change_list": log_entries})
                return render(request, 'main/editlogentry.html', {'form': form, 'log_entry': log_entry, "error_msg": error_msg,
                                                                  "heading": heading})
        except ValueError:
            error_msg = "Invalid entry"
            return render(request, 'main/editlogentry.html', {"log_entry": log_entry,
                                                              "error_msg": error_msg,
                                                              "heading": heading})
        form = UpdateLogEntryForm(instance=log_entry)
        return render(request, 'main/editlogentry.html', {"log_entry": log_entry, "form": form, "error_msg": error_msg,
                                                          "heading": heading})

So if the value from the model’s current state takes precedence, and that makes sense, it is possible to change the state of the “installed” property to True before rendering the form?

add the line:
log_entry.installed = True
after the log_entry = ... query.

Side note: Your query could be rewritten using the ORM to avoid using the raw SQL. Whether that would be “better” is a subjective opinion.

Okay, that did the trick! Thanks Ken.

Also, what are the implications of using raw SQL in this case? Just asking…I’m very comfortable with SQL as I’ve been working with it for about 30 years now.

Few of any real note, and most of those tend toward being academic rather than practical. (Not being able to effectively use the Pagination object is one. Limited abilities to compose this queryset with others is another.)

Potentially, this becomes another source of errors if the table is refactored (e.g., column name change)

Finally, it could be an issue for those maintaining this code after you.

Again - none of these are earth-shattering, and may not be important at all in your case. That’s why I made it as a side comment. There is value in learning just how powerful the ORM is, and being comfortable with its features, but there is no effective requirement for its exclusive use.

As am I (very comfortable, having started with it when its name was still “SEQUEL”).

But the ORM brings a different set of features and capabilities that fit in quite well with Python in general and Django in particular. (Not surprising since it is a fundamental component of Django.)

Those are all good points. I’ll need to dig into the ORM a bit more. I’m brand new to Python and Django, but I’m really liking what I am seeing.

I think the main reason I was using a raw query in this case is because I needed to do the INNER JOIN to get the description of the module_name for display rather than the module_code. I’m sure there’s a way to also do this join through the ORM.

And yes, I still pronounce it SEQUEL as well :grinning:!

Thanks again Ken!

I’m not talking about the pronounciation, I’m talking about the actual spelling of the language. The name of the language was originally SEQUEL before being shortened to SQL.

Okay, I don’t remember that, but my first exposure was with Microsoft SQL-Server 6.5 and I only remember it referred to as SQL.

Thanks again and have a great day!