**条件:**我有一个模型,在数据库中创建了一个空表,我正在尝试创建一个html表单,该表单将填充表中相应列的字段。下面是我的应用程序的外观:
模型.py
from django.db import models
class Cities(models.Model):
city = models.CharField(max_length=100)
def __str__(self):
return self.state
class Routes(models.Model):
route_name = models.CharField(max_length=50, default='Route')
lvl = models.IntegerField(default=0)
about = models.TextField(max_length=1500)
total_distance = models.IntegerField(default=0)
city = models.ForeignKey(Cities, on_delete=models.CASCADE)
表单.py
from django.forms import ModelForm
from .models import Routes
class RouteForm(ModelForm):
class Meta:
model = Routes
fields = '__all__'
查看次数.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from routes_form.forms import RouteForm
def getAbout(request):
if request.method == 'POST':
form = RouteForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'routes_form/form_page.html', {'form': form})
表单.html
<form method="post">
{% csrf_token %}
<legend>
<h2>About</h2>
</legend>
{{ form }}
<input type="text" placeholder="Write more about the route: about waypoints, points of interest and warnings.">
<input type="submit" value="Send route">
</form>
我已经试着按照Django Forms文档中的指示做了所有的事情,但是仍然有一些错误。甚至在启动服务器的那一刻,它也写了一个错误:
cannot access local variable 'form' where it is not associated with a value
2条答案
按热度按时间zvokhttg1#
在这里,您为
POST
请求传递了form = RouteForm(request.POST)
对象,您需要为GET
请求传递该对象,因此,当使用GET请求调用defgetAbout(request)
函数时,将其呈现如下...fcg9iug32#
这是因为您还没有为
GET
方法定义form
,所以:**注意:**Django中的模型是以单数形式书写的,因为Django本身添加了
s
作为后缀,所以最好将模型命名为City
和Route
。