我正在使用CreateView在前端上创建条目,然后保存到数据库/后端。但是每次我单击“保存”或提交表单时,都会按预期成功重定向,但不会保存到后端。
我尝试将success_url添加到我的views.py中,也将get_absolute_url(self)添加到我的models.py中,但仍然无法正常工作。
Views.py
class Dashboard (LoginRequiredMixin, CreateView):
model = PostedJob
template_name ='accounts/dashboard.html'
fields = ['firstname', 'lastname', 'job_title', 'email', 'budget',
'country', 'state', 'address', 'job_category',
'description', 'photo']
success_message = "Redirect successfully created!"
login_url= 'login'
models.py
Type = (
('building inspection', 'Building Inspection'),
('agriculture', 'Agriculture'),
('construction', 'Construction'),
('maintenance & training', 'Maintenance & Training'),
('surveying & mapping', 'Surveying & Mapping'),
('events coverage', 'Events Coverage'),
)
class PostedJob(models.Model):
firstname=models.CharField(max_length=200)
lastname=models.CharField(max_length =150)
email=models.EmailField(max_length =150)
job_title= models.CharField(max_length =150)
budget=models.PositiveIntegerField()
country=models.CharField(max_length = 150)
state=models.CharField(max_length = 150)
address=models.CharField(max_length = 150)
job_category=models.CharField(choices=Type, default ='agriculture',
max_length=50 )
photo= models.ImageField(upload_to='/%Y/%m/%d/', blank=False,
null=False)
description=models.TextField(max_length = 1500)
post_date=models.DateTimeField(default = datetime.now, blank=True)
publish=models.BooleanField(default =False)
def __str__(self):
return self.job_title
def get_absolute_url(self):
return reverse('home')
urls.py
urlpatterns =[
path('accounts/dashboard', Dashboard.as_view(), name='dashboard'),
]
index.html
<form action="" method="post">
{% csrf_token %}
{{form.as_p}}
<div>
<input type="submit" id="submit" value="Submit" class="btn waves-
effect waves-grey green">
</div>
</form>
该表单也不会显示任何错误消息。我真的很感谢您的帮助。谢谢。
答案 0 :(得分:1)
The form shows no errors but using the following SQL queries in Python prompt
revealed the error :
from django.db import connection
cursor = connection.cursor()
error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are
not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings.
** Updated**
但是,环境变量并不能真正解决这个问题。问题实际上出在表单本身。表单上有一个图像字段,默认情况下是必填字段。表单即使单击成功重定向,也没有保存到数据库。原因是由于所有字段都是必填字段,因此图像将在每次保存或提交操作时返回空白字段,从而导致表单始终不保存在每个提交操作中。
Solution: Simply add enctype="multipart/form-data to your form.
<form action="" method="POST" enctype="multipart/form-data">