mardi 22 novembre 2022

How to work with MultipleCheckBox with Django?

good afternoon, I'm new with django and I'm trying to make an application that registers the attendance of entrepreneurs (I'm currently working with this). There are some services that I would like to select, sometimes the same person requires more than one service per appointment. However, part of the application uses the Models and part uses the Forms, I'd like to keep the two ones separate to keep the code organized, but I have no idea how to do it, I even created a separate class just for the tuple that holds the values, but no I managed to implement, can anyone help me? Here are the codes:

models.py

    from django.db import models
    from django_cpf_cnpj.fields import CPFField, CNPJField    
    
    class CadastroEmpreendedor(models.Model):
    
        ABERTURA = 'ABERTURA MEI'
        ALTERACAO = 'ALTERAÇÃO CADASTRAL'
        INFO = 'INFORMAÇÕES'
        DAS = 'EMISSÃO DAS'
        PARC = 'PARCELAMENTO'
        EMISSAO_PARC = 'EMISSÃO DE PARCELA'
        CODIGO = 'CÓDIGO DE ACESSO'
        REGULARIZE = 'REGULARIZE'
        BAIXA = 'BAIXA MEI'
        CANCELADO = 'REGISTRO BAIXADO'
        
        descricao_atendimento = (
            (ABERTURA, 'FORMALIZAÇÃO'),
            (ALTERACAO, 'ALTERAÇÃO CADASTRAL'),
            (INFO, 'INFORMAÇÕES'),
            (DAS, 'EMISSÃO DAS'),
            (PARC, 'PARCELAMENTO'),
            (EMISSAO_PARC, 'EMISSÃO DE PARCELA'),
            (CODIGO, 'CÓDIGO DE ACESSO'),
            (REGULARIZE, 'REGULARIZE'),
            (BAIXA, 'BAIXA MEI'),
            (CANCELADO, 'REGISTRO BAIXADO'),
        )
    
        cnpj = CNPJField('CNPJ')
        cpf = CPFField('CPF')
        nome = models.CharField('Nome', max_length=120)
        nascimento = models.DateField()
        email = models.EmailField('Email', max_length=100)
        telefone_principal = models.CharField(max_length=11)
        telefone_alternativo = models.CharField(max_length=11, blank=True)
        descricao_atendimento
       
    
        def __str__(self) -> str:
            return self.nome
    
    class DescricaoAtendimento(models.Model):
     
        descricao = models.ForeignKey(CadastroEmpreendedor, on_delete=models.CASCADE)


forms.py


    from django import forms
    from .models import DescricaoAtendimento
    
    class EmpreendedorForm(forms.ModelForm):
        class Meta:
            model = DescricaoAtendimento
            fields = ['descricao']
            widgets = {'descricao': forms.CheckboxSelectMultiple(),}


views.py


    from django.shortcuts import render
    from django.contrib import messages
    
    from .forms import EmpreendedorForm
    
    def cadastro_empreendedor(request):
        if str(request.method) == 'POST':
            form = EmpreendedorForm(request.POST, request.FILES)
            
            if form.is_valid():   
                form.save()
                messages.success(request, 'Produto salvo com sucesso!')
                form = EmpreendedorForm()
            else:
                messages.success(request, 'Erro ao salvar produto!')
        else:
            form = EmpreendedorForm()
        context = {
            'form': form
        }

        return render(request, 'empreendedor.html', context)


If you have any tips, I really appreciate it, I started with django almost a month ago, so there's a long way to go.

P.s: I integrated with PostgreSQL and in the django administration part I can save all the fields in the DB, but I can't implement that part of the checkbox.

At this moment, I get the error:

It is impossible to add a non-nullable field 'descricao' to descricaoatendimento without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit and manually define a default value in models.py.

In the template, I gonna work with bootstrap4 to create the forms. But I'd like to resolve this before. I'm stil learning English, so sorry some mistake.




Aucun commentaire:

Enregistrer un commentaire