Django不允许使用一种输入法上传多个图像(POST):/图片/

nx7onnlm  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(127)

嗨,我刚刚建立了一个HTML表单,用户可以上传多个图像,但我得到Method Not Allowed (POST): /images/所有的时间。在image_list.html的图像应该显示。谢谢你的帮助
models.py

class ImageModel(models.Model):
    images = models.ImageField(upload_to='products/')

forms.py

class ImageForm(ModelForm):
    class Meta:
        model = ImageModel
        fields = ['images']
        widgets = {
            'images': FileInput(attrs={'multiple': True}),
        }

views.py

class ImageFormView(FormMixin, TemplateView):
    template_name = 'image_form.html'
    form_class = ImageForm

    def form_valid(self, form):
        # Save the images to the database
        form.save()
        # Redirect to the image list view
        return redirect('image_list')
    
    
class ImageListView(ListView):
    model = ImageModel
    template_name = 'image_list.html'
    context_object_name = 'images'

image_form.html

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Submit
</form>

image_list.html

{% load static %}
{% for image in images %}
<img src="{{image.images.url}}" alt="">
{% endfor %}

urls.py

urlpatterns = [
    path('images/', views.ImageFormView.as_view(), name='image_form'),
    path('', views.ImageListView.as_view(), name='image_list'),
]
yyyllmsg

yyyllmsg1#

您需要关闭HTML表单中的按钮标记

<form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

相关问题