Django manual form

Hi i want to add manually form in django templates i have my model like that

class ProjectType(models.Model):
    name = models.CharField(_("Project type name"), max_length=150)

    def __str__(self):
        return self.name

my forms.py

class RequestedProjectUserForm(forms.ModelForm):
    class Meta:
        model = RequestedProject
        fields = '__all__'
        exclude = ['client', 'amount', 'progress',
                   'notes', 'deadline', 'refused_cause', 'project_situation']
        widgets = {
            'type_selected': forms.CheckboxSelectMultiple()
        }

    def __init__(self, *args, **kwargs):
        super(RequestedProjectUserForm, self).__init__(*args, **kwargs)
        self.fields['project_name'].widget.attrs.update(
            {'class': 'bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500'})
        self.fields['type_selected'].widget.attrs.update({'class': 'sr-only peer'})```

in template

i have this

{% for error in form.type_selected.errors %}
                <p><small class="text-sm text-red-700 dark:text-red-500">{{ error }}</small></p>
                {% endfor %}
                {% for type_selected in form.type_selected %}
                <label for="{{ type_selected.id_for_label }}"
                    class="inline-flex relative items-center mb-4 cursor-pointer">
                    <input type="checkbox" name="type_selected" id="{{ type_selected.id_for_label }}"
                        class="sr-only peer" {% if type_selected.value %} checked {% endif %}
                        value="{{type_selected.value}}">
                    <div
                        class="w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600">
                    </div>
                    <span
                        class="ml-3 text-sm font-medium text-gray-900 dark:text-gray-300">{{type_selected.choice_label}}</span>
                </label>
                {% endfor %}

when i want to save the forms i got error “” is not a valid value.

haw can i add the value in template

I don’t quite follow what you’re trying to do here.

The field form.type_selected is a field - I don’t see what you’re looking to accomplish by trying to iterate over it. (It might help if you posted your view - it’s not clear what you’re trying to render. And since the form is a model form for the RequestedProject model, it may also help if you posted that model as well.)

Thank you for responding this is my model of RequestedProject and the view

class RequestedProject(models.Model):
    client = models.ForeignKey(User, on_delete=models.CASCADE)
    request_date = models.DateTimeField(auto_now_add=True)
    project_name = models.CharField(_("Project name"), max_length=255)
    slug = AutoSlugField(populate_from="project_name",
                         unique_with='request_date__month')
    type_selected = models.ManyToManyField(ProjectType)
    # Design
    logo = models.BooleanField(_("Create a logo"), default=False)
    ui = models.BooleanField(_("Create a UI for your web"), default=False)
    full_chart = models.BooleanField(_("Create a graphic charter (business card, letter, covers ...)"), default=False)
    # WEB
    web_ecommerce = models.BooleanField(_("Site Ecommerce"), default=False)
    web_pro = models.BooleanField(_("Professional website"), default=False)
    web_app = models.BooleanField(_("Customized site"), default=False)
    renovation = models.BooleanField(_("Renovation"), default=False)
    seo = models.BooleanField(_("Search engine optimization"), default=False)
    # Mobile App
    ios = models.BooleanField(_("IOS"), default=False)
    android = models.BooleanField(_("Android"), default=False)
    app_ecommerce = models.BooleanField(_("App Ecommerce"), default=False)
    # Marketing
    optimizing_ads = models.BooleanField(
        _("Optimization of ads"), default=False)
    strategie = models.BooleanField(
        _("Optimize your digital identity"), default=False)
    description = models.TextField(_("Description of the project and your objectives"), validators=[
        MinLengthValidator(
            150, _("The description must contain at least 150 characters"))
    ])
    referenced_link = models.TextField(
        _("Referenced sites or link of some projects"), blank=True, null=True)
    specifications = models.FileField(
        _("Specifications"), upload_to='project/specifications/%Y/%m/%d/', blank=True, null=True)
    delivery = models.DateField(
        _("Expected delivery date"), blank=True, null=True)

    class Situation(models.TextChoices):
        UNDERSTUDY = 'UNDERSTUDY', _("Under study")
        ACCEPTED = 'ACCEPTED', _("Project accepted")
        REFUSED = 'REFUSED', _("Project refused")
    project_situation = models.CharField(
        _("Project situation"), choices=Situation.choices, default=Situation.UNDERSTUDY, max_length=15)
    # Admin Input
    amount = models.IntegerField(_("Amount $"), blank=True, null=True)

    class Progress(models.TextChoices):
        IN_PROGRESS = "PROG", _("In Progress")
        DONE = "DONE", _("Done")
        PENDING = "PEND", _("Pending")

    progress = models.CharField(
        choices=Progress.choices, default=Progress.PENDING, max_length=5)
    deadline = models.DateField(
        _("Expected delivery date"), blank=True, null=True)
    notes = models.TextField(_("Admin notes"), blank=True, null=True, validators=[
        MinLengthValidator(
            150, _("The notes must contain at least 150 characters"))
    ])
    refused_cause = models.TextField(
        _("Cause of project rejection"), blank=True, null=True, validators=[
            MinLengthValidator(
                150, _("The description must contain at least 50 characters"))
        ])

    def __str__(self):
        return '%s - %s' % (self.project_name, self.type_selected)

    def get_absolute_url(self):
        return reverse("project-review", kwargs={"slug": self.slug})

and the view

class ProjectReview(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = RequestedProject
    template_name = 'project/admin/projects/index.html'
    form_class = RequestedProjectAdminForm
    success_message = _("Project successfully reviewed")

    def form_valid(self, form, **kwargs):
        self.object = form.save(commit=False)
        sender = self.request.user
        recipient = self.object.client
        target = self.object.get_absolute_url()
        condition = self.object.project_situation
        print(condition)
        if condition == 'REFUSED':
            message = _(
                f"Your project: {self.object.project_name}, is rejected. Check your project details to find out why or contact our support for more details.")
        elif condition == 'ACCEPTED':
            message = _(
                f"Your project: {self.object.project_name}, is accepted. Our team prepares tasks")
        elif condition == 'UNDERSTUDY':
            message = _(
                f"Your project: {self.object.project_name}, under study")
        notify.send(sender, recipient=recipient, verb='Message',
                    description=message,   **kwargs)

        # project_name = form.cleaned_data['name']
        subject, from_email, to = _("Be&Go: Project"), 'noreply@beandgo.io', 'joudakenore@gmail.com' #recipient.email
        text_content = _('Project Created.')
        html_content = _(f'<p>Project: <strong>{self.object.project_name}</strong> is created.<br> check your project progress from <a href="{target}" targe="_blanc">{self.object.project_name}</a>.</p><p>Sincerely<br>Be&Go Team</p>')
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        return super().form_valid(form)

and in the is a screenshot

and this is the error


when inspect elements I see that the value is empty

So it appears the issue is:

You’re trying to render a value attribute of type_selected. However, type_selected are objects of type ProjectType, which don’t have value as an attribute.

I believe what you want to be rendering for the value of that widget is the primary key for ProjectType which appears would be id.

I tried to add {{type_selected.id}} and {{type_selected.auto_id}} but it does not work, it does not show the id.

You have:

What is RequestedProjectAdminForm?

I only see this form in your post: