Reputation: 2084
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.
Upvotes: 2
Views: 105
Reputation: 1129
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
Upvotes: 1