[python] __init__() got an unexpected keyword argument 'user'

i am using Django to create a user and an object when the user is created. But there is an error

__init__() got an unexpected keyword argument 'user'

when calling the register() function in view.py. The function is:

def register(request):  
    '''signup view'''     
    if request.method=="POST":  
        form=RegisterForm(request.POST)  
        if form.is_valid():  
            username=form.cleaned_data["username"]  
            email=form.cleaned_data["email"]  
            password=form.cleaned_data["password"]  
            user=User.objects.create_user(username, email, password)  
            user.save()
            return HttpResponseRedirect('/keenhome/accounts/login/')
        else: 
            form = RegisterForm()      
            return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))  

    #This is used for reinputting if failed to register    
    else: 
        form = RegisterForm()      
        return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))

and the object class is:

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, temp=65):
        self.temp=temp

    TURN_ON_OFF = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    TEMP = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    on_off = models.CharField(max_length=2, choices=TURN_ON_OFF)
    temp = models.CharField(max_length=2, choices=TEMP)

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        LivingRoom.objects.create(user=instance)

post_save.connect(create_control_livingroom, sender=User)

The Django error page notifies the error information: user=User.objects.create_user(username, email, password) and LivingRoom.objects.create(user=instance)

I tried to search this problem, finding some cases, but still cannot figure out how to solve it.

This question is related to python django django-models django-forms django-views

The answer is


LivingRoom.objects.create() calls LivingRoom.__init__() - as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default keyword as explained in the FineManual.


I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-models

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries "Post Image data using POSTMAN" What does on_delete do on Django models? Django values_list vs values What's the difference between select_related and prefetch_related in Django ORM? Django Model() vs Model.objects.create() 'NOT NULL constraint failed' after adding to models.py django - get() returned more than one topic How to convert Django Model object to dict with its fields and values? How do I make an auto increment integer field in Django?

Examples related to django-forms

__init__() got an unexpected keyword argument 'user' What's the best way to store Phone number in Django models How to create Password Field in Model Django Django Forms: if not valid, show form with error message What is the equivalent of "none" in django templates? How to create password input field in django Python regex for integer? Change a Django form field to a hidden field CSS styling in Django forms Django: Model Form "object has no attribute 'cleaned_data'"

Examples related to django-views

Unable to import path from django.urls Class has no objects member The view didn't return an HttpResponse object. It returned None instead django - get() returned more than one topic __init__() got an unexpected keyword argument 'user' How can I get the username of the logged-in user in Django? Django DoesNotExist How do I call a Django function on button click? Django optional url parameters Update only specific fields in a models.Model