B
B
BigDB2021-05-15 17:41:12
Django
BigDB, 2021-05-15 17:41:12

Why is an image being loaded via a Django form?

Aloha everyone, when you try to upload a picture, nothing comes out through the form, but everything loads through the admin panel.

LINK to GITHUB: https://github.com/DarAnod-B/site.git

add_news.html

{% extends 'base.html' %}

{% block sidebar %}
{% include 'inc/_sidebar.html' %}
{% endblock %}

{% block content %}

<h1>Добавление новости</h1>

<form action="{% url 'add_news' %}" method="post">
   {% csrf_token %}
   {{ form.as_p }}
   <button type="submit" class="btn btn-primary btn-block">Добавить новость</button>
</form>
{% endblock %}

forms.py

from django import forms
from .models import Bd


class NewsForm(forms.ModelForm):
    class Meta:
        model = Bd
        # fields = '__all__'
        fields = ['name', 'content', 'category', 'is_published', 'photo']

admin.py

from django.contrib import admin
from .models import Bd, Category


class BdAdmin(admin.ModelAdmin):
    list_display = ('name', 'photo', 'category', 'is_published', 'created_at', 'updated_at')
    list_display_links = ('name', 'photo', 'category', 'is_published', 'created_at', 'updated_at')
    list_filter = ('updated_at', 'created_at')


class CategoryAdmin(admin.ModelAdmin):
    list_display = ('title',)
    list_display_links = ('title',)
    search_fields = ('title',)
    list_filter = ('title',)


# Register your models here.
admin.site.register(Bd, BdAdmin)
admin.site.register(Category, CategoryAdmin)

ulrs.py

from django.urls import path
from .views import *

urlpatterns = [
    path('', index, name='home'),
    # Создание переменной  category_id  с типом int, это число, которое передается через  url
    path('category/<int:category_id>/', get_category, name='category'),
    path('news/<int:news_id>/', view_news, name='view_news'),
    path('news/add-news/', add_news, name='add_news')
]

views.py

def add_news(request):
    if request.method == 'POST':
        form = NewsForm(request.POST)
        if form.is_valid():
            Bd.objects.create(**form.cleaned_data)
            return redirect('home')
    else:
        form = NewsForm()
    return render(request, 'bord/add_news.html', {'form': form})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-05-15
@BigDB

First of all,

<form action="{% url 'add_news' %}" method="post" enctype="multipart/form-data">

Secondly,
form = NewsForm(request.POST, request.FILES)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question