Problems making the POST in Django

Asked

Viewed 33 times

-1

I am in a part of the project, which is the page of records

Imagem do Forms

I created the View method but it’s not rolling yet

Imagem do metodo na view

From what I looked the button is ok.

Img Admin

The last image is from my admin, where the new users are not appearing

2 answers

2

Failed to save in database. follows an example:

if request.method == 'POST':
        nome = request.POST['nome']
        email = request.POST['email']
        senha = request.POST['password']
        senha2 = request.POST['password2']
        user = User.objects.create_user(
            username=nome, email=email, password=senha,)
        user.save()
        messages.success(request, 'Cadastro realizado com sucesso')
        return redirect('login')
    else:
        return render(request, 'usuarios/cadastro.html')

0

Try with Class based views:

form:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CadastroForm(UserCreationForm):
     class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'email']

In the list Fields, are the default names of the Django user, this reusing the.
In your case it would only be email and password but here is the reference.

View:

from django.views.generic import CreateView
from django.urls import reverse_lazy
from .forms import CadastroForm

    class Usuario(CreateView):
        form_class = CadastroForm
        template_name = 'cadastro.html'
      #  success_url = reverse_lazy('sucesso') #redireciona para algum lugar
      # ou as mensagens personalidadas do cbv
      # Pode dar erro indicando falta de redirecionamento se não tratar.

urls:

from .views import  Usuario
urlpatterns = [

      path('cadastrar/', Usuario.as_view())

html:

<form method="post">

    {%csrf_token%}
    {{ form.as_p }}
    <button type="submit">salvar</button>
</form>

Confirm by looking in the database if the data has been saved.

Browser other questions tagged

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