图像没有被上传//我的views.py中的python代码可能有问题

时间:2016-01-18 00:10:46

标签: python django

你好,我按照这里的步骤进行操作; Need a minimal Django file upload example我不确定我做错了什么。我试图添加一个用户能够发布图片的功能。这是我的尝试

settings.py

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root")
MEDIA_URL = '/media/'

    models.py

class Category(models.Model): 
    image = models.ImageField(upload_to='images',blank=True, null=True)

forms.py

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128)
    description = forms.CharField(max_length=300)
    image = forms.ImageField()

    class Meta:
        model = Category



my views.py

@login_required
def add_category(request):
    if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
        return render(request,'main/category_already_exists.html')
    if request.method == 'POST':
        category = Category(author=request.user)
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            form.save(commit=True)
            return redirect('index')

    else:
        form = CategoryForm()

    return render(request, 'main/add_category.html', {'form':form})


category.html

{% load staticfiles %}

{{category.image}} 

1 个答案:

答案 0 :(得分:0)

我假设您在模板中缺少enctype表单属性。

<form method="POST" enctype="multipart/form-data">
  {{ form.as_p }}
  <input type="submit" value="Submit" />
</form>

此外,在您的视图中,实例化您的表单应该是

form = CategoryForm(request.POST, request.FILES, instance=category)