python - 模型类在 Django 中被视为局部变量
问题描述
当我尝试访问表单进行编辑时,出现此错误
local variable 'Profile' referenced before assignment
视图.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect,get_object_or_404
from home.models import UserCreateForm,Profile
from home.forms import ProfileCreateForm
# Create your views here.
def update(request,pk):
profiles=Profile.objects.all()
print(profiles)
if request.method == 'POST':
form = ProfileCreateForm(request.POST,request.FILES)
if form.is_valid():
Profile = form.save()
return redirect('home')
else:
form = ProfileCreateForm(instance=profile_instance)
return render(request, 'registration/profile.html', {'form': form})
模型是 Profile
模型.py
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django import forms
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female')
)
class Profile(models.Model):
firstName = models.CharField(max_length=128)
lastName = models.CharField(max_length=128)
address = models.CharField(max_length=250)
dob = models.DateTimeField()
profilePic = models.ImageField(blank=True)
gender=models.CharField(max_length=2, choices=GENDER_CHOICES)
def __str__(self):
return self.firstName
添加新表单效果很好,但从数据库访问保存的表单会导致错误
解决方案
您已经设置了表单变量,即导入Profile = form.save()
模型变量,除了将其指向该特定模型之外,您无法真正使用它 Profile
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect,get_object_or_404
from home.models import UserCreateForm,Profile
from home.forms import ProfileCreateForm
# Create your views here.
def update(request,pk):
profiles=Profile.objects.all()
profile_instance = get_object_or_404(Profile, id=pk) #<-- you must already have this
print(profiles)
if request.method == 'POST':
form = ProfileCreateForm(request.POST,request.FILES, instance=profile_instance)
if form.is_valid():
abc = form.save() # <-- Changes
abc.save() # <-- Changes
return redirect('home')
else:
form = ProfileCreateForm(instance=profile_instance)
return render(request, 'registration/profile.html', {'form': form})
推荐阅读
- arrays - Qsort 结构体数组
- django - Django BinaryField 默认值
- python - 如何在 python 3 中为模块定义 `__path__` 属性?
- c - 从缓冲区发送消息时,缓冲区会自动清除吗?
- python - 最后一个块是什么意思?什么是unittest.main()?
- javascript - 获取应用程序错误代码 503 favicon angular
- python - 有没有什么办法可以得到这个网站上出现的(网络抓取)每日数字?需要刮一年
- python - OpenCV 关键点匹配器匹配 Python 中证书模板和图像的错误区域
- javascript - 如何在Javascript中的视频中显示下载按钮
- swift - 更新我的 pods 文件后构建运行问题