2

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

<form id="send-form" action="{% url 'chat:message' context.room_id %}"  method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <table style="width: 100%">
                <input type="hidden" name="from" value="{{ user }}">
                <input type="hidden" name="next" value="{{ request.path }}">
                <tr style="width: 100%">
                    <td style="width: 50%">
                        <input type="text" id="chat-input" autocomplete="off" placeholder="Say something" name="text" id="text"/>
                    </td>
                    <td style="width: 16%">
                        <input type="file" name="image" accept="image/*" id="image">
                    </td>
                    <td style="width: 16%">
                        <input type="file" name="file" accept="image/*" id="file">
                    </td>
                    <td style="width: 16%">
                        <input type="submit" id="chat-send-button" value="Send" />

                    </td>
                </tr>
            </table>
        </form>

In views.py, the form has to be submitted even if any of the three inputs is missing i.e, even if user submits only text/ only image/only file, the data has to be uploaded into database and I have written using try and except in the following way:

def messages(request, room_id):
    if request.method == 'POST':
        try:
            img = request.FILES['image']
        except:
            img = None
        try:
            text = request.POST['text']
        except:
            text = None
        try:
            file = request.FILES['file']
        except:
            file = None
        path = request.POST['next']
        fields = [img,file,text]
    ChatMessage.objects.create(room=room,user=mfrom,text=text,document=file,image=img)

Is there any other better way to do it. The code looks not so good with all the try excepts.

1
  • 2
    Use .get(), it returns the value if the key exists otherwise None which is essentially what you are doing but in one method call and without a try/except: img = request.FILES.get('image') Commented Feb 13, 2021 at 14:40

1 Answer 1

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

def messages(request, room_id):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES) # replace UploadFileForm with your form name
        if 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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.