Django Uploaded images not displayed in development

徘徊边缘 提交于 2021-02-20 00:40:26

问题


I have defined a model with a 'pic' image field:

class Photo(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    teaser = models.TextField('teaser', blank=True)
    pic = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/default.jpg')
    created=models.DateTimeField(default=datetime.datetime.now)
    pub_date=models.DateTimeField(default=datetime.datetime.now)
    categories = models.ManyToManyField(Category, blank=True)
    likes = models.IntegerField(default=0)
    dislikes = models.IntegerField(default=0)
    visits = models.IntegerField(default=0)
    slug = models.CharField(max_length=100,  unique=True, blank=True)

And here is the upload form:

class PhotoForm(forms.ModelForm):       

    class Meta:
            model= Photo
            fields = ( 'title', 'pic','body', 'categories') 

Wich post to this view:

@staff_member_required
def add_photo(request):
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.info(request, "photo was added") 
            return render(request, 'home.html')
        else:
            messages.info(request, 'form not valid')
            return render(request, 'home.html')

    if request.method == 'GET':
        form = PhotoForm()
        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render(request, 'photo/add_photo.html', args)  

The problem is that while photo objects are being saved and the file uploaded but the images are not displayed.

  <div class="photo_body"><img src="pic_folder/someimage.jpg" ></div>

I also set

MEDIA_ROOT = '/path/to/my_project/pic_folder'

and run manage.py collectstatic, but they did not solve the problem.

I really got confused about this. So appreciate your hints.


回答1:


First of all make a folder called media in your project's directory.

Django will store all your uploaded images inside media/pic_folder/ automatically.

In your settings.py file, add this:

MEDIA_URL = '/media/'

MEDIA_ROOT = '/path_to/media/' # write the path to the media folder you just created.

In your urls.py file, add the following lines at the top:

from django.conf import settings
from django.conf.urls.static import static

and add the following line at the end:

+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

something like below:

 urlpatterns = patterns('',

    # Your urls here 

) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And, finally, in your templates:

<img src="{{MEDIA_URL}}pic_folder/someimage.jpg" />


来源:https://stackoverflow.com/questions/22417146/django-uploaded-images-not-displayed-in-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!