Skip to content
Advertisement

Django NOT NULL constraint failed userprofile.user_id in case of uploading a file

I am trying to practice a simple project: A user registers (using Django registration-redux), uploads some file, and then s/he is provided with a list of her files, being downloadable. Here are my models.py, forms.py, and views respectively:

models.py

JavaScript

forms.py

JavaScript

view.py

JavaScript

however when I login with a user and try to upload a file I get the error: IntegrityError at /new NOT NULL constraint failed: _userprofile.user_id

After digging a lot I noticed someone suggested the reason of the error is because the user is not included anyhow in the process of posting the form, so I tried whatever came to my mind and the case in which I added the user field to the forms.py worked:

forms.py

JavaScript

the problem however is that the form shown in the browser now includes a drop-down list containing all the registered users. I tried to associate the logged-in user with the form in the views by I kept seeing different errors. My question is: How can I associate the uploads with the logged-in user in a transparent manner. sorry if the question is too newbie-liked

Advertisement

Answer

Keep the user out of the form and add it on save:

JavaScript

I must say your model looks a bit odd; you have multiple profiles for each user, each with a single upload. Seems more likely you want a single profile, with a OneToOne relationship to User, than a separate Uploads model with a ForeignKey to UserProfile.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement