我正在一个用户最初注册的项目中,然后填写关于其个人资料的两个单独的信息页面(在PII和finalPII页面上)。无论出于何种原因,我都无法将该信息正确地保存到我的Profile模型中,并且总是遇到与用户ID有关的两个错误之一:当我包含行profile.user = request.user
时,UNIQUE约束失败或当我摆脱这一行时,NOT NULL约束失败错误。我不确定中间位置在哪里,我非常感谢您提供的任何帮助或建议。
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, PIIForm, FinalPIIForm
from .models import Profile
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
def PII(request):
if request.method == 'POST':
form = PIIForm(request.POST,)
if form.is_valid():
#form.user = Profile.objects.get(user=request.user)
#
profile = form.save(False)
profile.user = request.user
profile.save()
#
#form.save()
return redirect('FinalPII')
else:
form = PIIForm(request.POST)
return render(request, 'users/pii.html', {'form':form})
def FinalPII(request):
if request.method == 'POST':
form = FinalPIIForm(request.POST)
if form.is_valid():
profile = form.save(False)
profile.user = request.user
profile.save()
return redirect('/')
else:
form = FinalPIIForm(request.POST)
return render(request, 'users/finalpii.html', {'form':form})
models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from django.db.models.signals import post_save
from django.dispatch import receiver
from PIL import Image
import birthday
class Profile(models.Model):
GENS = (('m','Male'),('f','Female'),('o','Not Represented Above'))
RACES = (('ai','American Indian or Alaska Native'),('as','Asian'),('bl','Black or African American'),('hi','Hispanic or Latino'),('ha','Native Hawaiian or Other Pacific Islander'),('wh','White'))
ETHNICITIES = (('n','Not Hispanic or Latino'),('h','Hispanic or Latino'))
INCBRACKET = (('a','$0 - $10,000'),('b','$10,001 - $40,000'),('c','$40,001 - $80,000'),('d','$80,001 - $150,000'),('e','$150,001 - $250,000'),('e','$250,001 - $500,000'),('e','$500,000+'))
EDUCATION = (('NE','No Formal Education'),('HS','High School Diploma'),('AD','Associate Degree'),('BD','Bachelor\'s Degree'),('MD','Masters\'s Degree'),('DD','Doctorate'))
EMPLOYMENT = (('e','Currently Employed'),('u','Currently Unemployed'))
STATES = [('AL', 'Alabama'),('AK', 'Alaska'),('AZ', 'Arizona'),('AR', 'Arkansas'),('CA', 'California'),('CO', 'Colorado'),('CT', 'Connecticut'),('DE', 'Delaware'),('FL', 'Florida'),
('GA', 'Georgia'),('HI', 'Hawaii'),('ID', 'Idaho'),('IL', 'Illinois'),('IA', 'Iowa'),('KS', 'Kansas'),('KY', 'Kentucky'),('LA', 'Louisiana'),('ME', 'Maine'),
('MD', 'Maryland'),('MA', 'Massachusetts'),('MI', 'Michigan'),('MN', 'Minnesota'),('MS', 'Mississippi'),('MO', 'Missouri'),('MT', 'Montana'),('NE', 'Nebraska'),
('NV', 'Nevada'),('NH', 'New Hampshire'),('NJ', 'New Jersey'),('NM', 'New Mexico'),('NY', 'New York'),('NC', 'North Carolina'),('ND', 'North Dakota'),('OH', 'Ohio'),
('OK', 'Oklahoma'),('OR', 'Oregon'),('PA', 'Pennsylvania'),('RI', 'Rhode Island'),('SC', 'South Carolina'),('SD', 'South Dakota'),('TN', 'Tennessee'),('TX', 'Texas'),
('UT', 'Utah'),('VT', 'Vermont'),('VA', 'Virginia'),('WA', 'Washington'),('WV', 'West Virginia'),('WI', 'Wisconsin'),('WY', 'Wyoming')
]
user = models.OneToOneField(User, on_delete=models.CASCADE, null=False, blank=True, default = '')
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
gender = models.CharField(max_length = 1, choices = GENS, default = '')
birthday = models.DateField(default = '1900-01-01')
race = models.CharField(max_length = 2, choices = RACES, default = 'x')
ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default = 'x')
income = models.CharField(max_length = 1, choices = INCBRACKET, default = 'x')
education = models.CharField(max_length = 2, choices = EDUCATION, default = 'x')
employment = models.CharField(max_length = 1, choices = EMPLOYMENT, default = 'x')
street = models.CharField(max_length = 100,default = 'x')
city = models.CharField(max_length = 50,default = 'x')
state = models.CharField(max_length = 2,choices = STATES,default = 'x')
zip = models.CharField(max_length = 10,default = 'x')
def __str__(self):
if self.user_id:
return f'{self.user.username}'
def save(self, *args, **kawrgs):
super().save(*args, **kawrgs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)