def upload_images(request, username, trip_name_slug, post_name_slug): # Construct the context Dictionary context_dict = {} try: inpost = BlogPost.objects.get(slug=post_name_slug) context_dict['post'] = inpost trip = Trip.objects.get(slug=trip_name_slug) context_dict['trip'] = trip except BlogPost.DoesNotExist: context_dict['post'] = None except Trip.DoesNotExist: context_dict['trip'] = None if request.method == 'POST': # If POST use form to create PostImage object form = PhotoForm(request.POST, request.FILES) if form.is_valid(): photo = form.save(commit=False) photo.post = inpost photo.save() # Create a JSON from the new PostImage object, and pass that in as our response, since the JS uses JSON data = { 'is_valid': True, 'name': photo.name, 'url': photo.image.url } else: data = {'is_valid': False} return JsonResponse(data) else: # If GET add current post photos to the context dict photos_list = PostImage.objects.filter(post=inpost) context_dict["photos"] = photos_list return render(request, 'app/upload_images.html', context_dict)
def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = { 'is_valid': True, 'name': photo.file.name, 'url': photo.file.url } else: data = {'is_valid': False} return JsonResponse(data)