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

class UserProfile(models.Model):
    user = models.ForeignKey(User, related_name='uploaded_by')
    names = models.CharField(max_length=40)
    lastname = models.CharField(max_length=50)
    email = models.EmailField()
    uploads = models.FileField(upload_to= 'blablabla')

    def __str__(self):
        return self.email

forms.py

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['names', 'uploads']

view.py

from .forms import UserProfileForm
from .models import UserProfile
@login_required()
def new(request):
    form = UserProfileForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
    context = {'title': 'welcome', 'form': form}
    return render(requst, 'upform.html', context)

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

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['names', 'uploads']

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:

if form.is_valid():
    profile = form.save(commit=False)
    profile.user = request.user
    profile.save()

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