我正在尝试将表单链接到我的模型,但是我在页面上始终遇到值错误。我没有看到任何语法错误,也不确定逻辑上的缺陷在哪里。
我已经尝试将meta更改为Meta,但没有任何效果。我已经在表中有一些实体,这可能是导致问题的原因吗?
# URLS________
path('posts/create_post/', views.create_post, name='create_post'),
#MODELS________
class Posts(models.Model):
priority = models.CharField(max_length=30)
client = models.CharField(max_length=30)
title = models.CharField(max_length=150)
assigned_to = models.ForeignKey(Users, on_delete=models.CASCADE)
exp_comp_time = models.FloatField(max_length=4)
percent_comp = models.FloatField(max_length=4)
post_date = models.CharField(max_length=20)
due_date = models.CharField(max_length=20)
latest_mod = models.CharField(max_length=20, null=True)
class PostsForm(forms.ModelForm):
class meta:
model = Posts
fields = '__all__'
#VIEWS________
def create_post(request):
""""Renders the create task page"""
if request.method == "GET":
form = PostsForm()
return render(request, 'app/form.html', {'form': form})
elif request.method == "POST":
form = PostsForm(request.POST)
form.save()
return HttpResponseRedirect('/posts')
#FORM.html________
{% extends "app/layout.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit Task</button>
</form>
{% endblock %}
帖子表格页面应该正在加载。
Traceback:
File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e,
request)
File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args,**callback_kwargs)
File "C:\DjangoWebProject1\DjangoWebProject1\app\views.py" in create_post
81. form = PostsForm()
File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\forms\models.py" in __init__
285. raise ValueError('ModelForm has no model class
specified.')
Exception Type: ValueError at /posts/create_post/
Exception Value: ModelForm has no model class specified.
答案 0 :(得分:1)
您需要大写Meta
:
from django.forms import ModelForm ### Double check your import statement
from django.db import models
...
class PostsForm(ModelForm): ### Notice that I have changed the inherited class name
class Meta: ### HERE
model = Posts
fields = '__all__'
我已经尝试过将meta更改为Meta
确保更改后保存文件。
我已经在表中有一些实体,这可能是导致问题的原因吗?
否。
最后要检查的是确保模型在匹配表单上方定义。