Django Wont Store AuthUser Referenced As Foreign Key In My Model

- 1 answer

I created my model that have authUser referenced as foreign key, then using django Form API i am trying to store data into my DB but my user field remains null.

I have used build-in FORM API to receive an uploaded file and before storing my file, i also store filename. I tried to do the same for userField but django throw ValueError.

class sample(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True ,default=1)
    submit_time = models.DateTimeField(auto_now=True)
    file_name = models.CharField(max_length=1024)
    score = models.FloatField(default=0.0)
    is_pending = models.BooleanField(default=True)
    is_complete = models.BooleanField(default=False)
    json_URL = models.FilePathField()
    sample = models.FileField(upload_to='samples/')

def upload(request):
    if request.method == 'POST':
        file = request.FILES['sample']
        form = SampleForm(request.POST, request.FILES)
        if form.is_valid():
            new_sample =  
            new_sample.file_name =
            new_sample.user = #throws ValueError Cannot assign  "sample.user" must be a "User" instance.
            return redirect('reports')
            print("form is invalid")
        form = SampleForm()
    if request.method == 'GET':
        return render(request, 'upload2.html', {'form': form})

class SampleForm(forms.ModelForm):
    class Meta:
        model =sample

my goal is to save the user id in my db so i know who uploaded the file.



You should use request.user to the new_sample.user object, or (or to the request.user_id attribute, like:

# …

new_sample =  
new_sample.file_name =
new_sample.user = request.user
return redirect('reports')

# …

By using, you get a reference to the field of the Usermodel, not an object.