如何上传图片?

时间:2014-03-19 18:59:45

标签: python django django-models

请帮助修复脚本。

在django1.6中我尝试使用sqllite加载图像的界面。

views.py:

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django import template
import datetime
import requests
from django.shortcuts import render_to_response, redirect
from django.core.mail import send_mail
from proj1.forms.forms import ContactForm
from sends.models import Sends, Carousel, MediaForm


def admin_carousel(request):    
    if request.method == "POST":
        form = MediaForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    else:
        form = MediaForm()
        t = template.loader.get_template('admin_carousel.html')
        c = template.Context({'name': 'Adrian'})
        html = t.render(c)      
        return HttpResponse(html, {'form': form})   

models.py:

from django.db import models
from django.forms.models import modelform_factory

class Carousel(models.Model):
    media_file = models.FileField(upload_to='kalininCarousel/') 

MediaForm = modelform_factory(Carousel) 

template.html:

<form action="" method="post" name="carousel_image" enctype="multipart/form-data">
    <input type="file" name="img_car" value="" />

    <input type="submit" name="img_submit" value="Загрузить изображение" />
</form>

问题是提交表单后我收到以下错误消息:

Django Version: 1.6.2
Exception Type: ValueError
Exception Value:    
The view proj1.views.views.admin_carousel didn't return an HttpResponse object.
Exception Location: C:\Python33\lib\site-packages\django\core\handlers\base.py in get_response, line 132

1 个答案:

答案 0 :(得分:2)

你的问题在这里:

def admin_carousel(request):    
    if request.method == "POST":
        form = MediaForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()

Django视图必须返回HttpResponse个对象,即使它是空的。尝试这样的事情:

def admin_carousel(request):    
    if request.method == "POST":
        form = MediaForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return HttpResponse(200)