R
R
Rassul Nassyrov2020-09-21 07:38:37
Django
Rassul Nassyrov, 2020-09-21 07:38:37

Why is the user's photo not saved in the database and in static/images/?

There are no errors, the text is saved and img is not.

models.py:

class Post(models.Model):
    date = models.DateTimeField('Создан пост был:', default=timezone.now(), blank=True)
    text = models.TextField('Ваши новости:', max_length=1500)
    img = models.ImageField('Фотография:', upload_to = 'static/images', blank = True)

    def __str__(self):
        return self.username

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['text', 'img']


Views.py:
form = PostForm()
    if request.method == "POST":
        if request.user.is_authenticated == True:
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                post = form.save(commit = False)
                post.date = timezone.now()
                #post.img = request.POST['img']
                post.save()
                context = Post.objects.order_by('-date')[:5000]
                return redirect('/user/profile/news')
    return render(request, "fr/addpost.html", {'form': form})


MEDIA URL AND MEDIA ROOT everything works! When I create a post through the database, everything is saved!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
noremorse_ru, 2020-09-21
@nssr02

date = models.DateTimeField('Создан пост был:', default=timezone.now(), blank=True)

Here, instead of default, it is better to add auto_now_add=True, otherwise there is a risk of creating unnecessary migrations.
context = Post.objects.order_by('-date')[:5000]
This is out of place at all, your function returns a redirect, and no one will see this context, just wasted resources.
upload_to = 'static/images'
Here you specify the path relative to the root folder with media files, those. the full path in your case will be like ***/media/static/images
And finally, the answer to the question:
you need to add the enctype="multipart/form-data" attribute to the html form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question