How can I manipulate data from a form in Django?

Asked

Viewed 225 times

0

I’m a beginner in Django and wanted to know how I can manipulate data sent by the form.

I have the following form:

class CreateNewUser(forms.Form):

    Nome = forms.CharField(max_length=200)
    email = forms.EmailField()
    idade = forms.DecimalField(min_value=5,max_value=120)
    cpf = forms.CharField(label="CPF",max_length=11)
    # Cadastrar um senha depois

View rendering the form:

def cadastro(request):
     # Instânciando o formulário para poder colocar ele na templates
     form = CreateNewUser()
     return render(request, 'cadastro.html', {'form': form})

I can’t find any place that leaves explicit how to access the data sent by the Django form.

  • 1

    Similar question : https://answall.com/questions/185109/comoros-acessar-dados-de-um-imput-dinamico-de-um-formulario-com-django

1 answer

1

You can get the form data through cleaned_data, some usage examples are:

View

@login_required
def add_post(request):
   if request.method == 'POST':
       form = PostForm(request.POST)

       if form.is_valid():
           data_form = form.cleaned_data
           # Obtendo o conteúdo de um Post digitado no formulário e salvando no post
           Post.objects.create(content=data_form['content'], user=request.user)

           return redirect('index')
       else:
           return redirect('index')               

   else:
        return redirect('index')

Form

class CommentForm(forms.Form):
content = forms.CharField(widget=forms.TextInput(attrs={'id': 'input-comment',}), required=False)

def is_valid(self):
    valid = super(CommentForm, self).is_valid()
    # No forms.py, recuperando o conteúdo do post
    content = self.cleaned_data.get('content')

    # Fazendo a validação desse conteúdo
    if content == '':
        self.add_error(_('Seu comentário precisa de um conteúdo'))

    return valid

def add_error(self, message):
    errors = self._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.utils.ErrorList())
    errors.append(message)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.