如何上传到Django中的imagefield

时间:2018-06-18 12:38:30

标签: javascript django

我可以在Django Framework中创建我的对象并直接从那里上传图像。 现在我想从HTML表单上传图像,而不是从Django Framework上传图像。如何将HTML中的图像上传到我的/media/文件夹?

my models.py:

class New(models.Model):
news_title = models.CharField(max_length=100,blank=False,verbose_name="Titolo news")
news_small_description = models.TextField(default=None,null=True,blank=True,verbose_name="Descrizione breve")
news_description = models.TextField(default=None, null=True, blank=True, verbose_name="Descrizione")
news_image = models.ImageField(default=None, blank=True, null=True, verbose_name="Immagine")
news_date = models.DateTimeField(auto_now=True, null=True, verbose_name="Data news")
class Meta:
    verbose_name = "New"
    verbose_name_plural = "News"

我的view.py POST API:

@api_view(['POST'])
def send_news(request):
    try:
        newstitle = get_param(request.POST, "newstitle", NOT_NONE)
        newssmalldescription = get_param(request.POST, "newssmalldescription", OPTIONAL)
        newsdescription = get_param(request.POST, "newsdescription", OPTIONAL)
        newsimage = get_param(request.POST, "newsimage", OPTIONAL)

        New.objects.create(
            news_title = newstitle,
            news_small_description = newssmalldescription,
            news_description = newsdescription,
            news_image = newsimage,
        )

        return HttpResponse("La tua novità è stata aggiunta correttamente.")

    except ValueError as ve:
        print(ve)
        return HttpResponseBadRequest(json.dumps({"error_message": str(ve)}), content_type='application/json')
    except Exception as e:
        print(e)
        return HttpResponseServerError(json.dumps({"error_message": str(e)}), content_type="application/json")

在我的html中,我向我的send_news API发送了一个POST请求,唯一缺少的字段是newsimage。 但我无法理解如何从我的HTML页面向我的MEDIA文件夹收取图片。谢谢!

2 个答案:

答案 0 :(得分:0)

使用文件时,您必须使用request.FILES代替request.POST
newsimage = get_param(request.FILES, "newsimage", OPTIONAL)

答案 1 :(得分:0)

您的表单是否为enctype =“multypart / form-data”?

 <form class="col" method="POST" enctype="multipart/form-data"action="{% url 'your_action' %}">

我遇到了同样的问题