How to create a registration form with Django

Asked

Viewed 1,151 times

0

I have been studying Django recently, but I came across a problem in creating forms, I tried to go in the official Framework documentation but I could not find the solution.

Forms.py

from django import forms
from .models import Novo_Usuario

class FormNovoUsuario(forms.Form):

    nome = forms.CharField(max_length=200, label='nome')
    sobrenome = forms.CharField(max_length=200, label='sobrenome')
    senha = forms.CharField(max_length=50, label='senha')


    class Meta:
        fields = ('nome', 'sobrenome', 'senha')
        models = Novo_Usuario

py.models

from __future__ import unicode_literals

from django.db import models

class Novo_Usuario(models.Model):
    nome = models.CharField(max_length=200)
    sobrenome = models.CharField(max_length=200)
    senha = models.CharField(max_length=50)

    def __str__(self):
        return self.nome

py views.

from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from .models import Novo_Usuario
from .forms import FormNovoUsuario

def cms(request):
    return render(request, 'base.html')

def cad_novo_usuario(request):
    form = FormNovoUsuario(request.POST or None)
    if request.method == 'POST':
        return form.save()
    return render(request, 'novo_usuario.html', {'form': form})

inserir a descrição da imagem aqui

  • What problem did you find? Explain better where you are struggling

  • Maybe the error is in the save() attribute, because the error I get is 'Formnovousuario' Object has no attribute 'save'

1 answer

1

Your form is not associated with the template, hence it has not inherited the "save" attribute anywhere. Here you have two ways to fix this, in the first remove the sub-class Meta form (it is not being used) and edit the method cad_novo_usuario() to something like this:

    # ...
    if request.method == 'POST':
        novo_usuario = model.Novo_Usuario()
        novo_usuario.nome = form..cleaned_data('nome')
        # ... daí um para cada campo que você tiver ...
        novo_usuario.save()
    return form.save()

Or, you can use the template-based form. Then change the form class to:

class FormNovoUsuario(forms.ModelForm):

    class Meta:
        fields = ('nome', 'sobrenome', 'senha')
        model = Novo_Usuario

And in the method cad_novo_usuario() do:

    # ...
    if request.method == "POST" and form.is_valid:
        form.save()

Browser other questions tagged

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