Your code gives an impression that you need more help, beyond the error that has occured. Here are my suggestions how to improve your code in general:
The recommended way to build relations to the user model is to use the setting AUTH_USER_MODEL.
Class names should be by convention in pascal case (PascalCase) and in singular.
Variable names, that means also class attributes, should be by convention in snake case (snake_case).
Thus your code could be enhanced like this:
from django.conf import settings
from django.db import models
class UserFile(models.Model):
filename = models.CharField(max_length=50)
browse = models.FileField()
username = models.ForeignKey(settings.AUTH_USER_MODEL)
Naming is an extreme important topic. You should name your classes, methods, attributes very meaningful. Using username
for a foreign key field is not very descriptive. This variable doesn't hold the value for the username, but the whole User object. Having a field filename
is also very confusing, because the FileField
actually saves the filepath and consequently the filename in the database as a string (varchar).
Code is written once, but read many times. Your intents are not clear to the reader.
If you add the field username
after this model has been migrated, you have first two variations: required or optional field.
If it should be an optional field, you can allow NULL:
username = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
Then run:
python manage.py makemigrations
python manage.py migrate
This is the easier way. But if this field is required, the migration will need to know which value should be assigned to the present entries in the table and will ask you interactively to add a default value. This is not the same as specifying a default value as an option.
In your case it means all future entries where username isn't explicitly specified will have the value 1. Do you really want that? Are you sure that there is an entry with this primary key in the table for users?
EDIT (2017-10-10):
If you have messed with the migrations, you can manually clean it up. In the database there is a table django_migrations
which keeps track of all applied migrations. It has four columns:
-----------------------------
| id | app | name | applied |
-----------------------------
If you use MySQL you could check the migrations for your app with the command:
SELECT * FROM django_migrations WHERE app = 'your_app';
Delete the entries in this table and the files in the migrations
directory of your app which are causing problems. Then start over.