0

私は Django を初めて使用し、登録フォームを作成しようとしています。これは私のモデルの関連部分です:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    university = models.ForeignKey('University')
    course_title = models.ForeignKey('Course_Title')

    class Meta:
        db_table = 'user_profile'

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

これは私が使用しているフォームです:

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from shelf.models import University, Course_Title, UserProfile

class RegistrationForm(UserCreationForm):

error_messages = {
    'duplicate_email': "A user with that e-mail already exists.",
    'email_mismatch': "The two e-mail fields didn't match.",
}

# An e-mail is being used instead of the usual Django username.
username = forms.EmailField(label="E-mail")
username2 = forms.EmailField(label="Confirm E-mail")
university = forms.ModelChoiceField(queryset=University.objects.all(), empty_label="Please choose a university")
course_title = forms.ModelChoiceField(queryset=Course_Title.objects.all(), empty_label="Please choose a course title")

class Meta:
    model = User
    fields = ("first_name", "last_name", "university", "course_title", "username", "username2")

    .
    .
    .

def save(self, commit=True):
    user = super(RegistrationForm, self).save(commit=False)
    user.save()
    user_profile = UserProfile(user=user, university=self.cleaned_data["university"], course_title=self.cleaned_data["course_title"])
    if commit:
        user_profile.save()
    return user_profile

そして、これは私の見解です:

def index(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/")
    else:
        form = RegistrationForm() 

    return render(request, "shelf/register.html",  {'form': form,  })

エラー user_profile.university_id may not be NULL が表示されます。なぜこれが起こるのかをよく調べましたが、なぜそれが起こるのか理解しています。しかし、私はそれを修正することはできません。

前もって感謝します。

4

2 に答える 2

0

問題はシグナル ハンドラが原因のようです。

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance) # no university here

post_save.connect(create_user_profile, sender=User)

このハンドラーを無効にして、もう一度テストしてください。

シグナル ハンドラーが必要な場合は、form.save メソッドを変更してみてください。

def save(self, commit=True):
    user = super(RegistrationForm, self).save(commit=False) #this should trigger the signal handler to create a UserProfile instance, but not commit
    user_profile = user.get_profile()
    user_profile.university=self.cleaned_data["university"]
    user_profile.course_title=self.cleaned_data["course_title"]
    if commit:
        user.save()
        user_profile.save()

シェルでユーザーを作成すると、同じエラーが発生することに注意してください。 UserProfile モデルのUniversityおよびcourse_titleフィールドのデフォルト値を追加できると思います。

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    university = models.ForeignKey('University', default=1)
    course_title = models.ForeignKey('Course_Title', default=1)
于 2012-06-04T02:14:22.573 に答える
0

私は同じ問題を抱えていますが、手順に従っても解決できませんでした

モデル

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    url = models.URLField()
    home_address = models.TextField()
    user = models.ForeignKey(User, unique=True)


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

意見

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Group
from django import forms
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template.context import RequestContext
from django.views.decorators.csrf import csrf_protect
class RegisterForm(UserCreationForm):
    permission_choices = (
            ('1', 'test1'),
            ('2', 'test2'),
            )
    email      = forms.EmailField(required=False)
    first_name = forms.CharField(required=False)
    last_name  = forms.CharField(required=False)
    url        = forms.URLField()
    permission = forms.ChoiceField(choices=permission_choices)

    class Meta(UserCreationForm.Meta):
        model = User
        fields = ('first_name', 'last_name', 'url', 'username', 'email', 'password1', 'password2', 'permission')

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user_profile    = user.get_profile()
        user.email      = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name  = self.cleaned_data['last_name']
        user.permission = self.cleaned_data['permission']
        user_profile.url = self.cleaned_data['url']
        if commit:
            user.save()
            user_profile.save()
        return user

@csrf_protect
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            if new_user.permission == 'q':
                try:
                    new_user.groups.add(Group.objects.get(name='test1'))
                except Group.DoesNotExist:
                    u = User.objects.get(pk=new_user.pk)
                    u.delete()
                    return HttpResponse('The Organisation you\'ve just choosed doesn\' exist')
            return HttpResponse('OK')
    else:
        form = RegisterForm()

    return render_to_response('registration/user.html', {'form': form}, context_instance=RequestContext(request))
于 2012-06-05T05:27:38.433 に答える