我需要编辑现有的表单并对数据库进行更改。为此,我使用基于UpdateView的类。当我使用“字段”时,一切都正常工作,但没有应用到表单的样式,因此我尝试使用“form_class”,当我单击提交按钮时,更改不会保存。请帮助我解决这个问题。
(url)
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('register/', views.register_page, name='register'),
path('login/', views.login_page, name='login'),
path('logout/', views.logout_user, name='logout'),
path('new_todo/', views.new_todo, name='new_todo'),
path('update_todo/<int:pk>', views.UpdateTodo.as_view(), name='update_todo'),
path('delete_todo/<int:pk>', views.delete_todo, name='delete_todo'),
]
(浏览次数)
class UpdateTodo(UpdateView):
model = Todos
template_name = 'todoapp/new_todo.html'
# fields = ['title', 'notes', 'date', 'deadline']
form_class = TodosForm
success_url = "/"
(型号)
from django.db import models
class Todos(models.Model):
title = models.CharField('Title', max_length=50)
notes = models.TextField('Note')
date = models.DateField('Date')
deadline = models.DateField('Deadline')
def __str__(self):
return f"Todo: {self.title}"
def get_absolute_url(self):
return f'/{self.id}'
(表格)
class TodosForm(ModelForm):
class Meta:
model = Todos
fields = ['title', 'notes', 'date', 'deadline']
widgets = {
'title': TextInput(attrs={
'class': 'form-control',
'placeholder': 'Title'
}),
'notes': Textarea(attrs={
'class': 'form-control',
'placeholder': 'Notes'
}),
'date': DateTimeInput(attrs={
'class': 'form-control',
'placeholder': 'Date'
}),
'deadline': DateTimeInput(attrs={
'class': 'form-control',
'placeholder': 'Deadline'
})
}
(HTML模板)
{% extends 'base.html' %}
{% block content %}
<form method="post" class="new-todo-form">
{% csrf_token %}
<h1 style="padding-bottom: 20px;">New todo</h1>
{{ form.title }}<br>
{{ form.notes }}<br>
{{ form.date }}<br>
{{ form.deadline }}<br>
<button class="create-btn" type="submit">Create</button>
<button class="clear-btn" type="reset">Clear</button>
</form>
{% endblock %}
1条答案
按热度按时间w8f9ii691#
您需要添加{{form.media}}以在模板中获取相关的css/js代码。
更改您的代码以包含它: