How to create a registration form with Django

0

I recently studied Django, but I came across a problem in creating forms, I tried to go in the official documentation of the Framework but I did 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

models.py

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

views.py

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})

    
asked by anonymous 03.06.2018 / 16:59

1 answer

0

Your form is not associated with the template, so it has not inherited the "save" attribute from anywhere. Here you have two ways to correct this, first remove the subclass Meta from the form (it is not being used) and edit the cad_novo_usuario() method 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 form based on a template. Hence change the form class to:

class FormNovoUsuario(forms.ModelForm):

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

And in the cad_novo_usuario() method do:

    # ...
    if request.method == "POST" and form.is_valid:
        form.save()
    
03.06.2018 / 22:34