2

我在 Django 中有一个表单,用户可以在其中以单个表单提交文件/图像/文本,如下所示。

<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 和 except 在以下方式:

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)

有没有其他更好的方法来做到这一点。代码看起来不太好,除了所有的尝试之外。

4

1 回答 1

1

可以使用更好的方法get,如果字典中不存在键,将返回第二个参数而不引发异常,这里是关于这个主题的一个很好的答案 - >链接

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})

这是一个草稿,但在表单无效的情况下,将用户重定向回表单当然总是一个好方法

于 2021-02-13T16:04:58.337 回答