在Django中将模型类视为局部变量

时间:2019-02-14 04:55:22

标签: python django

当我尝试访问表单进行编辑时,会发生此错误

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

模型是个人资料

models.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

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

StackTrace Error Stacktrace

1 个答案:

答案 0 :(得分:1)

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