#python #html #django #sqlite
Вопрос:
Когда я нажимаю кнопку отправить, она перенаправляет меня на страницу создать модель (в данном случае создать запись) и фактически не создает новую модель, она не отображается на главной странице, на которой показаны все созданные модели.
Я попытался следовать этому руководству: Ссылка
Я чувствую, что делал в основном то же самое, что и он, и все же кнопка отправки формы не создает мой пост. Различия между нашими программами заключаются просто в названии и количестве полей в моей модели.
Форма регистрации пользователя работает, но это представление на основе функций, это представление на основе классов (должно по-прежнему работать, насколько я знаю), и между html для создания модели и html для регистрации пользователей практически нет различий.
Вот форма создания модели, record_form.html:
{% extends "catalog/base.html" %}
{% block content %}
<h1 class="text py-3 pt-4">Create a Record!</h1>
<style>
.text {
font-size: 40px;
font-weight: bold;
color: #060007;
}
</style>
<div class="shadow p-3 mb-3 bg-light rounded">
<form class="form" method="POST" action="/catalog/">
{% csrf_token %}
<p>
<label for="name">Name:</label>
{{ form.name }}
</p>
<p>
<label for="description">Description:</label>
</p>
<p>
{{ form.description }}
</p>
<p>
<label for="date_start">Date start:</label>
{{ form.date_start }}
</p>
<p>
<label for="date_end">Date end:</label>
{{ form.date_end }}
</p>
<p>
<label for="manufacturer">Manufacturer:</label>
{{ form.manufacturer }}
</select>
</p>
<p>
<label for="condition_rating">Condition rating (between 0 and 5):</label>
{{ form.condition_rating }}
</p>
<p>
<label for="condition_description">Condition description:</label>
</p>
<p>
{{ form.condition_description }}
</p>
<div>
<input type="submit" name="Create Record" value="Create Record" class="submit action-button">
</div>
</form>
<style>
.form {
color: #060007;
}
</style>
</div>
{% endblock content %}
Вот мои модели, которые программа использует в models.py:
class CommonInfo(models.Model):
id = models.AutoField(primary_key=True) # not necessary as django adds this to every model, but declared so that it is clear
creation_date = models.DateField(auto_now_add=True)
last_modified = models.DateField(auto_now=True)
name = models.CharField(max_length=100, help_text='Enter name')
description = models.TextField(blank=True, help_text='Enter description')
class Meta:
abstract = True
ordering = ['-last_modified', 'name'] # '-' reverses order, e.i. newest first
# ordering = ['name','-last_modified'] # '-' reverses order, e.i. newest first
class Catalog(CommonInfo):
def get_absolute_url(self):
return reverse('catalog-detail', args=[str(self.id)])
def __str__(self):
return f'{self.name}'
class Record(CommonInfo):
my_catalog = models.ForeignKey(Catalog, on_delete=models.CASCADE) # Many records to one Catalog. Deletes all records associated with deleted catalog.
date_start = models.DateField() # TODO - is date range for when aquired or creation?
date_end = models.DateField()
manufacturer = models.ForeignKey('Manufacturer', null=True, blank=True, on_delete=SET_NULL)
condition_rating = DecimalField(
help_text='Enter condition rating from 0 to 5',
default=0,
decimal_places=2,
max_digits=3,
validators=[MinValueValidator(Decimal('0')), MaxValueValidator(Decimal('5'))]
)
condition_description = models.TextField(blank=True, help_text='Enter condition description')
def get_absolute_url(self):
return reverse('record-detail', args=[str(self.id)])
def __str__(self):
return f'{self.name} ({self.my_catalog})'
Вот класс CreateView в views.py:
class RecordCreateView(CreateView):
model = Record
fields = ['name', 'description', 'date_start', 'date_end', 'manufacturer', 'condition_rating', 'condition_description'] #Owner/nation/continent not able to be done, since provenance is not linked to Record
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Вот urls.py:
from django.urls import path
from .views import RecordDetailView, RecordCreateView
from . import views
from django.views.generic import RedirectView
urlpatterns = [
path('about/', views.about, name='catalog-about'),
path('home/', views.home, name='catalog-home'),
path('catalog/', views.catalogList, name='catalog-list'),
path('', RedirectView.as_view(url='about/', permanent=True)),
path('login/', views.loginPage, name='catalog-login'),
path('logout/', views.logoutUser, name='catalog-logout'),
path('register/', views.register, name='catalog-register'),
path('record/<int:pk>/', RecordDetailView.as_view(), name='record-detail'),
path('record/new/', RecordCreateView.as_view(), name='record-create'),
]
Комментарии:
1. вы тоже можете поделиться
urls.py
файлом.2. @Shanks Я обновил сообщение, чтобы включить urls.py, спасибо за помощь!
Ответ №1:
я не вижу поля «имя» в записанной таблице, и вы не даете каталог в своем просмотре создания записей.
Комментарии:
1. «имя» находится в классе CommonInfo, который задается классу записей в качестве параметра (насколько мне известно). Я не совсем понимаю, что вы подразумеваете под «вы не даете каталог…», я должен? Каталог не должен быть необходим для создания записи.