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.