A
A
alexkomp2019-07-19 22:55:27
Django
alexkomp, 2019-07-19 22:55:27

Why is the image not changing through the form on the site on Django?

Why is the image not changing through the form on the site on Django?
When you add a post, the image is added, but when you change it, it doesn't.
created model
model.py

class Ware(models.Model):
    title = models.CharField(max_length = 130)
    slug = models.SlugField()
    description = models.TextField()
    prise = models.DecimalField(max_digits = 7, decimal_places=0)
    available = models.BooleanField(default=True)
    image = models.ImageField(upload_to='images/', blank=True)
    
    def __str__(self):
        return self.title

moved to
forms.py
class CommentsForm(forms.ModelForm):
    class Meta:
        model = Ware
        fields = ['title', 'slug', 'prise', 'image', 'description', 'available']

views.py
def testimage_add(request):
    if request.method != 'POST':
        form=CommentsForm()
    else:
        form=CommentsForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            form.save()
            return HttpResponseRedirect("/")
    context={'form': form}
    return render(request, 'ware.html', context)


#функция изменения поста
def post_edit(request, pk):
    post = get_object_or_404(Ware, pk=pk)
    if request.method == "POST":
        form = CommentsForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            form.save()
            return HttpResponseRedirect("/")
    else:
        form = CommentsForm(instance=post)
    return render(request, 'ware.html', {'form': form})

urls.py
from django.conf.urls import url 
from django.views.generic import ListView, DetailView
from index.models import Ware
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url('shop/(?P<pk>[0-9]+)/', DetailView.as_view(model = Ware, template_name = 'detail_ware.html')),
    url('post/(?P<pk>[0-9]+)/edit/', views.post_edit, name='post_edit'),
    url(r'^$', ListView.as_view(queryset=Ware.objects.all().order_by('-title')[:20],
    template_name = 'index.html')),

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-07-20
@alexkomp

well, there are no files right there
form = CommentsForm(request.POST, instance=post)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question