djang中作为局部变量处理的模型类

2024-09-26 17:47:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

模型是剖面图

你知道吗型号.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


Tags: djangofromimportform表单homereturnmodels
1条回答
网友
1楼 · 发布于 2024-09-26 17:47:13

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

相关问题 更多 >

    热门问题