项目场景:
django2初次使用modelforms
问题描述
ModuleNotFoundError: No module named 'models'
原因分析:
直接在app内views里面创建了modelform类 与app的models冲突
解决方案:
app下新建一个myforms.py, 在这里创建modelform类,然后在view.py引入
myform.py
from django.forms import ModelForm
from django.forms import widgets
from app01.models import UserInfo
from django.core.exceptions import ValidationError
class UserInfoModelForm(ModelForm):
class Meta:
model = UserInfo
fields = ['name', 'password', 'age', 'phont']
views.py
from app01.myforms import UserInfoModelForm
def add_user_model(request):
form = UserInfoModelForm()
return render(request, "user_add_modelform.html", {"form": form})
user_add_modelform.html
<form method="POST">
{% csrf_token %}
{{ form.name }}
{{ form.age }}
</form>