Answer the question
In order to leave comments, you need to log in
How to use an ImageField in Django?
Hello.
Task: upload a photo through the junga admin panel and upload it to the site template.
What I do: # The view contains a couple of parts from another model, but in general this does not interfere
1) Media roots and statics
STATIC_URL = '/static/'
MEDIA_ROOT = ''
MEDIA_URL = ''
class Step(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=200)
annotation = models.TextField()
main_text = models.TextField()
main_photo = models.ImageField(upload_to='bakot/static/bakot/imagination', height_field=None, width_field=None, max_length=100)
true_question = models.TextField()
true_answer = models.TextField()
def step1(request):
stepfields = Step.objects.get()
navigators = Navigation_bar.objects.all()
context = {
"stepfieldst" : stepfields,
"navigators" : navigators,
}
return render_to_response('bakot/step1.html', context)
<div class="start-imagination">
<img src="{% block photocontent %}{% endblock %}">
</div> <!--Изображение -->
---
{% block photocontent %}{{ stepfieldst.main_photo.url }}{% endblock %}
Answer the question
In order to leave comments, you need to log in
Is the path to the statics specified in settings.py?
Usually this
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step.objects.all()
otherwise it is not clear how you select a specific object {% for img in stepfieldst %}
<img src="{{ img.main_photo.url }}" >
{% endfor %}
I found my own problem, which was fixed, but for the new version of django, it no longer wants to work:
stackoverflow.com/questions/5517950/django-media-u...
i.e. determined media roots, added an upload to the model, uploaded a photo = received a message that the image is not found at this url.
the code that is given there as a remedy does not work on version 1.9 on the local machine.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question