after filling profile completion form by first time user/incomplete profile user, it is redirecting to login page again, but i have given profile page as success url

Purpose: For the first time login user /incomplete profile user, directly website will redirect to profile completion page, then after submitting they will they go their profile page and if any changes required they will edit the required information by clicking the edit button and after completion only they will access the portal.
Problem::after submitting the complete profile form, it is redirecting to login page again, if even login again also it is showing same profile completion page. after submission, it is redirecting to Login not directly to profile

following are the codes i have created for this purpose, i am not seeing any errors in the code with my knowledge, if any one help me out this, its a big help.

codeeditor:Visual Studio 2022
django framework: latest
template using: Django web project in visual studio 2022

I have created a with this code to validate the user

from django.shortcuts import redirect
from django.urls import reverse
from .models import UserProfile

class ProfileCompletionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if (
            request.user.is_authenticated and
            not request.user.is_superuser and
            not request.session.get('profile_completed', False)  # Check if profile_completed session variable is False
                profile = request.user.userprofile
                if not profile.is_complete():
                    if request.path != reverse('profile_completion'):
                        return redirect('profile_completion')
            except UserProfile.DoesNotExist:
                if request.path != reverse('profile_completion'):
                    return redirect('profile_completion')

        response = self.get_response(request)

        if (
            request.user.is_authenticated and
            not request.user.is_superuser and
            request.path == reverse('profile_completion') and
            response.status_code == 302  # Check if the response is a redirect
            request.session['profile_completed'] = True  # Set the profile_completed session variable to True

        return response

then registered in file with ‘app_name.middleware.ProfileCompletionMiddleware’ in MIDDLEWARE.

then created a view in file as

class ProfileView(DetailView, LoginRequiredMixin):
    model = User
    template_name = 'organic/profile.html'
    def get_object(self, queryset=None):
        return self.request.user

class ProfileCompletionView(UpdateView, LoginRequiredMixin):
    model = User
    template_name = 'organic/profile_completion.html'
    form_class = UserRegistrationForm
    success_url = reverse_lazy('profile')
    def get_object(self):
            return self.request.user

    def form_valid(self, form):
        response = super().form_valid(form)
        return redirect(reverse('profile'))

then created urls:

 path('profile/', login_required(views.ProfileView.as_view()), name='profile'),
 path('profile_completion/', login_required(views.ProfileCompletionView.as_view()), name='profile_completion'),


{% extends 'app_name/layout.html' %}

{% block content %}
<h2>Complete Your Profile</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
{% endblock %}


{% extends 'app_name/layout.html' %}

{% block content %}
<h2>Profile Details</h2>
{% endblock %}

class UserRegistrationForm(UserCreationForm):
     class Meta:

class UserProfile(models.Model):
        ('test', 'test'),
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_type = models.CharField(max_length=100, choices=USERCHOICES)
    Name = models.CharField(max_length=100, unique=True)
    Address = models.CharField(max_length=255)
    Country = models.CharField(max_length=100)

    def __str__(self):
        return self.user.username

    def create_user_profile(sender, instance, created, **kwargs):
        if created:

    def is_complete(self):
        # Add your logic here to determine if the profile is complete
        # Return True if the profile is complete, False otherwise
        return (
            self.Name and
            self.Address and

    models.signals.post_save.connect(create_user_profile, sender=User)

i have all the required imports.

Side note: When posting code here, please surround each file’s code between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code, then another line of ```. This forces the forum software to keep your code properly formatted. (I have taken the liberty of editing your post to include those lines in your current post. Please remember to do this for any future posts.)

In no particular order:

  • Mixins must appear before the base class in class definitions

  • I would not use middleware or signals for any of this. The issue with middleware is that it’s going to affect every request that anyone makes forever after.

    • I would make this test in the login page. Upon the successful login, you make the check at that point as to whether the profile needs to be completed. If the profile has been completed, they redirect to the main site, if not, they’re redirected to the profile edit page. (Actually, this might not specifically be needed if you alter the LoginRequiredMixin.)
    • I would then subclass the LoginRequiredMixin to also add the test for a completed profile to ensure someone doesn’t go directly to a URL.
    • It appears, but is not entirely clear, that you’re using a custom User model. Instead of the signal, I would just create the profile instance in the view where the user is created.
  • Side note: If you are going to use middleware, make sure it’s being called in the right order of the middleware being defined. (The order that the middleware is defined is important.)

  • I definitely would not rely upon session data for this. Logging in / logging out can change your session - invalidating the old session and losing any data stored in it.