Already logged in but can't get my profile page it redirects to non exist pattern and already created user in admin users but got 'AnonymousUser' object has no attribute '_meta'

i am not an expert in custom user models in Django, so i started to use only AbstractUser class to be able to extend Auth functions, but i got this url pattern after login that shouldn’t be existed at all
http://localhost:8000/accounts/profile/ **
while my url in account app is
path(<int:id>, details, name = profile) so when i logged in i got 404 doesn’t exist accounts/profile
** while it should be accounts/1 according to my view function return redirect('accounts:profile')

Also i have a custom user model and when i create new user i got
AnonymousUser’ object has no attribute ‘_meta’
i have both signup and login functions as follows

def sign_up(request):
    # redirect a user to the home page if he is already logged in
    if request.user.is_authenticated:
        user = get_user_model().objects.get(id=request.user.id)
        profile = Profile.objects.get(user=user)
        return render(request, 'account/profile.html', {'form': profile})
    if request.method == 'POST':
        # replace UserCreationForm with SignUpForm for user acc. creation
        form = CustomUserCreationForm(request.POST) # instead of form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            #user.set_password(password)
            #user.save()
            user = authenticate(request, username=username, password=password)
            # Profile.objects.create(user=new_user) #that line already been created by the signal
            login(request, user)
            # display a nice message when a new user is registered
            messages.success(request, _('Your profile was successfully created!')) # messages.info(request,"Successfully Register ...")
            return redirect('accounts:profile')
        else:
            return render(request, 'registration/signup.html', {'form': form})
    else:
        form = CustomUserCreationForm()   # replace UserCreationForm with SignUpForm == form = UserCreationForm()
    return render(request, 'registration/signup.html', {'form': form})
def log_in(request):
    if request.user.is_authenticated:
        return redirect('accounts:profile')  # return render(request, 'homepage.html')
    if request.method == "POST":
        form = LoginForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data('username')
            password = form.cleaned_data('paswword')
        try:
            user = User.objects.get(username=username)
        except:
            messages.error(request, 'Username does not exist!')
            # We check if the data is correct
            user = authenticate(request, username=username, password=password)
            if user:  # If the returned object is not None
                login(request, user)  # we connect the user
                return redirect('accounts:profile') # return redirect('/')
            else:  # otherwise an error will be displayed
                messages.error(request, 'Invalid email or password')
            return render(request, 'registration/login.html', {'form': form})
    else:
        form = LoginForm()
    return render(request, 'registration/login.html', {'form': form})

my custome user model is

class User(AbstractUser): 
    # if you need any other information regarding any type of these following kinds of users make a model for them
    USER_TYPE_CHOICES = (
    (1, 'admin'),
    (2, 'supervisor'),
    (3, 'instructor'),
    (4, 'student'),
    (5, 'customer'),
    (6, 'employee'),
    (7, 'advertiser'),
  )
    # sys_id = models.AutoField(primary_key=True, blank=True) 
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True,)
    is_active = models.BooleanField(default=True)

    is_superuser = models.BooleanField(default=False) #is_admin = models.BooleanField(default=False) 
    objects = newUserManager()
    USERNAME_FIELD = 'email' # string describing the name of the field on
    # the User model that is used as the unique identifier
    REQUIRED_FIELDS = ["username"] # list of the field names that will be prompted
    # for when creating a user via thecreatesuperuser management command
    # roles = models.ManyToManyField(Role)
    # the next line has null=True to not having validation error when creating Superuser at the begining
    # django.db.utils.IntegrityError: null value in column "user_type" of relation "user_user" violates not-null constraint
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, null=True, blank=True)
    class Meta:
        #app_label = "user" # or 'auth'
        #db_table = "users"
        #verbose_name = _('User')
        #verbose_name_plural = _('Users')
        permissions = [
            ("change_post_status", "Can change the status of posts"),
            ("close_discussions", "Can remove a post by setting its status as closed"),
            ('can_publish', 'Can Publish Posts'),
        ]
    def __str__(self):
        return self.email
    # this methods are require to login super user from admin panel
    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, eturn True always or return self.is_superuser
        return True
    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always or return self.
        return True
    def get_full_name(self):
        '''
        Returns the first_name plus the last_name, with a space in between.
        '''
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()
    def get_short_name(self):
        '''
        Returns the short name for the user.
        '''
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        '''
        Sends an email to this User.
        '''
        send_mail(subject, message, from_email, [self.email], **kwargs)
    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_superuser

and my custom user creation form is

class CustomUserCreationForm(UserCreationForm): # as we have a odel but has only username as emails
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput) # You can remove those two fields as they are already been existed
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    class Meta(UserCreationForm.Meta): # UserCreationForm has already all default fields, so you just need to add the additional fields to it
        model = User
        #fields = UserCreationForm.Meta.fields + ('user_type',)  # birth date's been removed and added to profile model
        fields = ('username', 'email', ) # if you have any other special field add it here
    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError("Passwords don't match")
        return password2
    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM.
        username = self.cleaned_data["username"]
        try:
            #User.objects.get(username=username)
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

what i am doing wrong here pleeeeeease help me i am disparate of this


What do your urls.py files look like?

Do you have your view that handles the profile edit in an app named “accounts”? (If not, then your reference to that url is incorrect. If you do, then I suggest you change it because of the potential for conflicts with the built-in “accounts” app causing confusion like this one.)

You actually hint at the right answer in your message.

In your use of the url tag within your template, you show that you’re reversing the accounts:profile url with the user.id parameter.

But you’re not supplying that parameter in your redirect function call in your view.

Review the docs at redirect.

what do you mean brother can you give me clearer example cause i already tried these

redirect(reverse('/accounts/id'))
redirect('/accounts/id')

but didn’t work and the redirect should accept the urls pattern names as i think if this is not true pleeeeease just give me a sample correct line of code that can redirect well

What does the example in the referenced doc show for passing a parameter?

you mean passing this

return redirect(user)

What do the docs say about that version of the redirect function?

(There are 4 different uses of that function shown in the docs. One of them matches what you’re trying to do. This one isn’t it.)

Another question - what is this “django_registration” module you have referenced in your urls? Is there possibly some conflict of url names with it?
(Note: a conflict of url names here would be in addition to the improper use of the redirect function, not instead of.)

I have tried all these patterns but didn’t work

return redirect('http://localhost:8000/accounts/id/')
return redirect(details, user.id)
return redirect('accounts:profile')
return redirect(details, id=user.id)
return redirect('/accounts/id')

all of these version if that what do you mean didn’t resolve the problem help me please
I have removed the django-registration app as it’s been added for two step registration user by sending email for activate the account but there is no confections cause the problem still exist and can’t reach my profile page

**when i used these patterns **

return redirect(reverse('/accounts/id'))
return redirect(reverse('accounts:profile'))
id = User.objects.get(username=request.user).id
return redirect(reverse(details, id=id)) # return redirect('/')

i got this strange error

that mean that he couldn’t get the user id i will try to get request.user.id again and check but if you have an answer for the getting of the user object well please provide it and it will be precious appreciated
Should i delete my database and migration and re migrate and try again?

First, this has nothing to do with your database itself. There is no reason to even be thinking along the lines of dropping and recreating it.

Now, lets look at this situation more directly - we’ll start with what the docs say.

For the function definition it has:

redirect (to , *args , permanent=False , **kwargs )

Followed by:

The arguments could be:

  • A model: the model’s get_absolute_url() function will be called.
  • A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.
  • An absolute or relative URL, which will be used as-is for the redirect location.

You’re trying to use the second version - passing a view name. Note that this second bullet point is telling you that it will use reverse to reverse-resolve the name - there’s no reason for you to do that.

What’s your view name? ‘accounts:profile’

Now, if you look at your url definition, you have:

This means you need to supply a parameter named id. This parameter is supposed to be an integer. It appears that you want to use the id of the person logging in - but the issue is that since this person has just logged in, their user object isn’t in the session yet.

You do authenticate a user, and place that reference into an object named user, so user.id is going to contain the id you want to pass as a parameter.

Putting these two pieces of information together, what do you think your call to redirect should look like?

it seems that there are a permanent pattern that never be changed always shown up and exist as accounts/profile 404, so i need to read more in docs because i feel like i can’t reach to the correct form as the details view profile need that id with the request, so there is something missed in the ref. url pattern i don’t know anyway i will read more and back to you my brother

here is what i have tried but didn’t work

return redirect('accounts:profile', request.user.id)
return redirect(reverse('accounts:profile'), request.user.id)
return redirect('/accounts/id', request.user.id)
return redirect(reverse('/accounts/id'), request.user.id)

cause i think the second version that i am trying to use, as you were telling already included i the first version get_absolute_url that will be called in profile models.py file,

return reverse('accounts:profile', kwargs={'id': user.id})
return reverse('/accounts/id', permanent=False, kwargs={'pk': user.id})

so i forgot about these kind of subject and didn’t use them for long time and i was busy in other project so i will read first to not circling and trying without understanding and will back to you if i failed again
thanks for replying me

Items:

  1. You want to use redirect, not reverse. The redirect function uses the reverse function to build the redirect object.
  2. You want to use 'accounts:profile', nothing else
  3. You do not want to use request.user because the user hasn’t been established in the session yet (they’re just logging on). The object you need to reference is user - specifically, the id attribute, being user.id.
  4. As shown in the example, the parameter name you can use is id, so the parameter could just be id=user.id.

firstly i would like to thank you for trying to help me,
secondly unfortunately you didn’t get my point bro
i was trying to say that the problem in django itself because it ignoring all my redirect patterns in views.py file not only the sign up or login function but all the functions in my views
I will tell you why this happens
django and i don’t know why doing that, search by default on this pattern only

accounts/profile

thirdly
you didn’t notice that my login view was having to redirects
the first one is when the user is already authenticated, so i need to take the user id from the request.user.id
the second one is when the user is not authenticated and here i have to use only user.id
so i used to try the first one as i was already authenticated and also the second one when i logged out

So whenever i try any pattern in my views he never look for it as you may didn’t noticed
i have tried all kinds of patterns and they should work all
i knew that i was wrong in using reverse in redirect but the problem bro was never relate to the
redirect or urls patterns at all cause i already tried these patterns but never work

user = get_user_model().objects.get(id=request.user.id) # or username=request.user.username
profile = Profile.objects.get(user=user)
return redirect(profile)
return redirect('http://localhost:8000/accounts/id/')
return redirect('accounts:profile', id=user.id)
return redirect('/accounts/id', id=user.id)
return redirect('accounts:profile')
id = User.objects.get(username=request.user.username).id
return redirect('accounts:profile', id=id) # return redirect('/')
return redirect('accounts:profile', request.user.id)
return redirect('/accounts/id', request.user.id)
return reverse('accounts:profile', args={'id': user.id})
return reverse('/accounts/id', permanent=False, args={'id': request.user.id})
return redirect('accounts:profile', args=[user.id])
return redirect('accounts:profile', kwargs=[user.id])

They never work at all as i told you cause django ignoring all kinds of patterns that i have tried although they are correct all and should work fine and that
because django ignore my redirect pattern at all

anyway
when i added this line in settings

LOGIN_REDIRECT_URL= accounts/id

django look for the same pattern

accounts/id

and ignore also all my patterns in views

i have tried also to change my details view function to take the username instead of the id
and i got another strange error that

he fount the pattern but telling me that
no User match found

even when he got the user.username that already exist in session and in the request

So the problem was that details or profile function should never take any id or user name and just
got the profile using this next line when i be already authenticated

profile = User.objects.get(user=request.user)

and when i be not authenticated

profile = User.objects.get(user=user)

and then the simplest pattern

'accounts:profile'

did works already and no need for any other pattern

so what do you think about that

django only recognise this pattern

accounts/profile

after adding this patter in my urls i could get my profile page

so i read the docs already but there was no solution in it because i have tried all kind of versions of redirect and changed everything to notice this bug as i think in django itself

i don’t know why it doing so and ignore all views pattern except when it be like that

path(profile/, detils, name=profile)

so i think this bug should be taken care of someone among who creates or develop the framework, but if you have the reason please tell me why
the other problem we never take about it also but it’s already bee solved by changing the signup view
Anyway thanks for everything bro and for trying to help

First, there’s no bug in the framework - at least for these functions. There are too many people using them successfully without problems for your situation to be uncovering something that no one else has seen.

Second, let’s make sure one thing is clear - that at any given time you only have one return statement in a logic branch in a function.

If you have something like:

return a
return b

within a section of your code, the second return will never be executed.

If you have all of these returns in your code at the same time, then no, it’s never going to work.

You need to have one return statement in your code at that point.

When you are trying these different patterns, you need to only have the version that you are trying in the code. Your current attempt needs to replace the existing return statement and not be added to some sequence of them.

i don’t know if you mean the second commented return statement in the above code

#return

this is known bro as the basic fundamental concept the first return is executed first and the other will be ignored as the function already done and returned so this is away from our main subject and never related to what i was trying to say.

also why my code is working with these two return statement then if any is exist as you have said !!!

anyway as i have told you what is seen here is and was confirmed that the framework really never see any redirect function outside of accounts profile by default and this is for more than one user not only me,and i read a lot abot so many issues like that but sure if you want me to provide the link to them i can give you some links .

you can check this one if you want

not redirect

i think that this is the normal case that should work fine not a special case that i am the only one having so forgive me if my words was some kind bothering as you were defending for the framework as a support for it,

but for your known i like django and use it a lot so i am not judging you here

anyway thanks again and forgive me

Quite frankly, among all the various side topics raised, I’m not sure what the issue is that you’re trying to comment on.

So, some general notes:

#1
If you have this url in a url pattern in an app named ‘accounts’:

then this will create the redirect for the right url if user is a reference to the right User object:

#2
If you’re having an issue with retrieving the right User object, that’s a different issue, and one we should address separately from this one to avoid confusion. Yes, I know you referenced this early on, but I was ignoring it in favor of trying to address the more obvious issue being the incorrect redirect call.

#3
I don’t see where that article you’ve referenced is on point. You’re not using the standard system-provided login view - you’re handling things yourself.

#4
No apologies are necessary here. It’s actually all part of the learning process.

If you’re still interested in getting this figured out, lets take a step back and start with the first issue needing to be addressed. It would also probably be helpful if you posted the current view displaying the issue. It’s tough to follow all the different fragments that have been posted in this thread to know what the current status of the view is.

yes bro you are totally right
as you have mentioned too we were trying to use this patterns that should be work fine and amongest them this one that already been used with request.user.id and user.id

return redirect('accounts:profile', id=user.id)

but
#1
what i have done already with the simplest details function
it was having problem when it was

@login_required
def details(request, id):
    user = get_object_or_404(get_user_model(), id=id)
    profile = get_object_or_404(Profile, user=user)
    return render(request, 'account/profile.html', {'profile': profile, 'user': user})

and to not telling me why didn’t use

user = User.objects.get(...)

i think i have tried this one as i think cause i have tried a lot for this project to work

it’s now simpler as for testing the solution taking the user only from the request and that works well

@login_required
def details(request):
    profile = Profile(user=request.user)
    return render(request, 'account/profile.html', {'profile': profile})

but django want these patterns only to work fine => for example

    path('profile/', details, name='profile'), 
    path('profile/add/', edit_profile, name='edit_profile'),
    path('profile/add/.../', edit_profile, name='edit_profile'),
    path('profile/edit/', edit_profile, name='edit_profile'),
    path('profile/<int:id>/', edit_profile, name='edit_profile'),
    path('profile/edit/...', edit_profile, name='edit_profile'),
    etc

so it’s not convinced with this details problematic function taking id argument with any other has at the begining

path('<bla bla bla>/...', details, name='profile'),

i have changed these bla bla bla so many times with id or username or any other than profile but no way

#2
the referenced url stack-overflow subject related in the first two lines of the question that has been asked by the user he mentioned that django by default redirect to account/profile and if he added another redirect in settings it will be the same and i got a lot of other problems mentions that django ignoring all views redirect method

#3
finally really deeply thanks from my deep heart for caring and support because without your interactions and replying i wouldn’t really continued because i was circling for long time on this and really want to know why django ignoring all my redirect views pattern
and i would be glad if you have any idea or questions, would be more than happy to answer or reply

thanks again

#1

I’m sorry, I’m not following what you’re trying to say here - what specifically is your question? What is it that you’re wanting to do but isn’t working?

#2

But it’s not the same case as yours. They’re using the system login function, you’re using your own. The two situations are not the same. The information provided there does not apply to you.

yes bro because they are on the same standard of using the same default pattern
accounts/profile
if they were off this they will have the same problem as i had and like so many others, that’s what i mean
and
i am not trying to ask more i just clarifying what was causing the problem as you were asking me for more info back step for the root cause

You’re placing far too much emphasis on this. This is not nearly as important or as significant as you seem to think it is.