D
D
dt-wark2020-01-23 20:16:31
Django
dt-wark, 2020-01-23 20:16:31

Why is the image not loading via ImageField?

Recently started learning Django and stumbled upon a problem.
I have a blog post model that defines an og_image field that should hold a social media image. When creating a new post, I try to upload an image through the form. The form is submitted, but the image itself is not in the media/og_images folder , and the link in the template leads to the default value. How to be? There is a 3rd version of Dzhangi, I run it on a local server.
models.py

class Post(models.Model):
    title = models.CharField(max_length=150, db_index=True, verbose_name='Заголовок')
    slug = models.SlugField(max_length=150, blank=True, unique=True, verbose_name='УРЛ')
    body = MarkdownxField(blank=True, db_index=True, verbose_name='Текст')
    tags = models.ManyToManyField('Tag', blank=True, related_name='posts', verbose_name='Теги')
    og_image = models.ImageField(upload_to='og_images',
                                 default="og_images/default.jpg",
                                 verbose_name='Картинка для соцсетей')
    allow_comments = models.BooleanField(default=True, verbose_name='Открытые комментарии')
    date_pub = models.DateTimeField(auto_now_add=True)

settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

views.py
class PostCreate(LoginRequiredMixin, View):
    model_form = PostForm
    template = 'blog/post_create_form.html'
    raise_exception = True

    def get(self, request):
        form = self.model_form()
        return render(request, self.template, context={'form': form})

    def post(self, request):
        bound_form = self.model_form(request.POST)

        if bound_form.is_valid():
            new_obj = bound_form.save()
            return redirect(new_obj)
        return render(request, self.template, context={'form': bound_form})

forms.py
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'slug', 'body', 'tags', 'og_image', 'allow_comments']

        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'slug': forms.TextInput(attrs={'class': 'form-control'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
            'tags': forms.SelectMultiple(attrs={'class': 'form-control'}),
            'og_image': forms.FileInput(attrs={'class': 'form-control-file'}),
            'allow_comments': forms.CheckboxInput(attrs={'class': 'form-check-input position-static'})
        }

Post creation form
<form class="edit-form" action="{% url 'post_create_url' %}" method="post">
        <h1>Новый пост</h1>
        {% csrf_token %}
        {% for field in form %}
            <div class="form-group">
                {% if field.errors %}
                    <div class="alert alert-danger">
                        {{ field.errors }}
                    </div>
                {% endif %}
                {{ field.label }}
                {{ field }}
            </div>
        {% endfor %}
        <button type="submit" name="button" class="btn btn-primary">Создать</button>
    </form>
    {{ form.media }}

In the template, I want to substitute a link with a picture here
<meta property="og:image" content="{{ post.og_image.url }}">
<meta name="twitter:image:src" content="{{ post.og_image.url }}">

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-01-23
@dt-wark

Because you need to carefully read the docks and be able to google, the problem has been written a lot of times - enctype="multipart/form-data"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question