我目前正在开发一个博客Web应用程序,我试图用一对一字段扩展我的Django用户框架,一切都很好,但是当我尝试注册新用户时,它会抛出TypeError。还值得注意的是,正在创建和存储用户(我从管理页面进行了检查)。
它是说,我 views.py 的这一发言正在制造问题。profile.user = Profile.objects.get(user=request.user)
我的 models.py:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
CHOICES = (
('AB+', 'AB+'),
('AB-', 'AB-'),
('A+', 'A+'),
('A-', 'A-'),
('B+', 'B+'),
('B-', 'B-'),
('O+', 'O+'),
('O-', 'O-'),
)
bloodgroup = models.CharField(max_length=100, choices= CHOICES)
bio = models.TextField(max_length=300)
def __str__(self):
return f'{self.user.username} Profile'
我的 views.py
from django.shortcuts import render, redirect
from .models import Profile
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, ProfileForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
profile_form = ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
form.save()
profile = profile_form.save(commit=False)
profile.user = Profile.objects.get(user=request.user)
profile.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()
profile_form = ProfileForm
return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form})
@login_required
def profile(request):
return render(request, 'users/profile.html')
翻过高山走不出你
相关分类