H
H
howuu2018-08-16 23:44:09
Django
howuu, 2018-08-16 23:44:09

Image upload via Django form?

Worked with the documentation, but did not solve the problem.
You need to send a picture models to the blog post

from django.db import models
from django.utils import timezone


class Post(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField()

    image = models.ImageField(null=True, blank=True, upload_to='blog/images/')

    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

views:
def post_edit(request, pk):

    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.published_date = timezone.now()
            post.save()
            return redirect('/', pk=post.pk)
    else:
        form = PostForm(request.POST, request.FILES)
    return render(request, 'blog/post_edit.html', {'form': form})

in urls and project and application blog added
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

HTML
<h1>Новий пост</h1>

  <div class="col-md-12 col-lg-8 main-content">
            <form method="POST">{% csrf_token %}
                  <div class="row">
                    <div class="col-md-4 form-group">
                      
                      {% render_field form.title type="text" id="name" class="form-control " title="Заголовок" %}
                      
                      </div>
                    
                  </div>





                  <div class="row">
                    <div class="col-md-12 form-group">
                      {% render_field form.text name="message" id="message" class="form-control " %}
                       
                  </div>
                  </div>

                  <div class="row">
                    <div class="col-md-12 form-group">

                  {% render_field form.image %}

                  </div>
                  </div>

                  <div class="row">
                    <div class="col-md-6 form-group">
                      <input type="submit" value="Опубликовать" class="btn btn-primary">
                    </div>
                  </div>
                </form>
</div>

What is the problem, why the image is not loading?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ranwise, 2018-08-17
@Ranwise

'blog/images/'does such a folder exist? still need to be specified in the settings MEDIA_ROOT, MEDIA_URL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question