The image is not downloaded to the media root using 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.

settings root part:

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

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

models code:

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 create(view) code:

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 =
        # 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 =
            for form in vote_item_formset.forms:
                vote_item =
                vote_item.vote_type = vote_list
                print vote_item.vote_type
            return HttpResponseRedirect('created/%s' # Redirect to a 'success' page
        vote_list_form = VoteTypeForm()
        vote_item_formset = VoteFormSet()
        vote_list_form.pub_date =

    c = {'vote_form': vote_list_form,
         'vote_item_formset': vote_item_formset,

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

and there also is template code (which is pretty huge and not sure if it is required):

{% load staticfiles %}

Dynamic Forms in Django Example

$(document).ready(function() {
  // Code adapted from
  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,
    if ( =, replacement);
    if ( =, replacement);
  function deleteForm(btn, prefix) {
    var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
    if (formCount > 1) {
      // Delete the item/form
      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

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

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

      // 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');

Dynamic Forms in Django Example

Todo List

{% csrf_token %}
{{ vote_form.as_p }}

Todo Items

{{ vote_item_formset.management_form }} {% for form in vote_item_formset.forms %}
{{ form.as_p }}


{% endfor %}

Add another item

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

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.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,

The Problem now is that the When I try to get Image, the program looks for images at:

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

Which I think he takes from my 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?

This is my Vote/

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

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

Static Files

Static files are files that are shipped as part of your application.

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

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

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:

 - migrations
 - static
   - vote
     - images
       - foo.jpg

You need

Media Files

Media files are what django calls files that are uploaded by your application’s users

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 .

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

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

Files for the model will be uploaded to /home/foo/bar/proj/media/logos/ .

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. Set MEDIA_URL to /media/

  2. Configure to serve media files:

    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  3. Add '' to context_processors in TEMPLATES . This will activate {{ MEDIA_URL }} in your templates.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » The image is not downloaded to the media root using Django

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录