Ad

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.

Models.py

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/')

Views.py

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

forms.py

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

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

Ad

Answer

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

# …

new_sample = form.save(commit=False)  
new_sample.file_name = file.name
new_sample.user = request.user
form.save()
return redirect('reports')

# …

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

Ad
source: stackoverflow.com
Ad