Django Forms and User Authentication


  • Python
  • Django
    • 1
    • IN
    • Verified
    • Posted byPraveen
    • TimeSept. 4, 2024, 7:30 p.m.
    • StatusActive

    Snippet Description

    Explanation: Create a form: This defines a form class based on a Django model. Handle form submission: If the form is valid, save the user instance. Authenticate the user using the provided credentials. If authentication is successful, log the user in. Render the form: Render the form template with the form instance as context..

    Code

      # forms.py
      from django import forms

      class UserForm(forms.ModelForm):
          class Meta:
              model = User
              fields = ['username', 'email', 'password']

      # views.py
      from django.shortcuts import render, redirect
      from django.contrib.auth import authenticate, login
      from .forms import UserForm

      def signup(request):
          if request.method == 'POST':
              form = UserForm(request.POST)
              if form.is_valid():
                  user = form.save()
                  username = form.cleaned_data['username']
                  password = form.cleaned_data['password']
                  user = authenticate(username=username, password=password)
                  if user is not None:
                      login(request, user)
                      return redirect('home')
          else:
              form = UserForm()
          return render(request, 'signup.html', {'form': form})

    Comments

    Related Posts

    Send SMS using Django-Python

    Python Django

    3 Aug. 14, 2022, 4:32 p.m.
    Proud

    Nginx 502 Bad Gateway - Django

    Nginx Python Django

    13 March 17, 2022, 3:34 p.m.
    Proud

    Django Project Updating on Server

    Nginx Python Django

    14 March 17, 2022, 2:17 p.m.
    Proud

    Want to Hire our experts?

    We'll help you to grow your career and growth.
    SignUp Today