Im sorry but I'm really new to Django and I already tried the steps in the documentation. Unfortunately, it's not working quite as I would expect. I was hoping that after executing the steps it would save the file to my media folder. If possible I'd also like to use AJAX but I can't understand the flow.
HTML
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.TextField(max_length=500, blank=True)
contact_number = models.CharField(max_length=30, blank=True)
profile_picture = models.FileField(null=True,blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
forms.py
class UploadForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('profile_picture',)
views.py
def model_form_upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/home/')
I'm trying to save a photo for a user's profile. Please help me. If there is a way to do this with AJAX, that would be helpful as well.
heres how I solved my problem :
I used this method to extract my image from the input first
function extractPhoto(input) {
var files = input[0].files;
if (!files.length) {
alert('Unable to upload: no file selected');
return;
}
return files[0]
}
then I used jQuery's FormData and ajax to pass the extracted photo to my view
var image = $("#image");
$("#uploadbutton").click(function () {
const form = new FormData();
form.append('image', extractPhoto(image));
generateCSRFToken();
$.ajax({
url: '/upload_photo/',
data: form,
type: "POST",
contentType: false,
processData: false,
success: function (data) {
location.reload();
},
error: function (data) {
}
})
});
then I handle it in my views.py
def upload_photo(request):
if 'image' not in request.FILES:
return HttpResponse(status=400)
user = request.user
user.profile.profile_picture = request.FILES.get('image')
user.profile.save();
return HttpResponse(status=200)