所以我正在使用内置的Django登录表单,我希望我的博客模型继承使用表单创建的所有用户,但它没有显示在博客模型中。
模型
class Blogger(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
follows = models.ManyToManyField('self', related_name='following', symmetrical=False)
def __str__(self):
return self.user.username
查看注册
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/blog')
else:
form = SignUpForm()
return render(request, 'winterblog/signup.html', {'form': form})
使用Django表格
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/blog')
else:
form = SignUpForm()
return render(request, 'winterblog/signup.html', {'form': form})
非常感谢!
答案 0 :(得分:1)
您的注册视图不会创建Blogger
实例。您可以在视图中为新用户创建博客记录:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
Blogger.objects.create(user=user)
login(request, user)
return redirect('/blog')
else:
form = SignUpForm()
return render(request, 'winterblog/signup.html', {'form': form})
另一个选项是添加signal,以便在创建新用户后自动创建新博客:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Blogger.objects.create(user=instance)