简化Django中的表单提交 [英] Simplify form submission in Django
问题描述
我在Django中有一个表单,用户可以按以下形式提交文件/图像/文本.
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>
在 views.py
中,即使缺少三个输入中的任何一个,也必须提交表单,即,即使用户仅提交文本/仅图像/仅文件,数据也必须是上传到数据库中,并且我已使用try和编写了以下内容:
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.
推荐答案
更好的方法是使用 get
,如果字典中不存在该键,则将返回第二个参数毫无例外这里是有关此主题的好答案->链接
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
这篇关于简化Django中的表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!