I have a Django custom user model 'es_user' which inherit the Django's default user model. when a user signup it works fine but that user will be part of 'Users' and nothing will add upto es_user. so each time a user sign up I've to go to admin panel and add a signed in 'User' to 'es_user'.

So to solve that I added these 2 to lines to views.py

 es_user_instance = es_user.objects.create(user= req_user)

which gives me this error

ValueError at /signup/

Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f9c787b9be0>>": "es_user.user" must be a "User" instance.


class es_user(models.Model):
user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE)


def signup(request):
signup_form_instance = SignUpForm()

if request.method == "POST":

    signup_form_instance = SignUpForm(request.POST)
    if signup_form_instance.is_valid():
        signup_form_instance2 = signup_form_instance.save(commit = False)
        req_user = request.user
        signup_form_instance2.password = make_password(signup_form_instance.cleaned_data['password'])
        es_user_instance = es_user.objects.create(user= req_user)

        return index(request)#successful signup redirect or return
        print("SIGN UP FORM INVALID")

return render(request,'signup.html',{'signup_form':signup_form_instance})


class SignUpForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password')

can somebody tell me where is the problem

NOTE: I've used this custom user model because I will be adding many more fields to 'es_user' later on.

1 Answers

damores On Best Solutions

The problem is that req_user = request.user is returning an AnonymousUser because you haven't logged in the user yet. So before using request.user, login the user first.

Alternatively, you could just add the user you just created without logging it in:

es_user_instance = es_user.objects.create(user=signup_form_instance2)