Python 使用一对一字段扩展Django用户框架,错误:唯一约束失败:userprofile\u profile.User\u id

Python 使用一对一字段扩展Django用户框架,错误:唯一约束失败:userprofile\u profile.User\u id,python,django,Python,Django,我想用一对一字段扩展Django用户框架。这样,我可以在注册时将数据保存在userprofile中。 注册后,用户数据作为新用户保存在admin user中。但是,唯一约束失败:userprofile\u profile.user\u id发生错误,profile.save()语句在错误页面中显示灰色。 此外,数据(学生ID和CBNU ID)不会保存在用户配置文件中 如何解决错误 如何在userprofile中保存数据 我正在关注这个youtube教程 这是视图.py from django.s

我想用一对一字段扩展Django用户框架。这样,我可以在注册时将数据保存在userprofile中。 注册后,用户数据作为新用户保存在admin user中。但是,
唯一约束失败:userprofile\u profile.user\u id发生错误,
profile.save()
语句在错误页面中显示灰色。 此外,数据(学生ID和CBNU ID)不会保存在用户配置文件中

  • 如何解决错误
  • 如何在userprofile中保存数据
  • 我正在关注这个youtube教程

    这是视图.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm, ProfileForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    def update_profile(request):
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            profile_form = ProfileForm(request.POST)
    
            if form.is_valid() and profile_form.is_valid():
                user = form.save()
    
                profile = profile_form.save(commit=False)
                profile.user = user
    
                profile.save()
    
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)
                login(request, user)
                return redirect('login')
    
        else:
            form = SignUpForm()
            profile_form = ProfileForm()
        
        context = {'form': form, 'profile_form': profile_form}
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    from apps.userprofile.models import Profile
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                'password', 
                'password2', 
            ]
    
    class ProfileForm(forms.ModelForm):
       
        class Meta:
            model = Profile
            fields= [ 'student_ID', 'CBNU_PW' ]
            widgets = {
                'student_ID': forms.TextInput(attrs={'placeholder': 'student_ID'}),
                'CBNU_PW': forms.TextInput(attrs={'placeholder': 'CBNU_PW'})
            }
    
    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)
        student_ID = models.CharField(max_length=30, blank=True)
        CBNU_PW = models.CharField(max_length=30, blank=True)
    
        def __str__(self):
            return '%s %s' % (self.user.first_name, self.user.last_name)
    
    @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()
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, update_profile
    from django.contrib.auth import views as auth_views
    # from apps.common.forms import register
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', update_profile, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]
    
    这是forms.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm, ProfileForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    def update_profile(request):
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            profile_form = ProfileForm(request.POST)
    
            if form.is_valid() and profile_form.is_valid():
                user = form.save()
    
                profile = profile_form.save(commit=False)
                profile.user = user
    
                profile.save()
    
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)
                login(request, user)
                return redirect('login')
    
        else:
            form = SignUpForm()
            profile_form = ProfileForm()
        
        context = {'form': form, 'profile_form': profile_form}
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    from apps.userprofile.models import Profile
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                'password', 
                'password2', 
            ]
    
    class ProfileForm(forms.ModelForm):
       
        class Meta:
            model = Profile
            fields= [ 'student_ID', 'CBNU_PW' ]
            widgets = {
                'student_ID': forms.TextInput(attrs={'placeholder': 'student_ID'}),
                'CBNU_PW': forms.TextInput(attrs={'placeholder': 'CBNU_PW'})
            }
    
    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)
        student_ID = models.CharField(max_length=30, blank=True)
        CBNU_PW = models.CharField(max_length=30, blank=True)
    
        def __str__(self):
            return '%s %s' % (self.user.first_name, self.user.last_name)
    
    @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()
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, update_profile
    from django.contrib.auth import views as auth_views
    # from apps.common.forms import register
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', update_profile, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]
    
    这是model.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm, ProfileForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    def update_profile(request):
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            profile_form = ProfileForm(request.POST)
    
            if form.is_valid() and profile_form.is_valid():
                user = form.save()
    
                profile = profile_form.save(commit=False)
                profile.user = user
    
                profile.save()
    
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)
                login(request, user)
                return redirect('login')
    
        else:
            form = SignUpForm()
            profile_form = ProfileForm()
        
        context = {'form': form, 'profile_form': profile_form}
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    from apps.userprofile.models import Profile
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                'password', 
                'password2', 
            ]
    
    class ProfileForm(forms.ModelForm):
       
        class Meta:
            model = Profile
            fields= [ 'student_ID', 'CBNU_PW' ]
            widgets = {
                'student_ID': forms.TextInput(attrs={'placeholder': 'student_ID'}),
                'CBNU_PW': forms.TextInput(attrs={'placeholder': 'CBNU_PW'})
            }
    
    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)
        student_ID = models.CharField(max_length=30, blank=True)
        CBNU_PW = models.CharField(max_length=30, blank=True)
    
        def __str__(self):
            return '%s %s' % (self.user.first_name, self.user.last_name)
    
    @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()
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, update_profile
    from django.contrib.auth import views as auth_views
    # from apps.common.forms import register
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', update_profile, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]
    
    这是url.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm, ProfileForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    def update_profile(request):
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            profile_form = ProfileForm(request.POST)
    
            if form.is_valid() and profile_form.is_valid():
                user = form.save()
    
                profile = profile_form.save(commit=False)
                profile.user = user
    
                profile.save()
    
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)
                login(request, user)
                return redirect('login')
    
        else:
            form = SignUpForm()
            profile_form = ProfileForm()
        
        context = {'form': form, 'profile_form': profile_form}
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    from apps.userprofile.models import Profile
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                'password', 
                'password2', 
            ]
    
    class ProfileForm(forms.ModelForm):
       
        class Meta:
            model = Profile
            fields= [ 'student_ID', 'CBNU_PW' ]
            widgets = {
                'student_ID': forms.TextInput(attrs={'placeholder': 'student_ID'}),
                'CBNU_PW': forms.TextInput(attrs={'placeholder': 'CBNU_PW'})
            }
    
    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)
        student_ID = models.CharField(max_length=30, blank=True)
        CBNU_PW = models.CharField(max_length=30, blank=True)
    
        def __str__(self):
            return '%s %s' % (self.user.first_name, self.user.last_name)
    
    @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()
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, update_profile
    from django.contrib.auth import views as auth_views
    # from apps.common.forms import register
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', update_profile, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]