Django - uploading image to database raises IntegrityError - django

I'm trying to allow users to upload an image. When users are first created, they are given a unique ID / primary key. When users upload an image, I want to save that image in a folder depending on what the users unique ID is. For example, if the users unique ID is 1, I want to save it in
1/uploadedPhotos/imageName
This is my model:
def get_file_path(instance, filename):
return os.path.join('%s/uploadedPhotos' % instance.user_id, filename)
class UserImages(models.Model):
user = models.ForeignKey(User)
photo = models.ImageField(upload_to=get_file_path)
and this is my form:
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserImages
fields = ['photo']
and this is my view:
def uploadImageView(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return redirect('/')
else:
form = UploadImageForm()
return render(request, 'uploadImagePage.html', {'uploadImageForm': form})
The URL which calls the uploadImageView view is /uploadImage/. when I go to that URL and upload an image using the uploadImageForm, it gives an error saying:
IntegrityError at /uploadImage/
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (1, null, None/uploadedPhotos/imageName.png).
and the traceback leads back to the
form.save()
line in my uploadImageView. What am I doing wrong to cause this error?

Your UserImages model requires user but your form UploadImageForm is asking only asking for photo. You need to set user, try something like this:
def uploadImageView(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('/')
else:
form = UploadImageForm()
return render(request, 'uploadImagePage.html', {'uploadImageForm': form})

obj = form.save(commit=False)
obj.user = request.user
obj.save()

You must extract user from request.user and add it to form data.

Related

How to get the ID of the record created in the model after saving it from a Form

Let's say I submit a form to the back-end and I save a record of the model in the following way:
views.py:
def viewName(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save() #I want to get the id of this after it is saved
else:
print (form.errors)
form = ProjectForm()
return render(request, 'index.html', context)
forms.py:
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = '__all__'
Right after saving the form, I would like to get the id of the record for the model.
I tried with form.id and form.pk as I saw in other similar questions without success.
How can I get the id or the pk of the new entry added to the Project model?
form.save() returns the object, so:
obj = form.save()
print(obj.pk)

Django Send Form By Authenticated User

i stuck when trying to send data or save data with django form by user it self (logged).
When i test why form "From" user must be selectable not automatic selected by user it self.
class ValidationCreate(forms.ModelForm):
class Meta:
model = About
fields = '__all__'
def upload(request):
upload = ValidationCreate()
if request.method == 'POST':
upload = ValidationCreate(request.POST, request.FILES)
if upload.is_valid():
upload.save()
return redirect('validation')
else:
return HttpResponse("""your form is wrong, reload on reload""")
else:
return render(request, 'upload_form.html', {'about_form': upload})
sample
this way you can assign the request.user
if upload.is_valid():
instance = upload.save(commit=False)
instance.profile = Profile.objects.get(user=request.user) # you can change the user if field name is different
instance.save()
return redirect('validation')
else:
in forms
fields = ['field_1', 'field_2',] # except user field

How to add model with ImageField using form in a correct way in django

I have a ModelForm containing a field: image = models.ImageField:
class InstanceForm(ModelForm):
class Meta:
model = Instance
exclude = ('created_at','author',)
And my view is:
def add_instance(request):
if request.user.is_authenticated():
if request.POST:
form=InstanceForm(request.POST,request.FILES)
if form.is_valid():
new_instance=form.save(commit=False)
new_instance.author=request.user.username
new_instance.save()
locals().update(csrf(request))
return render_to_response(...)
else:
return render_to_response(...)
else:
form=InstanceForm()
return render_to_response(...)
else: return HttpResponse(...)
When my form is not valid it shows not only errors, but field 'image' without path to image. It's working in this way, even if I have chosen image at first using Browse.

How to save current login user? user_id may not be NULL

I have this error:
appname_mymodel.user_id may not be NULL
def form_view(request):
user = request.user
f_form = FForm(request.POST or None, request.FILES or None)
if request.method == "POST":
if f_form.is_valid():
f_form.user = user
f_form.save()
return HttpResponseRedirect('/thanks/')
return render_to_response('upload.html', {'f_form': f_form}, context_instance=RequestContext(request))
forms.py:
class FForm(ModelForm):
class Meta:
model = MyModel
exclude =['user']
How to save current login user?
The form doesn't have a user attribute so it is useless to assign to it. What you should do instead is:
if f_form.is_valid():
my_model = f_form.save(commit=False)
my_model.user = user
my_model.save()
This way the form will construct a MyModel instance, but will not attempt to save it to the database. Then you can fill the user field and save it.
You can also provide the necessary data as an instance argument:
f_form = FForm(request.POST or None, request.FILES or None, \
instance = MyModel(user=user))
if request.method == "POST":
if f_form.is_valid():
f_form.save()
return HttpResponseRedirect('/thanks/')

Uploading Profile Image using Django ModelForm

I've looked around at related questions, but none of the answers seem to work. I'm trying to upload a profile image for a user and have it replace (overwrite) the current image. Upon saving the image I want to change the filename to the user id. In it's current form the image will upload, but it won't replace the existing image (e.g. it'll be saved as 2_1.png).
class PhotoForm(forms.ModelForm):
def save(self):
content_type = self.cleaned_data['photo'].content_type.split('/')[-1]
filename = '%d.%s' % (self.instance.user.id, content_type)
instance = super(PhotoForm, self).save(commit=False)
instance.photo = SimpleUploadedFile(filename, self.cleaned_data['photo'].read(), content_type)
instance.save()
return instance
class Meta:
model = UserProfile
fields = ('photo',)
def photo_form(request):
if request.method == 'POST':
form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
if form.is_valid():
form.save()
else:
form = PhotoForm()
return render(request, 'photo_form.html', {'form': form})
def photo_form(request):
if request.method == 'POST':
form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
if form.is_valid():
handle_uploaded_file(request.FILES['<name of the FileField in models.py>'])
def handle_uploaded_file(f):
dest = open('/path/to/file', 'wb') # write should overwrite the file
for chunk in f.chunks():
dest.write(chunk)
dest.close()
check here: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/
If that doesn't work, I suppose you could just use os.system to delete the file if the form is accepted. That probably wouldn't be that great of a solution, but it should work.