I’m new to Django. And I’m faced with the problem of saving data from the form to the database. I was writing code in PyCharm. The main problem is that the data is not saved in the database. There are no errors, no warnings, NOTHING. Everything works except saving. I will be very grateful for your help!
Here is the code:
views.py:
`from django.shortcuts import render, redirect
from .models import Articles
from .forms import ArticlesForm
def news_home(request):
news = Articles.objects.order_by('title')
return render(request, 'news/news_home.html', {'news': news})
def create(request):
error = ''
if request.method == 'POST':
form = ArticlesForm(request.POST)
if form.is_valid():
article = form.save()
return redirect('news_home')
else:
error = 'Unfortunately, the form was not filled out correctly.'
form = ArticlesForm()
data = {
'form': form,
'error': error
}
return render(request, 'news/create.html', data)`
models.py:
`from django.db import models
class Articles(models.Model):
title = models.CharField('name', max_length=50)
anons = models.CharField('anons', max_length=250)
full_text = models.TextField('article')
date = models.DateTimeField('Date of publication')
def __str__(self):
return self.title
class Meta:
verbose_name = 'news'
verbose_name_plural = 'news'`
forms.py:
`from .models import Articles
from django.forms import ModelForm, TextInput, DateTimeInput, Textarea
class ArticlesForm(ModelForm):
class Meta:
model = Articles
fields = ['title', 'anons', 'full_text', 'date']
widgets = {
"title": TextInput(attrs={
'class': 'form-control',
'placeholder': 'the name of the record'
}),
"anons": TextInput(attrs={
'class': 'form-control',
'placeholder': 'Announcement of the recording'
}),
"full_text": Textarea(attrs={
'class': 'form-control',
'placeholder': 'write about something'
}),
"date": DateTimeInput(attrs={
'class': 'form-control',
'placeholder': 'Date of publication'
}),
}`
urls.py:
`from django.urls import path
from . import views
urlpatterns = [
path('', views.news_home, name='news'),
path('сreate', views.create, name='create'),
]`
I’ve tried a lot of YouTube videos and articles from the Internet, but all in vain.
UPD: I also looked at the documentation.
user24993423 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.