C
C
Cyber_bober2016-03-12 11:47:49
Django
Cyber_bober, 2016-03-12 11:47:49

How to fix adding images via form?

Hello, I have two forms - "Create" and "Edit". In the create form, the image is attached, but not in the edit form, while the framework does not give any errors.
Please tell me where to dig? Maybe there are some subtleties in working with images that I don't know about?
Create form listing

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            farm = form.save(commit=False)
            farm.owner = request.user
            farm.published_date = timezone.now()
            farm.save()
            return redirect('blog.views.post_detail', id=post.id)
        else:
            post = PostForm()
            return render(request, 'posts/post_edit.html', {'form': form})

Edit form listing
def post_edit_main(request, id):
    post = get_object_or_404(Post, id=id)
    if request.method == "POST":
        form = PostEditMain(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.owner = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post.views.own_farm_detail', id=farm.id)
    else:
        form = PostEditMain(instance=farm)
    return render(request, 'posts/post_edit_main.html', {'form': form})

Model
class Post(models.Model):
owner = models.ForeignKey('auth.User')
title = models.CharField(max_length=100,verbose_name=u'Название')
image = models.ImageField(upload_to="{{ MEDIA_ROOT }}",
verbose_name=u'Заглавное фото', help_text='Большое', blank=True, null=True)

Sample
<form method="POST" class="post-form">{% csrf_token %}
            {{ form|bootstrap}}
            <button type="submit" class="save send">Save</button>
        </form>

I was sinning on CHMOD, but when creating an image, it is attached, but when editing it is not (

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-03-12
@Cyber_bober


  1. post = get_object_or_404(Post, id=id)
    but
    form = PostEditMain(request.POST, instance= farm )
    In the template, add enctype="multipart/form-data" to the form declaration
    request.FILES add to the form parameters after all.
    upload_to is equal to MEDIA_ROOT by default, can be omitted. And the upload_to="{{ MEDIA_ROOT }}" construct is a guaranteed problem.

D
Dmitry Voronkov, 2016-03-12
@DmitryVoronkov

PostEditMain(request.POST, request.FILES, instance=farm)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question