python Django 形态:无法访问未与值关联的局部变量“form”

nfg76nw0  于 2022-11-27  发布在  Python
关注(0)|答案(2)|浏览(828)

**条件:**我有一个模型,在数据库中创建了一个空表,我正在尝试创建一个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
zvokhttg

zvokhttg1#

在这里,您为POST请求传递了form = RouteForm(request.POST)对象,您需要为GET请求传递该对象,因此,当使用GET请求调用def getAbout(request)函数时,将其呈现如下...

def getAbout(request):
  form=RouteForm() # <---- called at GET request
  if request.method == 'POST':
    form = RouteForm(request.POST) # <---- called at POST request
    if form.is_valid():
      form.save()
      return redirect("/")
  return render(request, 'routes_form/form_page.html', {'form': form})
fcg9iug3

fcg9iug32#

这是因为您还没有为GET方法定义form,所以:

def getAbout(request):
    if request.method == 'POST':
        form = RouteForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('some_view_name_to_redirect')
    else:
        form=RouteForm()
    return render(request, 'routes_form/form_page.html', {'form': form})

**注意:**Django中的模型是以单数形式书写的,因为Django本身添加了s作为后缀,所以最好将模型命名为CityRoute

相关问题