0
我正在嘗試爲我的所有用戶創建一個配置文件模型。我有下面的代碼中,我得到一個自定義字段birth_date
,但似乎無法得到任何我的其他自定義字段的工作:在Django中擴展用戶模型
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
class Meta:
model = User
fields = ('username', 'first_name','last_name', 'birth_date','location', 'password1', 'password2',)
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
views.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import SignUpForm
def home(request):
return HttpResponse('fd')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.profile.birth_date = form.cleaned_data.get('birth_date')
user.profile.college = form.cleaned_data.get('college')
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'accounts/profile.html', {'form': form})
urls.py
urlpatterns = [
url(r'^register/$', views.signup, name='profile'),
url(r'^home/$', views.home, name='home'),
]
如果我從forms.py刪除location
,形式會正確加載,並讓我填寫,並在提交的所有數據,包括自定義字段birth_date
將節省。但是,當我嘗試添加location
的形式,我得到以下錯誤:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/models.py", line 262, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (location) specified for User
我不知道爲什麼我不能location
字段添加到窗體。
我一直在努力讓這個工作好幾天,謝謝! –