我一直在遵循一个教程,但是做一些小的修改,不允许我将表单保存在DB中。你知道吗
但是,我知道模型是正确的,因为我可以从shell中保存对象。你知道吗
我没有得到任何错误,提交后,我被重定向到主页。你知道吗
但是如果我提交表单然后转到管理员,我会看到注册的模型,但是在中没有记录(通过shell保存的记录除外)。怎么回事?你知道吗
型号.py:
class TamaniosCantidades(models.Model):
TAMANIOS = (('498', '2" x 2"',), ('499', '3" x 3"',),
('500', '4" x 4"',), ('501', '5" x 5"',))
CANTIDADES = (('100', '50',), ('100', '100',),
('150', '150',))
tamanios = models.CharField(max_length=10, choices=TAMANIOS)
cantidades = models.CharField(max_length=10, choices=CANTIDADES)
表单.py:
from django import forms
from .models import TamaniosCantidades
class TamaniosCantidadesForm(forms.ModelForm):
class Meta:
model = TamaniosCantidades
fields = ['tamanios', 'cantidades']
你知道吗网址.py地址:
from . import views
from django.urls import path, include
urlpatterns = [
path('', views.index),
path('productos/', views.productos),
path('post_url/', views.post_treasure, name='post_treasure'),
path('post_url_tamanioscantidades/', views.post_tamanioscantidades, name='post_tamanioscantidades'),
]
视图.py:
def index(request):
treasures = Treasure.objects.all()
form = TreasureForm()
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/index.html', {'treasures': treasures,
'form': form,
'tamanioscantidades_form': tamanioscantidades_form})
def post_tamanioscantidades(request):
tamanioscantidades_form = TamaniosCantidadesForm()
if tamanioscantidades_form.is_valid():
tamanioscantidades_form.save(commit = True)
return HttpResponseRedirect('/')
html:
<div class="row">
<form action="post_url_tamanioscantidades/" method="post">
{% csrf_token %}
{{ tamanioscantidades_form.as_p }}
<input type="submit" value="Submit"/>
</form>
</div>
这个方法创建了一个空的
TamaniosCantidadesForm
,这是无效的,所以它永远不会被保存。你知道吗您可能希望执行
TamaniosCantidadesForm(request.POST)
之类的操作,用提交的数据实际填充表单。你知道吗相关问题 更多 >
编程相关推荐