【问题标题】:local variable 'form' referenced before assignment error赋值错误之前引用的局部变量“表单”
【发布时间】:2019-05-31 18:40:30
【问题描述】:

我是 django 2.x 的新手 .. 尝试创建博客项目作为对我的培训 我有问题错误 /create_post/ 处的 UnboundLocalError 赋值前引用的局部变量“form”

这个错误会让我生气

这是我的views.py文件

# views.py
def add_post (request):
    if request.method=='POST':
        form = postform(request.POST)
        if form.is_valid():
            form.save()
        else:
            form=postform()
    context = {
        'form': form
    }
    return render(request, 'create_post.html', {})

这是我的 models.py 文件

# models.py
from django.db import models
from django.utils.timezone import now

# Create your models here.

class post (models.Model):
    Post_Title = models.CharField (max_length=200)
    Post_Image = models.ImageField(upload_to='post/statics/img/')
    Post_Text = models.TextField()
    Post_Date = models.DateTimeField(default=now, editable=False)


    def __str__(self):
        return self.Post_Title

这是我的 create_post.html 文件

# create_post.html
<form method="post">
{% csrf_token %}
    {{ form }}
    <button type="submit"}>save new post</button>
</form>

这是我的 forms.py 文件

# forms.py
from django import forms
from .models import *

class postform (forms.ModelForm):
    class Meta:
        model = post
        fields = ['Post_Title', 'Post_Image', 'Post_Text']

这是我得到的错误

UnboundLocalError at /create_post/
local variable 'form' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/create_post/
Django Version: 2.2.1
Exception Type: UnboundLocalError
Exception Value:    
local variable 'form' referenced before assignment
Exception Location: D:\PEPSI\PycharmProjects\bloggersystem\post\views.py in add_post, line 29
Python Executable:  C:\Users\Mohamed Abaas\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.3
Python Path:    
['D:\\PEPSI\\PycharmProjects\\bloggersystem',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\Mohamed Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\Mohamed Abaas\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time:    Fri, 31 May 2019 18:28:50 +0000

我想了解的不仅仅是修复代码

任何机构都可以帮忙吗???!!!

【问题讨论】:

  • 想想如果if request.method=='POST':为假会发生什么,form的值在你尝试使用它之前永远不会被赋值,即引用它。
  • 是的,谢谢,发现错误.. 在if request.method == 'POST': 之前添加form = postform() 以识别为引用变量.. 但它没有保存到数据库.. 我现在不知道为什么? ??

标签: python django forms


【解决方案1】:

在 GET 请求的情况下,您没有定义 form 变量。这是因为您将else 缩进了太多:

def add_post (request):
    if request.method=='POST':
        form = postform(request.POST)
        if form.is_valid():
            form.save()
    else:
        form=postform()
    context = {
        'form': form
    }
    return render(request, 'create_post.html', {})

【讨论】:

  • 是的,谢谢,发现错误.. 在if request.method == 'POST': 之前添加form = postform() 以标识为引用变量.. 但它没有保存到数据库.. 我现在不知道为什么? ??
  • @MohamedAbbase:你需要用request.POST创建一个postform(..),如果你没有在request.method == 'POST'之后创建一个,那么你填写了一个空的表格,因此form.is_valid()会是假的。
猜你喜欢
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
相关资源
最近更新 更多