Answer the question
In order to leave comments, you need to log in
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 %}
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']
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)
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')
]
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
First of all,
<form action="{% url 'add_news' %}" method="post" enctype="multipart/form-data">
form = NewsForm(request.POST, request.FILES)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question