Field 'id' expected a number but got <SimpleLazyObject:...

I’m working on an insta clone made with django to hone my skills. while working onthis project it was almost complete just finishing a few kinks, I had to leave it for a while beacause of university. when i opened it again after a week or two I started to get this error everytime i run the server. I did not edit the code in anyway shape or form and have spent a month almost trying to fix this to no avail, below I’ll attach an ss of the error and the github repo so you can check the code, I would love any and all help.

p.s: i have no int Id fields in my models you can check for yourself

GITHUB Repo of the project

Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001A553CAE8D0>>.
Request Method:	GET
Request URL:	http://127.0.0.1:8000/users/sign-in/
Django Version:	4.2.16
Exception Type:	TypeError
Exception Value:	
Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001A553CAE8D0>>.
Exception Location:	D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\fields\__init__.py, line 2055, in get_prep_value
Raised during:	authy.views.UserProfile
Python Executable:	D:\Instagram-Clone-master\Instagram-Clone-master\env\Scripts\python.exe
Python Version:	3.12.4
Python Path:	
['D:\\Instagram-Clone-master\\Instagram-Clone-master',
 'C:\\Users\\Sheru\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip',
 'C:\\Users\\Sheru\\AppData\\Local\\Programs\\Python\\Python312\\DLLs',
 'C:\\Users\\Sheru\\AppData\\Local\\Programs\\Python\\Python312\\Lib',
 'C:\\Users\\Sheru\\AppData\\Local\\Programs\\Python\\Python312',
 'D:\\Instagram-Clone-master\\Instagram-Clone-master\\env',
 'D:\\Instagram-Clone-master\\Instagram-Clone-master\\env\\Lib\\site-packages']
Server time:	Fri, 07 Mar 2025 07:39:13 +0000
Traceback Switch to copy-and-paste view
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\fields\__init__.py, line 2053, in get_prep_value
            return int(value)
                         ^^^^^^^^^^ …
Local vars
The above exception (int() argument must be a string, a bytes-like object or a real number, not 'SimpleLazyObject') was the direct cause of the following exception:
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\core\handlers\exception.py, line 55, in inner
                response = get_response(request)
                               ^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\core\handlers\base.py, line 197, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs)
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\authy\views.py, line 37, in UserProfile
    Profile.objects.get_or_create(user=request.user)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\manager.py, line 87, in manager_method
                return getattr(self.get_queryset(), name)(*args, **kwargs)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\query.py, line 916, in get_or_create
            return self.get(**kwargs), False
                        ^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\query.py, line 623, in get
        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
                                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\query.py, line 1436, in filter
        return self._filter_or_exclude(False, args, kwargs)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\query.py, line 1454, in _filter_or_exclude
            clone._filter_or_exclude_inplace(negate, args, kwargs)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\query.py, line 1461, in _filter_or_exclude_inplace
            self._query.add_q(Q(*args, **kwargs))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\sql\query.py, line 1546, in add_q
        clause, _ = self._add_q(q_object, self.used_aliases)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\sql\query.py, line 1577, in _add_q
            child_clause, needed_inner = self.build_filter(
                                                …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\sql\query.py, line 1492, in build_filter
        condition = self.build_lookup(lookups, col, value)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\sql\query.py, line 1319, in build_lookup
        lookup = lookup_class(lhs, rhs)
                       ^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\lookups.py, line 27, in __init__
        self.rhs = self.get_prep_lookup()
                       ^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\fields\related_lookups.py, line 166, in get_prep_lookup
                self.rhs = target_field.get_prep_value(self.rhs)
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\env\Lib\site-packages\django\db\models\fields\__init__.py, line 2055, in get_prep_value
            raise e.__class__(
                  ^^^^^^^^ …
Local vars
Request information
USER
AnonymousUser

GET
No GET data

POST
No POST data

FILES
No FILES data

COOKIES
No cookie data

META
Variable	Value
ALLUSERSPROFILE	
'C:\\ProgramData'
APPDATA	
'C:\\Users\\Sheru\\AppData\\Roaming'
BUNDLED_DEBUGPY_PATH	
'c:\\Users\\Sheru\\.vscode\\extensions\\ms-python.debugpy-2025.4.0-win32-x64\\bundled\\libs\\debugpy'
CHROME_CRASHPAD_PIPE_NAME	
'\\\\.\\pipe\\crashpad_11996_MGBZVBMKHNILJCQG'
COLORTERM	
'truecolor'
COMMONPROGRAMFILES	
'C:\\Program Files\\Common Files'
COMMONPROGRAMFILES(X86)	
'C:\\Program Files (x86)\\Common Files'
COMMONPROGRAMW6432	
'C:\\Program Files\\Common Files'
COMPUTERNAME	
'DESKTOP-UKIQKS7'
COMSPEC	
'C:\\WINDOWS\\system32\\cmd.exe'
CONTENT_LENGTH	
''
CONTENT_TYPE	
'text/plain'
DEBUGPY_ADAPTER_ENDPOINTS	
'C:\\Users\\Sheru\\AppData\\Local\\Temp\\noConfigDebugAdapterEndpoints-95230e47240c43ab2d21\\debuggerAdapterEndpoint.txt'
DJANGO_SETTINGS_MODULE	
'ig_prj.settings'
DRIVERDATA	
'C:\\Windows\\System32\\Drivers\\DriverData'
EFC_7584	
'1'
FPS_BROWSER_APP_PROFILE_STRING	
'Internet Explorer'
FPS_BROWSER_USER_PROFILE_STRING	
'Default'
GATEWAY_INTERFACE	
'CGI/1.1'
GIT_ASKPASS	
'********************'
GIT_LFS_PATH	
'C:\\Program Files\\Git LFS'
HOMEDRIVE	
'C:'
HOMEPATH	
'\\Users\\Sheru'
HTTP_ACCEPT	
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
HTTP_ACCEPT_ENCODING	
'gzip, deflate, br, zstd'
HTTP_ACCEPT_LANGUAGE	
'en-US,en;q=0.9'
HTTP_CONNECTION	
'keep-alive'
HTTP_HOST	
'127.0.0.1:8000'
HTTP_SEC_CH_UA	
'"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"'
HTTP_SEC_CH_UA_MOBILE	
'?0'
HTTP_SEC_CH_UA_PLATFORM	
'"Windows"'
HTTP_SEC_FETCH_DEST	
'document'
HTTP_SEC_FETCH_MODE	
'navigate'
HTTP_SEC_FETCH_SITE	
'none'
HTTP_SEC_FETCH_USER	
'?1'
HTTP_UPGRADE_INSECURE_REQUESTS	
'1'
HTTP_USER_AGENT	
('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like '
 'Gecko) Chrome/134.0.0.0 Safari/537.36')
INTELLIJ IDEA	
'D:\\Program Files\\JetBrains\\IntelliJ IDEA 2024.3.1\\bin;'
LANG	
'en_US.UTF-8'
LOCALAPPDATA	
'C:\\Users\\Sheru\\AppData\\Local'
LOGONSERVER	
'\\\\DESKTOP-UKIQKS7'
MOZ_PLUGIN_PATH	
'C:\\Program Files (x86)\\Foxit Software\\Foxit PDF Reader\\plugins\\'
NUMBER_OF_PROCESSORS	
'8'
ONEDRIVE	
'C:\\Users\\Sheru\\OneDrive - National University of Sciences & Technology'
ORIGINAL_XDG_CURRENT_DESKTOP	
'undefined'
OS	
'Windows_NT'
PATH	
('D:\\Instagram-Clone-master\\Instagram-Clone-master\\env/Scripts;c:\\Users\\Sheru\\.vscode\\extensions\\ms-python.python-2025.2.0-win32-x64\\python_files\\deactivate\\powershell;D:\\Instagram-Clone-master\\Instagram-Clone-master\\env/Scripts;c:\\Users\\Sheru\\.vscode\\extensions\\ms-python.python-2025.2.0-win32-x64\\python_files\\deactivate\\powershell;D:\\Instagram-Clone-master\\Instagram-Clone-master\\env/Scripts;C:\\Program '
 'Files (x86)\\Common Files\\Oracle\\Java\\java8path;C:\\Program Files '
 '(x86)\\Common '
 'Files\\Oracle\\Java\\javapath;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program '
 'Files\\dotnet\\;C:\\Program Files\\Git\\cmd;C:\\Program '
 'Files\\Cloudflare\\Cloudflare WARP\\;C:\\msys64\\ucrt64\\bin;C:\\Program '
 'Files (x86)\\Windows Kits\\10\\Windows Performance '
 'Toolkit\\;C:\\Users\\Sheru\\Downloads\\platform-tools;;C:\\Program '
 'Files\\Git LFS;C:\\Program Files\\Docker\\Docker\\resources\\bin;D:\\Program '
 'Files (x86)\\Microchip\\MPLAB C32 '
 'Suite\\bin;C:\\Users\\Sheru\\AppData\\Local\\Programs\\Python\\Python312\\Scripts\\;C:\\Users\\Sheru\\AppData\\Local\\Programs\\Python\\Python312\\;C:\\Users\\Sheru\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Program '
 'Files\\JetBrains\\PyCharm Community Edition '
 '2024.1.4\\bin;;C:\\Users\\Sheru\\AppData\\Local\\Programs\\Microsoft VS '
 'Code\\bin;C:\\msys64\\ucrt64\\bin;D:\\Downloads\\OpenCV\\opencv\\build\\x64\\vc16\\bin;D:\\Downloads\\OpenCV\\opencv\\build\\x64\\vc16\\lib;D:\\Program '
 'Files\\JetBrains\\IntelliJ IDEA '
 '2024.3.1\\bin;;C:\\Users\\Sheru\\Downloads\\platform-tools;')
PATHEXT	
'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL'
PATH_INFO	
'/users/sign-in/'
PROCESSOR_ARCHITECTURE	
'AMD64'
PROCESSOR_IDENTIFIER	
'Intel64 Family 6 Model 165 Stepping 2, GenuineIntel'
PROCESSOR_LEVEL	
'6'
PROCESSOR_REVISION	
'a502'
PROGRAMDATA	
'C:\\ProgramData'
PROGRAMFILES	
'C:\\Program Files'
PROGRAMFILES(X86)	
'C:\\Program Files (x86)'
PROGRAMW6432	
'C:\\Program Files'
PSMODULEPATH	
('C:\\Users\\Sheru\\OneDrive - National University of Sciences & '
 'Technology\\Documents\\WindowsPowerShell\\Modules;C:\\Program '
 'Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules')
PUBLIC	
'C:\\Users\\Public'
PYCHARM COMMUNITY EDITION	
'C:\\Program Files\\JetBrains\\PyCharm Community Edition 2024.1.4\\bin;'
PYDEVD_DISABLE_FILE_VALIDATION	
'1'
QUERY_STRING	
''
REMOTE_ADDR	
'127.0.0.1'
REMOTE_HOST	
''
REQUEST_METHOD	
'GET'
RUN_MAIN	
'true'
SCRIPT_NAME	
''
SERVER_NAME	
'kubernetes.docker.internal'
SERVER_PORT	
'8000'
SERVER_PROTOCOL	
'HTTP/1.1'
SERVER_SOFTWARE	
'WSGIServer/0.2'
SESSIONNAME	
'Console'
SYSTEMDRIVE	
'C:'
SYSTEMROOT	
'C:\\WINDOWS'
TEMP	
'C:\\Users\\Sheru\\AppData\\Local\\Temp'
TERM_PROGRAM	
'vscode'
TERM_PROGRAM_VERSION	
'1.98.0'
TMP	
'C:\\Users\\Sheru\\AppData\\Local\\Temp'
USERDOMAIN	
'DESKTOP-UKIQKS7'
USERDOMAIN_ROAMINGPROFILE	
'DESKTOP-UKIQKS7'
USERNAME	
'Sheru'
USERPROFILE	
'C:\\Users\\Sheru'
VIRTUAL_ENV	
'D:\\Instagram-Clone-master\\Instagram-Clone-master\\env'
VIRTUAL_ENV_PROMPT	
'env'
VSCODE_DEBUGPY_ADAPTER_ENDPOINTS	
'c:\\Users\\Sheru\\.vscode\\extensions\\ms-python.debugpy-2025.4.0-win32-x64\\.noConfigDebugAdapterEndpoints\\endpoint-0d03b507a2420585.txt'
VSCODE_GIT_ASKPASS_EXTRA_ARGS	
'********************'
VSCODE_GIT_ASKPASS_MAIN	
'********************'
VSCODE_GIT_ASKPASS_NODE	
'********************'
VSCODE_GIT_IPC_HANDLE	
'\\\\.\\pipe\\vscode-git-da17f6ee2e-sock'
VSCODE_INJECTION	
'1'
WINDIR	
'C:\\WINDOWS'
ZES_ENABLE_SYSMAN	
'1'
wsgi.errors	
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>
wsgi.file_wrapper	
<class 'wsgiref.util.FileWrapper'>
wsgi.input	
<django.core.handlers.wsgi.LimitedStream object at 0x000001A553CAD570>
wsgi.multiprocess	
False
wsgi.multithread	
True
wsgi.run_once	
False
wsgi.url_scheme	
'http'
wsgi.version	
(1, 0)
Settings
Using settings module ig_prj.settings
Setting	Value
ABSOLUTE_URL_OVERRIDES	
{}
ADMINS	
[]
ALLOWED_HOSTS	
['instagram-clone-d.herokuapp.com', '127.0.0.1']
APPEND_SLASH	
True
AUTHENTICATION_BACKENDS	
['django.contrib.auth.backends.ModelBackend']
AUTH_PASSWORD_VALIDATORS	
'********************'
AUTH_USER_MODEL	
'auth.User'
BASE_DIR	
WindowsPath('D:/Instagram-Clone-master/Instagram-Clone-master')
CACHES	
{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS	
'default'
CACHE_MIDDLEWARE_KEY_PREFIX	
'********************'
CACHE_MIDDLEWARE_SECONDS	
600
CRISPY_TEMPLATE_PACK	
'bootstrap4'
CSRF_COOKIE_AGE	
31449600
CSRF_COOKIE_DOMAIN	
None
CSRF_COOKIE_HTTPONLY	
False
CSRF_COOKIE_MASKED	
False
CSRF_COOKIE_NAME	
'csrftoken'
CSRF_COOKIE_PATH	
'/'
CSRF_COOKIE_SAMESITE	
'Lax'
CSRF_COOKIE_SECURE	
False
CSRF_FAILURE_VIEW	
'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME	
'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS	
[]
CSRF_USE_SESSIONS	
False
DATABASES	
{'default': {'ATOMIC_REQUESTS': False,
             'AUTOCOMMIT': True,
             'CONN_HEALTH_CHECKS': False,
             'CONN_MAX_AGE': 0,
             'ENGINE': 'django.db.backends.sqlite3',
             'HOST': '',
             'NAME': WindowsPath('D:/Instagram-Clone-master/Instagram-Clone-master/db.sqlite3'),
             'OPTIONS': {},
             'PASSWORD': '********************',
             'PORT': '',
             'TEST': {'CHARSET': None,
                      'COLLATION': None,
                      'MIGRATE': True,
                      'MIRROR': None,
                      'NAME': None},
             'TIME_ZONE': None,
             'USER': ''}}
DATABASE_ROUTERS	
[]
DATA_UPLOAD_MAX_MEMORY_SIZE	
2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS	
1000
DATA_UPLOAD_MAX_NUMBER_FILES	
100
DATETIME_FORMAT	
'N j, Y, P'
DATETIME_INPUT_FORMATS	
['%Y-%m-%d %H:%M:%S',
 '%Y-%m-%d %H:%M:%S.%f',
 '%Y-%m-%d %H:%M',
 '%m/%d/%Y %H:%M:%S',
 '%m/%d/%Y %H:%M:%S.%f',
 '%m/%d/%Y %H:%M',
 '%m/%d/%y %H:%M:%S',
 '%m/%d/%y %H:%M:%S.%f',
 '%m/%d/%y %H:%M']
DATE_FORMAT	
'N j, Y'
DATE_INPUT_FORMATS	
['%Y-%m-%d',
 '%m/%d/%Y',
 '%m/%d/%y',
 '%b %d %Y',
 '%b %d, %Y',
 '%d %b %Y',
 '%d %b, %Y',
 '%B %d %Y',
 '%B %d, %Y',
 '%d %B %Y',
 '%d %B, %Y']
DEBUG	
True
DEBUG_PROPAGATE_EXCEPTIONS	
False
DECIMAL_SEPARATOR	
'.'
DEFAULT_AUTO_FIELD	
'django.db.models.BigAutoField'
DEFAULT_CHARSET	
'utf-8'
DEFAULT_EXCEPTION_REPORTER	
'django.views.debug.ExceptionReporter'
DEFAULT_EXCEPTION_REPORTER_FILTER	
'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE	
'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL	
'webmaster@localhost'
DEFAULT_INDEX_TABLESPACE	
''
DEFAULT_TABLESPACE	
''
DISALLOWED_USER_AGENTS	
[]
EMAIL_BACKEND	
'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST	
'localhost'
EMAIL_HOST_PASSWORD	
'********************'
EMAIL_HOST_USER	
''
EMAIL_PORT	
25
EMAIL_SSL_CERTFILE	
None
EMAIL_SSL_KEYFILE	
'********************'
EMAIL_SUBJECT_PREFIX	
'[Django] '
EMAIL_TIMEOUT	
None
EMAIL_USE_LOCALTIME	
False
EMAIL_USE_SSL	
False
EMAIL_USE_TLS	
False
FILE_UPLOAD_DIRECTORY_PERMISSIONS	
None
FILE_UPLOAD_HANDLERS	
['django.core.files.uploadhandler.MemoryFileUploadHandler',
 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE	
2621440
FILE_UPLOAD_PERMISSIONS	
420
FILE_UPLOAD_TEMP_DIR	
None
FIRST_DAY_OF_WEEK	
0
FIXTURE_DIRS	
[]
FORCE_SCRIPT_NAME	
None
FORMAT_MODULE_PATH	
None
FORM_RENDERER	
'django.forms.renderers.DjangoTemplates'
IGNORABLE_404_URLS	
[]
INSTALLED_APPS	
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'post',
 'crispy_forms',
 'authy',
 'comment',
 'directs',
 'notification',
 'reels']
INTERNAL_IPS	
[]
LANGUAGES	
[('af', 'Afrikaans'),
 ('ar', 'Arabic'),
 ('ar-dz', 'Algerian Arabic'),
 ('ast', 'Asturian'),
 ('az', 'Azerbaijani'),
 ('bg', 'Bulgarian'),
 ('be', 'Belarusian'),
 ('bn', 'Bengali'),
 ('br', 'Breton'),
 ('bs', 'Bosnian'),
 ('ca', 'Catalan'),
 ('ckb', 'Central Kurdish (Sorani)'),
 ('cs', 'Czech'),
 ('cy', 'Welsh'),
 ('da', 'Danish'),
 ('de', 'German'),
 ('dsb', 'Lower Sorbian'),
 ('el', 'Greek'),
 ('en', 'English'),
 ('en-au', 'Australian English'),
 ('en-gb', 'British English'),
 ('eo', 'Esperanto'),
 ('es', 'Spanish'),
 ('es-ar', 'Argentinian Spanish'),
 ('es-co', 'Colombian Spanish'),
 ('es-mx', 'Mexican Spanish'),
 ('es-ni', 'Nicaraguan Spanish'),
 ('es-ve', 'Venezuelan Spanish'),
 ('et', 'Estonian'),
 ('eu', 'Basque'),
 ('fa', 'Persian'),
 ('fi', 'Finnish'),
 ('fr', 'French'),
 ('fy', 'Frisian'),
 ('ga', 'Irish'),
 ('gd', 'Scottish Gaelic'),
 ('gl', 'Galician'),
 ('he', 'Hebrew'),
 ('hi', 'Hindi'),
 ('hr', 'Croatian'),
 ('hsb', 'Upper Sorbian'),
 ('hu', 'Hungarian'),
 ('hy', 'Armenian'),
 ('ia', 'Interlingua'),
 ('id', 'Indonesian'),
 ('ig', 'Igbo'),
 ('io', 'Ido'),
 ('is', 'Icelandic'),
 ('it', 'Italian'),
 ('ja', 'Japanese'),
 ('ka', 'Georgian'),
 ('kab', 'Kabyle'),
 ('kk', 'Kazakh'),
 ('km', 'Khmer'),
 ('kn', 'Kannada'),
 ('ko', 'Korean'),
 ('ky', 'Kyrgyz'),
 ('lb', 'Luxembourgish'),
 ('lt', 'Lithuanian'),
 ('lv', 'Latvian'),
 ('mk', 'Macedonian'),
 ('ml', 'Malayalam'),
 ('mn', 'Mongolian'),
 ('mr', 'Marathi'),
 ('ms', 'Malay'),
 ('my', 'Burmese'),
 ('nb', 'Norwegian Bokmål'),
 ('ne', 'Nepali'),
 ('nl', 'Dutch'),
 ('nn', 'Norwegian Nynorsk'),
 ('os', 'Ossetic'),
 ('pa', 'Punjabi'),
 ('pl', 'Polish'),
 ('pt', 'Portuguese'),
 ('pt-br', 'Brazilian Portuguese'),
 ('ro', 'Romanian'),
 ('ru', 'Russian'),
 ('sk', 'Slovak'),
 ('sl', 'Slovenian'),
 ('sq', 'Albanian'),
 ('sr', 'Serbian'),
 ('sr-latn', 'Serbian Latin'),
 ('sv', 'Swedish'),
 ('sw', 'Swahili'),
 ('ta', 'Tamil'),
 ('te', 'Telugu'),
 ('tg', 'Tajik'),
 ('th', 'Thai'),
 ('tk', 'Turkmen'),
 ('tr', 'Turkish'),
 ('tt', 'Tatar'),
 ('udm', 'Udmurt'),
 ('uk', 'Ukrainian'),
 ('ur', 'Urdu'),
 ('uz', 'Uzbek'),
 ('vi', 'Vietnamese'),
 ('zh-hans', 'Simplified Chinese'),
 ('zh-hant', 'Traditional Chinese')]
LANGUAGES_BIDI	
['he', 'ar', 'ar-dz', 'ckb', 'fa', 'ur']
LANGUAGE_CODE	
'en-us'
LANGUAGE_COOKIE_AGE	
None
LANGUAGE_COOKIE_DOMAIN	
None
LANGUAGE_COOKIE_HTTPONLY	
False
LANGUAGE_COOKIE_NAME	
'django_language'
LANGUAGE_COOKIE_PATH	
'/'
LANGUAGE_COOKIE_SAMESITE	
None
LANGUAGE_COOKIE_SECURE	
False
LOCALE_PATHS	
[]
LOGGING	
{}
LOGGING_CONFIG	
'logging.config.dictConfig'
LOGIN_REDIRECT_URL	
'index'
LOGIN_URL	
'users/sign-in/'
LOGOUT_REDIRECT_URL	
'users/sign-in/'
MANAGERS	
[]
MEDIA_ROOT	
'D:\\Instagram-Clone-master\\Instagram-Clone-master\\media'
MEDIA_URL	
'/media/'
MESSAGE_STORAGE	
'django.contrib.messages.storage.cookie.CookieStorage'
MIDDLEWARE	
['django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
MIGRATION_MODULES	
{}
MONTH_DAY_FORMAT	
'F j'
NUMBER_GROUPING	
0
PASSWORD_HASHERS	
'********************'
PASSWORD_RESET_TIMEOUT	
'********************'
PREPEND_WWW	
False
ROOT_URLCONF	
'ig_prj.urls'
SECRET_KEY	
'********************'
SECRET_KEY_FALLBACKS	
'********************'
SECURE_CONTENT_TYPE_NOSNIFF	
True
SECURE_CROSS_ORIGIN_OPENER_POLICY	
'same-origin'
SECURE_HSTS_INCLUDE_SUBDOMAINS	
False
SECURE_HSTS_PRELOAD	
False
SECURE_HSTS_SECONDS	
0
SECURE_PROXY_SSL_HEADER	
None
SECURE_REDIRECT_EXEMPT	
[]
SECURE_REFERRER_POLICY	
'same-origin'
SECURE_SSL_HOST	
None
SECURE_SSL_REDIRECT	
False
SERVER_EMAIL	
'root@localhost'
SESSION_CACHE_ALIAS	
'default'
SESSION_COOKIE_AGE	
1209600
SESSION_COOKIE_DOMAIN	
None
SESSION_COOKIE_HTTPONLY	
True
SESSION_COOKIE_NAME	
'sessionid'
SESSION_COOKIE_PATH	
'/'
SESSION_COOKIE_SAMESITE	
'Lax'
SESSION_COOKIE_SECURE	
False
SESSION_ENGINE	
'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE	
False
SESSION_FILE_PATH	
None
SESSION_SAVE_EVERY_REQUEST	
False
SESSION_SERIALIZER	
'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE	
'ig_prj.settings'
SHORT_DATETIME_FORMAT	
'm/d/Y P'
SHORT_DATE_FORMAT	
'm/d/Y'
SIGNING_BACKEND	
'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS	
[]
STATICFILES_DIRS	
['D:\\Instagram-Clone-master\\Instagram-Clone-master\\static']
STATICFILES_FINDERS	
['django.contrib.staticfiles.finders.FileSystemFinder',
 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE	
'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT	
'D:\\Instagram-Clone-master\\Instagram-Clone-master\\staticfiles'
STATIC_URL	
'/static/'
STORAGES	
{'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
 'staticfiles': {'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage'}}
TEMPLATES	
[{'APP_DIRS': True,
  'BACKEND': 'django.template.backends.django.DjangoTemplates',
  'DIRS': ['D:\\Instagram-Clone-master\\Instagram-Clone-master\\templates'],
  'OPTIONS': {'context_processors': ['django.template.context_processors.debug',
                                     'django.template.context_processors.request',
                                     'django.contrib.auth.context_processors.auth',
                                     'django.contrib.messages.context_processors.messages']}}]
TEST_NON_SERIALIZED_APPS	
[]
TEST_RUNNER	
'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR	
','
TIME_FORMAT	
'P'
TIME_INPUT_FORMATS	
['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE	
'UTC'
USE_DEPRECATED_PYTZ	
False
USE_I18N	
True
USE_L10N	
True
USE_THOUSAND_SEPARATOR	
False
USE_TZ	
True
USE_X_FORWARDED_HOST	
False
USE_X_FORWARDED_PORT	
False
WSGI_APPLICATION	
'ig_prj.wsgi.application'
X_FRAME_OPTIONS	
'DENY'
YEAR_MONTH_FORMAT	
'F Y'
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code.```
Profile.objects.get_or_create(user=request.user)

the user here is an AnonymousUser, meaning there is no one logged in. You can’t create a profile unless the user has logged in.

I’ve tried redirecting to sign in if no user is logged in but i get stuck in an infinite loop of redirects, I’ve flushed the database and tried again but the problem still persists

You’re probably redirecting to the login page even if the user is trying to load the login view. Which is an infinite loop of redirects as you describe.

can you suggest a work around please I’m completely at a loss

You need to show some code.

Sorry for the late reply got held up with exams, but I have provided the GitHub link to the code

It is best to share only the relevant portion of your code, rather than expect people to look through your whole project to help you.

If you look through the error traceback, starting from the bottom upwards, you see references to lots of files, which are all in site-packages\django\.... Keep going until you get to one of your own files, which is in these lines:

Local vars
D:\Instagram-Clone-master\Instagram-Clone-master\authy\views.py, line 37, in UserProfile
    Profile.objects.get_or_create(user=request.user)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …

That shows you where the error is occurring. In views.py we see this:

def UserProfile(request, username):
    Profile.objects.get_or_create(user=request.user)
    ...

The error, generated by that line, was:

Field ‘id’ expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001A553CAE8D0>>.

So you’re trying to get or create a new Profile by passing the request.user as the user parameter. But getting this error.

Profile expects an actual User, with an id, to get or create an object.

But you’re passing an AnonymousUser. This means the current user is not logged in and, therefore, does not represent a User in the database, and so there is no id. Hence the error.

The problem is I wanna provide a specific code, but the error you’ve pointed out, I’ve already tried that, replaced that with redirection, checks and a bunch of other things, the problem is it doesn’t redirect to the login page, the thing I don’t get is that the code was working normally and perfectly it just randomly started giving this error, I’m really sorry for being annoying I’m just at a complete loss

You’ll need to show the code that isn’t working, with a detailed description of what you want to happen, and what actually happens, if you want someone to help fix it.

While that often seems like the case it never is. Something changed - if not the code, then the inputs.

1 Like

<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001A553CAE8D0>>.

This means that the user is not logged in.

You did something on the login page, but the project called authy.views.UserProfile.

I think it wants to show the user profile page regardless of whether the login was successful or not.

There seems to be no problem with urls.py, but I don’t know exactly why because you didn’t post the error message properly.

And you uploaded it strangely on GitHub, so it’s hard to see the code.

If you fix it like this, you can avoid the immediate problem.

def UserProfile(request, username):
  Profile.objects.get_or_create(user=request.user)
  ...
from django.shortcuts import redirect
...

def UserProfile(request, username):
  if request.user.is_anonymous: return redirect('/')
  Profile.objects.get_or_create(user=request.user)
  ...
1 Like

This question has not been answered. I am having same issue right now. My Login page that has been working using if request.method == 'POST': stopped working and POST changed to GET.

If you’ve got a specific issue that you are looking for assistance with, I suggest you open a new topic to discuss that issue to avoid confusion here.

While the symptoms might be similar (or identical) to the original post, it’s quite possible that the cause of the problem could be something different from theirs.

1 Like

Sorry to bother you but this gives me a redirected too many times error. The thing is just to clarify I’m using the builtin login view from Django in login, previously it would normally go to that view but now it isn’t working

Heres some more specific code:

Settings:

Django settings for ig_prj project.

Generated by 'django-admin startproject' using Django 3.1.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k1l8gsqp&&glb@%qafi26xb-y4%xjf60g)2!6bspqc+@xjl7me'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['instagram-clone-d.herokuapp.com', '127.0.0.1']


# Application definition

INSTALLED_APPS = [

    # 'channels',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',

    #own
    'post',
    'crispy_forms',
    'authy',
    'comment',
    'directs',
    'notification',
    'reels',
    # 'chat',
]

ASGI_APPLICATION = 'ig_prj.asgi.application'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',

    'whitenoise.middleware.WhiteNoiseMiddleware',
    
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ig_prj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ig_prj.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

LOGIN_REDIRECT_URL = '/users/<username>/'

LOGOUT_REDIRECT_URL = '/users/sign-in/'

LOGIN_URL = '/users/sign-in/'

CRISPY_TEMPLATE_PACK = 'bootstrap4'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"```

Authy urls;
```from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy
from authy.views import *
from reels.views import userReels

urlpatterns = [
    # Profile Section
    path('<username>/', UserProfile, name='profile'),
    path('<username>/settings', prof_settings, name='profile-settings'),
    path('<username>/settings/password_change', password_change, name='password-change'),
    path('<username>/saved/', UserProfile, name='profilefavourite'),
    path('<username>/follow/<option>/', follow, name='follow'),
    path('<username>/followers/', followers_list, name='followers'),
    path('<username>/add-to-close/<follower_username>', add_to_close_friends, name='add-to-close'),
    path('<username>/following/', following_list, name='following'),
    path('<username>/Close-Friends/', close_friends, name='close-friends'),
    path('<username>/followers/remove/<follower_username>/', follower_remove, name='follower-remove'),
    path('<username>/following/remove/<following_username>/', following_remove, name='following-remove'),
    path('<username>/reels/', userReels.as_view(), name='profile-reels'),
    path('profile/edit', EditProfile, name="editprofile"),
    # path('profile/<str:username>/reels/', views.ReelsView.as_view(), name='profile-reels'),
    # User Authentication
    path('sign-up/', views.register, name="sign-up"),
    path('sign-in/', auth_views.LoginView.as_view(template_name="sign-in.html", redirect_authenticated_user=True), name='sign-in'),
    path('sign-out/', auth_views.LogoutView.as_view(template_name="sign-out.html"), name='sign-out'),
    # path("users/sign-in/", CustomLoginView.as_view(), name="sign-in"),
    # path('manual_sign_in/', manual_login, 'manual-sign-in'), 
    # path('sign-in/', auth_views.LoginView.as_view(
    #     template_name="sign-in.html",
    # ), name='sign-in'),
]

Authy views:

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Follow, CloseFrens
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, JsonResponse, HttpResponseForbidden,HttpResponse
from django.core.paginator import Paginator
from django.db import transaction
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.contrib import messages
from django.contrib.auth import authenticate, login, update_session_auth_hash
from django.contrib.auth import views as auth_views
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from .models import *
from post.models import Post, Follow, Stream
from django.contrib.auth.models import User
from authy.models import Profile
from .forms import *
from django.urls import resolve
from comment.models import Comment
from django.contrib.auth.hashers import check_password

class CustomLoginView(auth_views.LoginView):
    template_name = "users/sign_in.html"

    def dispatch(self, request, *args, **kwargs):
        # If user is already authenticated, redirect them away from login page
        if request.user.is_authenticated:
            return redirect("index")  # or any other page
        return super().dispatch(request, *args, **kwargs)
# @login_required
def UserProfile(request, username):
    # # Check if the user is authenticated
    # if not request.user.is_authenticated:
    #     return redirect('sign-in')  # Redirect to the login page
    # if request.user.is_anonymous: return redirect('/')
    if not username:
        return redirect('/')
    # Debugging prints
    print(request.user)
    print('asdfvbn')
    print(request.user.id)

    # Get or create the profile for the authenticated user
    Profile.objects.get_or_create(user=request.user)

    # Get the user profile for the requested username
    user = get_object_or_404(User, username=username)
    profile = Profile.objects.get(user=user)

    # Resolve the URL name
    url_name = resolve(request.path).url_name

    # Get posts based on the URL name
    if url_name == 'profile':
        posts = Post.objects.filter(user=user).order_by('-posted')
    else:
        posts = profile.favourite.all()

    # Profile Stats
    posts_count = Post.objects.filter(user=user).count()
    close = CloseFrens.objects.all()
    following_count = Follow.objects.filter(follower=user).count()
    followers_count = Follow.objects.filter(following=user).count()
    follow_status = Follow.objects.filter(following=user, follower=request.user).exists()

    # Pagination
    paginator = Paginator(posts, 8)
    page_number = request.GET.get('page')
    posts_paginator = paginator.get_page(page_number)

    # Context for the template
    context = {
        'posts': posts,
        'profile': profile,
        'posts_count': posts_count,
        'following_count': following_count,
        'followers_count': followers_count,
        'posts_paginator': posts_paginator,
        'follow_status': follow_status,
    }

    return render(request, 'profile.html', context)

# def UserProfile(request, username):
#     print(request.user)
#     print('asdfvbn')
#     # print(request.user.id)
#     Profile.objects.get_or_create(user=request.user)
#     user = get_object_or_404(User, username=username)
#     profile = Profile.objects.get(user=user)
#     url_name = resolve(request.path).url_name
#     posts = Post.objects.filter(user=user).order_by('-posted')

#     if url_name == 'profile':
#         posts = Post.objects.filter(user=user).order_by('-posted')
#     else:
#         posts = profile.favourite.all()
    
#     # Profile Stats
#     posts_count = Post.objects.filter(user=user).count()
#     close= CloseFrens.objects.all()
#     following_count = Follow.objects.filter(follower=user).count()
#     followers_count = Follow.objects.filter(following=user).count()
#     # count_comment = Comment.objects.filter(post=posts).count()
#     follow_status = Follow.objects.filter(following=user, follower=request.user).exists()

#     # pagination
#     paginator = Paginator(posts, 8)
#     page_number = request.GET.get('page')
#     posts_paginator = paginator.get_page(page_number)

#     context = {
#         'posts': posts,
#         'profile':profile,
#         'posts_count':posts_count,
#         'following_count':following_count,
#         'followers_count':followers_count,
#         'posts_paginator':posts_paginator,
#         'follow_status':follow_status,
#         # 'count_comment':count_comment,
#     }
#     return render(request, 'profile.html', context)

# def manual_login(request):
#     user = authenticate(username="hehe34", password="noidea")
#     if user:
#         login(request, user)
#         return HttpResponse("Logged in successfully!")
#     return HttpResponse("Login failed.")

# @login_required(login_url="/users/sign-in/")  # Redirects unauthenticated users
# def UserProfile(request, username):
#     user = get_object_or_404(User, username=username)

#     # Ensure 'Profile' exists for the user
#     profile, created = Profile.objects.get_or_create(user=user)

#     url_name = resolve(request.path).url_name
#     posts = Post.objects.filter(user=user).order_by('-posted')

#     if url_name != 'profile':
#         posts = profile.favourite.all()

#     # Profile Stats
#     posts_count = Post.objects.filter(user=user).count()
#     following_count = Follow.objects.filter(follower=user).count()
#     followers_count = Follow.objects.filter(following=user).count()
#     follow_status = Follow.objects.filter(following=user, follower=request.user).exists()

#     # Pagination
#     paginator = Paginator(posts, 8)
#     page_number = request.GET.get('page')
#     posts_paginator = paginator.get_page(page_number)

#     context = {
#         'posts': posts,
#         'profile': profile,
#         'posts_count': posts_count,
#         'following_count': following_count,
#         'followers_count': followers_count,
#         'posts_paginator': posts_paginator,
#         'follow_status': follow_status,
#     }
#     return render(request, 'profile.html', context)

def EditProfile(request):
    user = request.user.id
    profile = Profile.objects.get(user__id=user)

    if request.method == "POST":
        form = EditProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, "Your profile has been updated successfully!")
            return redirect('profile', username=profile.user.username)
        else:
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f"{field}: {error}")
    else:
        form = EditProfileForm(instance=request.user.profile)

    context = {
        'form':form,
    }
    return render(request, 'editprofile.html', context)


def close_friends(request, username):
    # Get the user whose profile is being viewed
    user = get_object_or_404(User, username=username)
    profile = get_object_or_404(Profile, user=user)  # Ensure the profile exists

    # Get all Follow objects where the current user is being followed
    followers = Follow.objects.filter(following=user)

    # Get CloseFrens objects where friendProf matches the followers queryset
    close = CloseFrens.objects.filter(friendProf__in=followers)

    context = {
        'profile_user': user,  # The user whose profile is being viewed
        'close_friends': close,  # List of CloseFrens related to the user's followers
        'is_owner': request.user == user,  # Check if the logged-in user owns the profile
    }

    return render(request, 'close_friends_list.html', context)



@login_required
def add_to_close_friends(request, username, follower_username):
    """
    Allows the logged-in user to add a follower to their Close Friends list.
    """
    # Get the currently logged-in user
    current_user = request.user
    profile_user = get_object_or_404(User, username=username)
    # Get the follower to be added to Close Friends
    target_user = get_object_or_404(User, username=follower_username)

    # Check if the target_user is following the current_user
    follow_instance = Follow.objects.filter(follower=target_user, following=current_user).first()
    if not follow_instance:
        messages.error(request, f"{target_user.username} must be following you to add them to Close Friends.")
        return redirect('profile', username=current_user.username)

    # Check if the follower is already in the Close Friends list
    close_friend_exists = CloseFrens.objects.filter(friendProf=follow_instance).exists()
    if close_friend_exists:
        messages.info(request, f"{target_user.username} is already in your Close Friends list.")
        return redirect('profile', username=current_user.username)

    # Add the follower to Close Friends
    CloseFrens.objects.create(friendProf=follow_instance)
    messages.success(request, f"{target_user.username} has been added to your Close Friends list.")

    # Redirect back to the profile or close friends page
    return redirect('followers', username=current_user.username)


@login_required
def prof_settings(request, username):
    user = request.user
    profile_user = get_object_or_404(User, username=username)

    if request.user != profile_user:
        return HttpResponseForbidden("You are not allowed to perform this action.")
    return render(request, "profile_settings.html")

@login_required
def password_change(request, username):
    user = request.user
    if user.username != username:
        return HttpResponseForbidden("You are not allowed to access this page.")

    if request.method == "POST":
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            current_password = form.cleaned_data['current_password']
            new_password = form.cleaned_data['new_password']
            confirm_new_password = form.cleaned_data['confirm_new_password']

            if not check_password(current_password, user.password):
                messages.error(request, "Current password is incorrect.")
                return render(request, "passChange.html", {'form': form})

            if new_password != confirm_new_password:
                messages.error(request, "New password and confirmation do not match.")
                return render(request, "passChange.html", {'form': form})

            user.set_password(new_password)
            user.save()
            update_session_auth_hash(request, user)
            messages.success(request, "Your password has been successfully updated.")
            return redirect('profile-settings', username=user.username)
    else:
        form = PasswordChangeForm()

    return render(request, "passChange.html", {'form': form})


@login_required
def following_remove(request, username, following_username):
    profile_user = get_object_or_404(User, username=username)

    # Ensure only the owner of the profile can remove followers
    if request.user != profile_user:
        return HttpResponseForbidden("You are not allowed to perform this action.")

    # Get the follower by their username
    following = get_object_or_404(User, username=following_username)
    print(f"{following.username} deleted")
    
    # Remove the follow relationship
    Follow.objects.filter(follower=profile_user, following=following).delete()
    # Optional: Add a success message
    messages.success(request, f"{following.username} has been removed from your following.")
    
    # Redirect back to the followings list
    # return HttpResponseRedirect(reverse('following-list'))
    return redirect('following', username=username)


def follower_remove(request, username, follower_username):
    profile_user = get_object_or_404(User, username=username)

    # Ensure only the owner of the profile can remove followers
    if request.user != profile_user:
        return HttpResponseForbidden("You are not allowed to perform this action.")

    # Get the follower by their username
    follower = get_object_or_404(User, username=follower_username)
    print(f"{follower.username} deleted")
    
    # Remove the follow relationship
    Follow.objects.filter(follower=follower, following=profile_user).delete()
    # Optional: Add a success message
    messages.success(request, f"{follower.username} has been removed from your followers.")
    
    # Redirect back to the followers list
    # return HttpResponseRedirect(reverse('follower-list'))
    return redirect('followers', username=username)

def followers_list(request, username):
    user = get_object_or_404(User, username=username)
    profile = Profile.objects.get(user=user)

    followers = Follow.objects.filter(following=user).select_related('follower')
    close_friends = CloseFrens.objects.filter(friendProf__following=user).select_related('friendProf__follower')
    close_friend_usernames = {cf.friendProf.follower.username for cf in close_friends}

    context = {
        'profile_user': user,  # The user whose profile is being viewed
        'followers': followers,  # All users following the profile_user
        'close_friend_usernames': close_friend_usernames,  # Usernames in Close Friends
        'is_owner': request.user == user,  # Check if the logged-in user owns the profile
    }
    
    return render(request, 'followers_list.html', context)

def following_list(request, username):
    user = get_object_or_404(User, username=username)
    profile = Profile.objects.get(user=user)

    following = Follow.objects.filter(follower=user).select_related('following')

    context = {
        'profile_user': user,  # The user whose profile is being viewed
        'following': following,  # List of followers
        'is_owner': request.user == user,  # Check if the logged-in user is the profile owner
    }
    return render(request, 'following_list.html', context)

def follow(request, username, option):
    user = request.user
    following = get_object_or_404(User, username=username)

    try:
        f, created = Follow.objects.get_or_create(follower=request.user, following=following)

        if int(option) == 0:
            f.delete()
            Stream.objects.filter(following=following, user=request.user).all().delete()
        else:
            posts = Post.objects.all().filter(user=following)[:25]
            with transaction.atomic():
                for post in posts:
                    stream = Stream(post=post, user=request.user, date=post.posted, following=following)
                    stream.save()
        return HttpResponseRedirect(reverse('profile', args=[username]))

    except User.DoesNotExist:
        return HttpResponseRedirect(reverse('profile', args=[username]))


def register(request):
    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            try:
                # Validate the password
                password = form.cleaned_data.get('password1')
                validate_password(password)
                
                # Save the user
                new_user = form.save()
                username = form.cleaned_data.get('username')
                messages.success(request, f'Hurray! Your account was created successfully.')

                # Automatically log in the user
                new_user = authenticate(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'],
                )
                if new_user:
                    login(request, new_user)
                return redirect('index')

            except ValidationError as e:
                # Capture specific password errors
                for error in e:
                    messages.error(request, error)
        else:
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f"{field}: {error}")


    elif request.user.is_authenticated:
        return redirect('index')
    else:
        form = UserRegisterForm()
    context = {
        'form': form,
    }
    return render(request, 'sign-up.html', context)```

Posts url;

```from django.urls import path
from post.views import *

urlpatterns = [
    path('', index, name='index'),
    path('create-R-or-P', create_view, name='create-new'),
    path('newpost', NewPost, name='newpost'),
    path('<uuid:post_id>', PostDetail, name='post-details'),
    path('<uuid:post_id>/delete', post_del, name='post-del'),
    path('tag/<slug:tag_slug>', Tags, name='tags'),
    path('<uuid:post_id>/like', like, name='like'),
    path('<uuid:post_id>/favourite', favourite, name='favourite'),

]

Posts views:

from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, JsonResponse, HttpResponseForbidden
from django.contrib import messages
from post.models import Post, Tag, Follow, Stream, Likes
from django.contrib.auth.models import User
from post.forms import NewPostform
from authy.models import Profile
from django.urls import resolve
from comment.models import Comment
from comment.forms import NewCommentForm
from django.core.paginator import Paginator
from django.views.generic.edit import CreateView, FormMixin
from django.contrib.auth.mixins import LoginRequiredMixin

from django.db.models import Q
from post.models import Post, Follow, Stream

@login_required
def index(request):
    if request.user.is_anonymous:
        return redirect('sign-in')
    user = request.user
    all_users = User.objects.all()
    follow_status = Follow.objects.filter(following=user, follower=request.user).exists()

    profile = Profile.objects.all()

    posts = Stream.objects.filter(user=user)
    group_ids = []

    
    for post in posts:
        group_ids.append(post.post_id)
        
    post_items = Post.objects.filter(id__in=group_ids).all().order_by('-posted')

    query = request.GET.get('q')
    if query:
        users = User.objects.filter(Q(username__icontains=query))

        paginator = Paginator(users, 6)
        page_number = request.GET.get('page')
        users_paginator = paginator.get_page(page_number)


    context = {
        'post_items': post_items,
        'follow_status': follow_status,
        'profile': profile,
        'all_users': all_users,
        #'users_paginator': users_paginator,
        # 'users_paginator': users_paginator,
    }
    return render(request, 'index.html', context)


@login_required
def create_view(request):
    return render(request, 'create/create_options.html')
    


@login_required
def NewPost(request):
    user = request.user
    profile = get_object_or_404(Profile, user=user)
    tags_obj = []
    
    if request.method == "POST":
        form = NewPostform(request.POST, request.FILES)
        if form.is_valid():
            picture = form.cleaned_data.get('picture')
            caption = form.cleaned_data.get('caption')
            close = form.cleaned_data.get('is_close')
            tag_form = form.cleaned_data.get('tags')
            tag_list = list(tag_form.split(','))

            for tag in tag_list:
                t, created = Tag.objects.get_or_create(title=tag)
                tags_obj.append(t)
            p, created = Post.objects.get_or_create(picture=picture, caption=caption, user=user, is_close=close)
            p.tags.set(tags_obj)
            # p.is_close.set()
            p.save()
            return redirect('profile', request.user.username)
    else:
        form = NewPostform()
    context = {
        'form': form
    }
    return render(request, 'newpost.html', context)

@login_required
def PostDetail(request, post_id):
    user = request.user
    post = get_object_or_404(Post, id=post_id)
    comments = Comment.objects.filter(post=post).order_by('-date')

    if request.method == "POST":
        form = NewCommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = user
            comment.save()
            return HttpResponseRedirect(reverse('post-details', args=[post.id]))
    else:
        form = NewCommentForm()

    context = {
        'post': post,
        'form': form,
        'comments': comments
    }

    return render(request, 'postdetail.html', context)

@login_required
def Tags(request, tag_slug):
    tag = get_object_or_404(Tag, slug=tag_slug)
    posts = Post.objects.filter(tags=tag).order_by('-posted')

    context = {
        'posts': posts,
        'tag': tag

    }
    return render(request, 'tag.html', context)


# Like function
@login_required
def like(request, post_id):
    user = request.user
    post = Post.objects.get(id=post_id)
    current_likes = post.likes
    liked = Likes.objects.filter(user=user, post=post).count()

    if not liked:
        Likes.objects.create(user=user, post=post)
        current_likes = current_likes + 1
    else:
        Likes.objects.filter(user=user, post=post).delete()
        current_likes = current_likes - 1
        
    post.likes = current_likes
    post.save()
    # return HttpResponseRedirect(reverse('post-details', args=[post_id]))
    return HttpResponseRedirect(reverse('post-details', args=[post_id]))

@login_required
def favourite(request, post_id):
    user = request.user
    post = Post.objects.get(id=post_id)
    profile = Profile.objects.get(user=user)

    if profile.favourite.filter(id=post_id).exists():
        profile.favourite.remove(post)
    else:
        profile.favourite.add(post)
    return HttpResponseRedirect(reverse('post-details', args=[post_id]))

def post_del (request, post_id):
    user = request.user
    post = Post.objects.get(id=post_id)
    profile = Profile.objects.get(user=user)

    if post.user != user:
        return HttpResponseForbidden("You are not allowed to access this page.")
    
    if request.method == 'POST':
        post.delete()
        messages.success(request, "Reel has been successfully deleted.")
        return redirect("profile", profile.user.username)
    
    context= {
        "post": post,
        "user": user,
        "profile": profile
    }

    return render(request, "post_delete_view.html", context)````

posts urls;

from post.views import *

urlpatterns = [
    path('', index, name='index'),
    path('create-R-or-P', create_view, name='create-new'),
    path('newpost', NewPost, name='newpost'),
    path('<uuid:post_id>', PostDetail, name='post-details'),
    path('<uuid:post_id>/delete', post_del, name='post-del'),
    path('tag/<slug:tag_slug>', Tags, name='tags'),
    path('<uuid:post_id>/like', like, name='like'),
    path('<uuid:post_id>/favourite', favourite, name='favourite'),

]

This is one of your issues:

URLs being requested search through the urlpatterns in order.

When a request is made for “sign-in/”, Django is going to search through this list, and see that this url matches this pattern:

and so is going to dispatch this request to the UserProfile view.

You need to rework these URLs.

(There may be other issues as well, but this is the first that needs to be addressed.)

Read the docs at URL dispatcher | Django documentation | Django for a better understanding of what’s going on here.

Side Note: I’d also strongly suggest you adopt the standard Django / Python naming conventions. I found it quite confusing that you have an FBV named UserProfile - I would have expected something by that name to be a CBV, and so expected that this path definition was incorrect.

1 Like

THANK YOU, it worked, also sorry about the naming its a force of habit bcz I normally work with classes and class based views.