Мой метод form_valid не работает должным образом

Я работал в проекте и мне трудно понять, почему мой метод form_valid не работает для ProfileCreateView. Я создал модель профиля для пользователя. Вот код:

# views.py
from django.views.generic import CreateView
from .models import UserProfile
from django.urls import reverse_lazy

class ProfileCreateView(CreateView):
   model = UserProfile
   template_name = "profile/profile_create.html"
   fields = ('profile_picture', 'bio', 'occupation', 'hobbies', 'date_of_birth')
   success_url = reverse_lazy("login")

   def form_valid(self, form):
      form.instance.author = self.request.user
      return super().form_valid(form)

  # template
  {% extends 'base.html' %}

  {% block title %}Create Your Profile{% endblock title %}
  {% load crispy_forms_tags %}
  {% block content %}
  <div class="container border border-success rounded mt-4 ">
  <h2 class="display-6 fst-italic mt-3 mb-3">Create Your Profile</h2>
  <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form|crispy}}

     <button type="submit" class="btn btn-outline-primary mt-4 mb-4">Create my 
        profile</button>
    </form>

   {% endblock content %}

   # models.py
   from django.db import models
   from django.contrib.auth import get_user_model
   import uuid
   from django.core.files.storage import FileSystemStorage


   class UserProfile(models.Model):
      author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
      profile_picture = models.ImageField(upload_to='images/')
      id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
      bio = models.TextField(blank=True)
      occupation = models.CharField(max_length=100)
      hobbies = models.TextField(blank=True)
      date_of_birth = models.TimeField()

      def __str__(self):
           return self.author.username + ("'s profile")

пожалуйста, подскажите, как правильно это сделать!

Вот мое решение, использующее django UserCreationForm, но вы также можете создать пользовательскую форму для регистрации пользователей, но это отлично работает, поскольку django будет обрабатывать форму для создания новых пользователей.

from django.contrib.auth.forms import UserCreationForm

class ProfileCreateView(CreateView):
   template_name = "profile/profile_create.html"
   form_class = UserCreationForm
   success_url = reverse_lazy("login")

    def form_valid(self, form):
        result = super(ProfileCreateView,
                        self).form_valid(form)
        
        cd = form.cleaned_data
        user = authenticate(username=cd['username'],
                            password=cd['password1'])
        login(self.request, user)
        return result 
      
Вернуться на верх