Answer the question
In order to leave comments, you need to log in
I can't upload images from a form to the site in DJANGO, what should I do?
Help, good people... All articles on the Internet on this topic do not help (either some pieces of information are given, or outdated codes ...), but I'm just learning and I can't figure out how to make the user, having written a post, he could attach a photo to the post through the form, send it to my site, and have this photo displayed along with his post. The form accepts text and photos. The text is displayed on the site. No photo. Not a hint at all. Although it appears that the form is submitting a photo, in a folder on my computer I can see the photos submitted by the form appear. But the site does not display them.
Despite the fact that simple pictures from the template (which are in the template through {% load static %}
) are perfectly loaded, they are visible on the site ... There is some kind of trouble with the form.
Django 2.0
models.py version:
class Descriptions(models.Model):
city=models.ForeignKey(Cities, on_delete=models.CASCADE)
description=models.TextField()
date_added=models.DateTimeField(auto_now_add=True)
owner=models.ForeignKey(User, on_delete=models.DO_NOTHING)
image=models.ImageField(upload_to='images/', blank=True)
def __str__(self):
return self.description[:100]+'...'
@login_required
def new_description(request, countries_id, cities_id):
country=Countries.objects.get(id=countries_id)
city_name=Cities.objects.get(id=cities_id)
if request.method != 'POST':
form=DescriptionsForm()
else:
form=DescriptionsForm(request.POST, request.FILES)
if form.is_valid():
new_description=form.save(commit=False)
new_description.city=city_name
new_description.owner=request.user
new_description.save()
return HttpResponseRedirect(reverse('countries:descr', args=[country.id, city_name.id]))
context={'country': country, 'city': city_name, 'form': form}
return render(request, 'countries/new_description.html', context)
class DescriptionsForm(forms.ModelForm):
class Meta:
model = Descriptions
fields = ['description', 'image']
labels = {'text': 'add data here'}
widgets = {'description': forms.Textarea(attrs={'cols': 100})}
<form action="{% url 'countries:new_descr' country.id city.id %}" method="post" enctype="multipart/form-data">
{{ form }}
</form>
{% for description in descriptions %}
{{ description.description|linebreaks }}
{% if description.image %}
<img scr="{{description.image.url}}">
{% endif %}
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('', include('countries.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
STATIC_URL = '/static/'
MEDIA_URL = 'static/media/'
STATIC_ROOT=os.path.join(BASE_DIR, 'static')
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question