图像未使用Django上传到媒体根目录 [英] image isn't uploaded to media root using Django

查看:64
本文介绍了图像未使用Django上传到媒体根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手,并试图解决此问题,但找不到任何问题。表单的所有验证均已完美通过,但是图像实际上并未上传到媒体根目录。我试图显示图像,但只得到图像图标,而不是图像。

I am new to django and tried to fix this problem, but couldn't find whats wrong with it. All the validations of forms are passed perfectly, but the image doesn't actually get uploaded to the media root. I tried to show images and I only get image icon instead of Image.

设置根部分:

STATIC_ROOT = os.path.join(BASE_DIR, 'Vote','static')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

型号代码:

class Vote(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to= "images/vote/")
    rating = models.IntegerField(default=0)
    vote_type = models.ForeignKey(VoteType)

    def __unicode__(self):
        return self.name

views.py创建(查看)代码:

def create(request):
    class RequiredFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            super(RequiredFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False
    VoteFormSet = formset_factory(VoteForm, max_num=10, formset=RequiredFormSet)
    if request.method == 'POST': # If the form has been submitted...
        vote_list_form = VoteTypeForm(request.POST) # A form bound to the POST data
        vote_list_form.pub_date = timezone.now()
        # Create a formset from the submitted data
        vote_item_formset = VoteFormSet(request.POST, request.FILES)
        if vote_list_form.is_valid() and vote_item_formset.is_valid():
            vote_list = vote_list_form.save()
            for form in vote_item_formset.forms:
                vote_item = form.save(commit=False)
                vote_item.vote_type = vote_list
                print vote_item.vote_type
                vote_item.save()
            return HttpResponseRedirect('created/%s' %vote_list.id) # Redirect to a 'success' page
    else:
        vote_list_form = VoteTypeForm()
        vote_item_formset = VoteFormSet()
        vote_list_form.pub_date = timezone.now()

    c = {'vote_form': vote_list_form,
         'vote_item_formset': vote_item_formset,
        }
    c.update(csrf(request))

    return render_to_response('Vote/create.html', c)

,同时也有模板代码(非常庞大,不确定是否需要):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
{% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static 'Vote/style.css' %}" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Dynamic Forms in Django Example</title>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
  // Code adapted from http://djangosnippets.org/snippets/1389/
  function updateElementIndex(el, prefix, ndx) {
    var id_regex = new RegExp('(' + prefix + '-\\d+-)');
    var replacement = prefix + '-' + ndx + '-';
    if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex,
 replacement));
    if (el.id) el.id = el.id.replace(id_regex, replacement);
    if (el.name) el.name = el.name.replace(id_regex, replacement);
  }
  function deleteForm(btn, prefix) {
    var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
    if (formCount > 1) {
      // Delete the item/form
      $(btn).parents('.item').remove();
      var forms = $('.item'); // Get all the forms
      // Update the total number of forms (1 less than before)
      $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
      var i = 0;
      // Go through the forms and set their indices, names and IDs
      for (formCount = forms.length; i < formCount; i++) {
        $(forms.get(i)).children().children().each(function() {
          updateElementIndex(this, prefix, i);
        });
      }
    } // End if
    else {
        alert("You have to enter at least one todo item!");
    }
    return false;
  }
  function addForm(btn, prefix) {
    var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
    // You can only submit a maximum of 10 todo items 
    if (formCount < 10) {
      // Clone a form (without event handlers) from the first form
      var row = $(".item:first").clone(false).get(0);
      // Insert it after the last form
      $(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300);

      // Remove the bits we don't want in the new row/form
      // e.g. error messages
      $(".errorlist", row).remove();
      $(row).children().removeClass('error');

      // Relabel/rename all the relevant bits
      $(row).children().children().each(function() {
        updateElementIndex(this, prefix, formCount);
        if ( $(this).attr('type') == 'text' )
          $(this).val('');
      });

      // Add an event handler for the delete item/form link 
      $(row).find('.delete').click(function() {
        return deleteForm(this, prefix);
      });
      // Update the total form count
      $('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1); 
    } // End if
    else {
      alert("Sorry, you can only enter a maximum of ten items.");
    }
    return false;
  }
  // Register the click event handlers
  $("#add").click(function() {
    return addForm(this, 'form');
  });

  $(".delete").click(function() {
    return deleteForm(this, 'form');
  });
});
</script>

</head>
<body>

<h1>Dynamic Forms in Django Example</h1>
<h2>Todo List</h2>

<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
    <div class="section">
        {{ vote_form.as_p }}
    </div>

    <h2>Todo Items</h2>
    {{ vote_item_formset.management_form }}
    {% for form in vote_item_formset.forms %}
    <div class="item">
      {{ form.as_p }}
      <p style=""><a class="delete" href="#">Delete</a></p>
    </div>
    {% endfor %}

    <p><a id="add" href="#">Add another item</a></p>

    <input type="submit" value=" Submit " />

</form>

</body>
</html>


当我使用create view创建文件时,它不会将图像上传到媒体/图像/投票。为什么会发生这种情况?

When I create a file with create view, it doesn't upload an image to the media/images/vote. Why is this happening?

编辑1:添加了一些代码
有人还告诉我,我应该将此代码添加到我的代码中

EDIT 1:added some code Someone also told me that I should add this to my code

 if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
    )

现在的问题是,当我尝试获取图像时,程序会在以下位置查找图像:

"GET /Vote/216/voting/images/vote/background_OeAkutY.gif/ HTTP/1.1" 404 3135

我认为他是从我的urls.py文件中获取的。但是我不明白为什么程序在/ Vote / ID / voting ...而不是MEDIA_ROOT中查找。还是不是GET并不意味着它正在看那个地方?

Which I think he takes from my urls.py file. But I dont get why is the program looking in /Vote/ID/voting... instead of MEDIA_ROOT. Or does GET not mean that it is looking at that place?

这是我的Vote / urls.py:

urlpatterns = [
    #url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^$', views.index, name='index'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<pk>[0-9]+)/voting/$', views.voting, name='voting'),
    url(r'^create/$', views.create, name='create'),
    url(r'^create/created/(?P<pk>[0-9]+)/$', views.created, name='created'),
]


推荐答案

您对媒体和静态感到困惑。希望这可以澄清问题:

You are confused between media and static. Hopefully this will clarify the matter:

静态文件是作为

STATIC_ROOT collectstatic 命令将转储所有静态文件,因此您可以将它们移动到生产Web服务器。

STATIC_ROOT is where the collectstatic command will dump all static files, so you can move them to the production web server.

您无需弄乱 STATIC_ROOT 在开发过程中。

You don't need to mess with STATIC_ROOT during development.

在您的情况下,您有一个应用程序 Vote 如果您有一个 static 文件夹。您只需在开发过程中提供静态文件即可。您所要做的就是 {%static'folder / filename.ext'%} 其中 folder 是static内部包含您文件的文件夹。

In your case, you have an application Vote, and inside it you have a static folder. That's all you need to serve static files during development. All you have to do is {% static 'folder/filename.ext' %} where folder is the folder inside static that contains your file.

因此,如果您的目录结构为:

So if your directory structure is:

/Vote
 - __init__.py
 - migrations
 - admin.py
 - views.py
 - static
   - vote
     - images
       - foo.jpg

您需要< img src = {%static 'vote / images / foo.jpg'%}>

媒体文件是django调用的由应用程序用户上传的文件

要上传文件,您需要设置一个位置所有上传的文件均已存储。此位置是父目录,它在整个项目中是通用的。设置为 MEDIA_ROOT 。这应该是完整的系统文件路径

For uploading files, you need to set a location where all uploaded files are stored. This location is the parent directory and its universal across your entire project. The setting for this is MEDIA_ROOT. This should be a full system file path.

假设您设置了 MEDIA_ROOT ='/ home / foo / bar / proj / media',并且在您的模型中有:

Suppose you set MEDIA_ROOT = '/home/foo/bar/proj/media', and in your models you have:

image = models.ImageField(upload_to='logos/')

模型文件将上传到 / home / foo / bar / proj / media / logos /

要显示这些文件,您需要告诉django链接的名称指向 MEDIA_ROOT 目录,此设置为 MEDIA_URL

To display these files, you need to tell django the name of a link that points to the MEDIA_ROOT directory, this setting is MEDIA_URL.

对于开发,您需要做三件事:

For development, you need to do three things:


  1. 设置 MEDIA_URL / media /

配置 urls.py 以便提供媒体文件:

Configure urls.py to serve media files:

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


  • 添加' django.template.context_processors.media' TEMPLATES 中的 context_processors 。这将激活模板中的 {{MEDIA_URL}}

  • Add 'django.template.context_processors.media' to context_processors in TEMPLATES. This will activate {{ MEDIA_URL }} in your templates.

    这篇关于图像未使用Django上传到媒体根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆