首页 > 解决方案 > 模型类在 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

添加新表单效果很好,但从数据库访问保存的表单会导致错误

堆栈跟踪 错误堆栈跟踪

标签: pythondjango

解决方案


您已经设置了表单变量,即导入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})

推荐阅读