赋值错误之前引用的局部变量“ form”

时间:2019-05-31 18:40:30

标签: python django forms

我是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

我不仅要理解代码,还要理解

任何身体都可以帮助??? !!!

1 个答案:

答案 0 :(得分:2)

在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', {})