Skip to content Skip to sidebar Skip to footer

Simplify Form Submission In Django

I have a form in Django where the user can submit a file/ an image/ text in a single form as follows.

Solution 1:

A nicer approach could be use the get, in case of the key is not present in the dictionaty, will return the second argument without raise an exception here a nice answer on this topic -> link

defmessages(request, room_id):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES) # replace UploadFileForm with your form nameif form.is_valid(): # just check if the form is valid, i don't know if you are doing it before
            img = request.FILES.get('image', None)
            text  = request.FILES.get('text', None)
            file  = request.FILES.get('file', None)
            path = request.POST['next']
            fields = [img, file, text]
        ChatMessage.objects.create(
            room=room, 
            user=mfrom,
            text=text,
            document=file,
            image=img
        )
        else:
            return render(request, 'upload.html', {'form': form})

It's a draft, but of course is always a good approach to redirect the user back to the form in case the form is not valid

Post a Comment for "Simplify Form Submission In Django"