gpt4 book ai didi

python - 模型类在 django 中被视为局部变量

转载 作者:行者123 更新时间:2023-12-01 08:20:25 26 4
gpt4 key购买 nike

当我尝试访问表单进行编辑时,出现此错误

local variable 'Profile' referenced before assignment

views.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})

模型是配置文件

模型.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

添加新表单工作正常,但从数据库访问保存的表单会导致错误

堆栈跟踪 Error Stacktrace

最佳答案

您已将表单变量(即 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})

关于python - 模型类在 django 中被视为局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54683418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com