26👍
You have to create a userprofile
for the user first:
profile = UserProfile.objects.create(user=request.user)
In your views.py
you can use get_or_create
so that a userprofile
is created for a user if the user doesn’t have one.
player, created = UserProfile.objects.get_or_create(user=request.user)
UPDATE: For automatically creating user profiles every time a new user is made, use signals.
In myapp/signals.py
do something like this:
@receiver(post_save, sender=User, dispatch_uid='save_new_user_profile')
def save_profile(sender, instance, created, **kwargs):
user = instance
if created:
profile = UserProfile(user=user)
profile.save()
6👍
If you are getting this error even if you’ve tried the suggestions above, it may caused by the fact that the first user you had created (with createsuperuser command) does not have a profile.
I was getting this error when I tried to login with that user. I solved it this way:
-Create a new user.
-Undo the changes. (Erase the code you’ve written for Profile or make them comment lines)
-Log in to your superuser.
-Give admin authorization to newly created user.
Now you can delete the first user. (The user with no profile)
- [Django]-How to save a model without sending a signal?
- [Django]-AssertionError: database connection isn't set to UTC
- [Django]-What is the use of PYTHONUNBUFFERED in docker file?
3👍
Nothing in what you’ve done forces the creation of a UserProfile
object when a User
is created. There are two basic ways of handling this:
-
If you always want a
UserProfile
to exist (which seems like the case as you give adefault
value toscore
, create apost_save
handler that creates a new profile when ever theUser
object is created (but not every time it’s saved, so make sure to check thecreated
argument in the handler). -
If it’s expected a user may not have a profile, you need to catch the
UserProfile.DoesNotExist
exception when trying to access it. If you do this frequently, make some kind of helper function.
UPDATED TO ANSWER SIGNAL QUESTION
It also looks like somewhere around here
post_save.connect(create_profile, sender=User)
should be added?
You would need to define a function called create_profile
and then wire it up as you have shown. I typically do this right in the models.py
file that includes the sender
but in this case where the sender is a built-in Django model and you’re already importing that model into the file where you define your UserProfile
that’s the place to do it. It would look something like:
def create_profile(sender, instance, created, *args, **kwargs):
# ignore if this is an existing User
if not created:
return
UserProfile.objects.create(user=instance)
post_save.connect(create_profile, sender=User)
- [Django]-Timestamp fields in django
- [Django]-Examples of Django and Celery: Periodic Tasks
- [Django]-CSS styling in Django forms
2👍
I had the same problem (= User exists, Profile does not but there is OneToOne relation introduced from Profile side) so I could not log in to Admin site. The app was already in production, and I could not trash the database.
The solution was to create a temporary view function fixme
with no login requirements (but a hard-to-guess URL) and visit it once. The view queried for all User objects, and then reverse-queried for the Profile of each User with get_or_create()
. If Profile was not there, it was created.
Print was for monitoring success through logs. Finally removed the view and URL from the production app.
def fixme(request):
users = User.objects.all()
for user in users:
obj, created = Profile.objects.get_or_create(user=user)
print(user.username,' : ',created)
print("all done")
return HttpResponse("It's done.")
- [Django]-Django ModelChoiceField: filtering query set and setting default value as an object
- [Django]-Django: formats of urlpatterns in urls.py
- [Django]-Docker&Celery – ERROR: Pidfile (celerybeat.pid) already exists
1👍
First Register profile model in admin.py if not already done.
Create new superuser using ./manage.py createsuperuser.
Log in with new superuser.
From Admin panel click Profile and add new entry and selct user from user dropdown and save.
- [Django]-How to use "OR" using Django's model filter system?
- [Django]-Migrating data from "Many-To-Many" to "Many-To-Many Through" in django
- [Django]-Related_name argument not working as expected in Django model?
1👍
I solve this problem (Django 3.8.3-Mongodb). Firstly, I created signals.py, then I added apps.py in project.
signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile
@receiver(post_save,sender=User)
def update_user_profile(sender,instance,created,**kwargs):
if created:
profile = Profile.objects.create(user =instance)
apps.py
from django.apps import AppConfig
class ProfileConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Profile'
def ready(self):
import Profile.signals
views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.urls.base import reverse
from .forms import ProfileForm
from .models import Profile
from django.shortcuts import redirect, render,get_object_or_404
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
login_required(login_url="user:login")
def dashboard(request):
return render(request,"dashboard.html")
@login_required(login_url="user:login")
def get_profile(request):
profile = get_object_or_404(Profile,user=request.user)
return render(request,"profile.html",{"profile":profile})
@login_required(login_url="user:login")
def update_profile(request):
profile = get_object_or_404(Profile, user=request.user)
form = ProfileForm(instance=profile)
if request.method=="POST":
form = ProfileForm(request.POST,request.FILES,instance=request.user.user_profile)
if form.is_valid():
form.save()
messages.success(request,"Profile is updated successfully")
return HttpResponseRedirect(reverse("profile:profile"))
else:
return render(request,"profile.html",{"form":form})
return render(request,"edit.html",{"form":form})
- [Django]-Django admin action without selecting objects
- [Django]-Django reverse causes circular import
- [Django]-How to run a celery worker with Django app scalable by AWS Elastic Beanstalk?
1👍
I had the same error but i solved it by creating my signals example below
then i edited my apps.py as follows:
`from django.apps import AppConfig
class BlogConfig(AppConfig):
default_auto_field = ‘django.db.models.BigAutoField’
name = ‘app_name’
def ready(self):
import app_name.signals`
- [Django]-Django REST framework – limited queryset for nested ModelSerializer?
- [Django]-Rendering JSON objects using a Django template after an Ajax call
- [Django]-How do Django models work?
0👍
Answering your updated question. There is already a save() method in models and it gets called every time you save a model (in your case when you call create_user()). So all you need to do is define a handler function and connect it to the post_save signal.
def create_extension(sender, instance, created, *args, **kwargs): if created: # do your thing models.signals.post_save.connect(create_extension, sender=User, dispatch_uid='create_extension')
I usually put the handler functions into a separate file signals.py and add connect() statements at the end of models.py
- [Django]-Enforce unique upload file names using django?
- [Django]-Last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework
- [Django]-How to get Django form field from model field?
0👍
Just try to create a new user using shell to get access to the admin page then create a profile from admin page for the old user : python manage.py createsuperuser
To access to shell, inside your directory project ine terminall type :
python manage.py shell
- [Django]-Aggregating save()s in Django?
- [Django]-How to install libpq-fe.h?
- [Django]-Access ForeignKey set directly in template in Django
0👍
I’m a bit kinda late for this but ill just, share the solution that worked for me on Django 3.0.8…
Error : RelatedObjectDoesNotExist: User has no profile
This the is where my error was directing me to :
@login_required
def dashboard(request):
if request.method == 'POST':
user_form = UserEditForm(instance=request.user, data=request.POST)
profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES)
Note: You have to login or your profile to be saved.
Just after creating your account, you should be able to see that you are not logged in and you will have to log in to for your profile be saved and to start working.
- [Django]-Defining a model class in Django shell fails
- [Django]-Add Serializer on Reverse Relationship – Django Rest Framework
- [Django]-Create composite index from a Django model
0👍
Go inside your views, at your create_user function and do these
profile = userprofile()
profile.user = user
profile.save()
I had similar problems and after 3 days of research, I was able to sort this with just the above 3 lines of codes.
- [Django]-Can django's auth_user.username be varchar(75)? How could that be done?
- [Django]-Django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
- [Django]-Django admin: can I define fields order?
0👍
The problem is that your superuser isn’t connected to a userprofile.
There are one of the many ways to fix this, one is creating the user from a shell
py manage.py shell
> from django.contrib.auth.models import User
>
> user=User.objects.create_user('UserName', password='AdminPassword')
> user.is_superuser=True
> user.is_staff=True
> user.save()
> exit()
And another way around being, you can add the following code in the Models.py so that the superuser you create is added to the scope of UserProfile.
User.userprofile = property(lambda
u:Userprofile.objects.get_or_create(user=u)[0])
- [Django]-Extending urlize in django
- [Django]-Django migration strategy for renaming a model and relationship fields
- [Django]-Test if Django ModelForm has instance
0👍
If you created a user prior to setting up authentication on your app, you need to create a new super user on the terminal and then login with that account. I am certain there is no profile created as stated by the error!
- [Django]-How to create Password Field in Model Django
- [Django]-Silence tqdm's output while running tests or running the code via cron
- [Django]-Django for loop counter break
0👍
Had the same error.
Adding the following code in models.py of the apps solved the problem.
def create_profile(sender, instance, created, *args, **kwargs):
if not created: # if user already exits then ignore
return
UserProfile.objects.create(user=instance)
post_save.connect(create_profile, sender=User)
- [Django]-'Manager' object is not callable
- [Django]-Django: How do I override app-supplied urls in my project urlconf?
- [Django]-Displaying graphs/charts in Django