2012-05-11 3 views
1

저는 이것을 몇 시간 동안 알아 내려고 노력해 왔으며, 저를 믿습니다. 저는 실제로 Stack Overflow에서 보았습니다.외래 키 제약 조건을 부여하는 UserProfile에 외래 키를 추가하지 못했습니다.

내 UserProfile에 다른 모델 ("회사"라고 함)에 대한 ForeignKey 참조가 있으며 등록시 새 회사를 만들고 UserProfile ForeignKey를 해당 회사로 지정합니다.

class UserProfile(models.Model): 
    company = models.ForeignKey(Company) 
    title = models.CharField(max_length = 50, default = '') 
    user = models.OneToOneField(User, default = 0, null = True) 

class Company(models.Model): 
    """A company profile.""" 
    name = models.CharField(max_length = 50) 

내가 서명까지 할 수있는 양식을 사용하여 다음과 같이

models.py이다.

class SignupForm(ModelForm): 
    name = forms.CharField(label = "Name") 
    company = forms.CharField(max_length = 50) 
    email = forms.EmailField(label = "Email") 
    password = forms.CharField(widget=forms.PasswordInput) 

    class Meta: 
    model = User 
    fields = ("name", "company", "email", "password") 

    def save(self, commit=True): 
    user = super(SignupForm, self).save(commit=False) 
    name = self.cleaned_data["name"].split() 
    if len(name) == 1: 
     # User did not enter a last name. 
     user.first_name = name 
    else: 
     user.first_name, user.last_name = name 
    user.email = self.cleaned_data["email"] 
    user.set_password(self.cleaned_data["password"]) 
    user.username = user.email 
    if commit: 
     user.save() 

    return user 

을 여기에 가입 뷰의 : 여기에 양식입니다

def signup(request): 
    if request.method == 'POST': 
    form = SignupForm(request.POST) 
    if form.is_valid(): 
     # Check if email has already been used for an account. 
     email = request.POST['email'] 
     existing_account = User.objects.filter(email = email) 
     if existing_account: 
     form = SignupForm() 
     return render_to_response('registration/signup.html', 
      { 'form': form, 
      'error': 'duplicate_email', 
      }) 

     # Otherwise, save the form and create a new user. 
     new_user = form.save() 

     company = Company(name=request.POST['company']) 
     company.save() 

     user_profile = new_user.get_profile() 
     user_profile.company = company 
     user_profile.save() 

     new_user = authenticate(
     username = email, 
     password = request.POST['password'] 
    ) 
     # Log the user in automatically. 
     login(request, new_user) 

     # Redirect user to Thank You page. 
     return HttpResponseRedirect('/thanks') 
    else: 
    form = SignupForm() 

    return render_to_response('registration/signup.html', { 
    'form': form, 
    }) 

내가 나에게 그 COMPANY_ID을 말하고 무엇입니까 오류가 null 일 수 없습니다. 나는 분명히 새로운 회사를 추가한다. 당신이 잘못 생각한 것을 알려주십시오.

감사합니다.

+0

오류를 붙여 넣으십시오. 나는 회선을 알고 싶다 – Goin

+0

응답에 감사드립니다. 오류에서 참조되는 행은 new_user = form.save() 및 user.save()입니다. 오류는 (1048, " 'company_id'열은 null 일 수 없습니다.) –

답변

0

SQLite로 인해 발생한 것 외에는 아무런 이유없이이 정확한 오류가있었습니다. SQLite에서는 한 테이블의 id 필드가 INTEGER PRIMARY KEY에서 INTEGER로 이동했습니다. SQLite를 사용하고 있다면 문제가되는 테이블을 삭제하고 syncdb로 다시 만들어보십시오.

user_profile = new_user.get_profile() 

의 가치는 무엇입니까?

+0

MySQL을 사용하며 ID 필드는 INTEGER PRIMARY KEY입니다. 또한, 내 user_profile 테이블에 아무것도 표시되지 않기 때문에 내가 가정 할 값은 null입니다. –

0

취향에 너무 익숙하지 않은지 확실하지 않지만 회사 개체를 만들고 저장 한 다음 위치/키워드 인수로 SignupForm.save() 메서드에 전달할 수 있습니다.

당신이 얻을 수있는 문제는 당신이 CharField를 기대하고 회사 객체를 전달할 것이라는 것입니다. 그래서 당신은 아마 company.pk를 당신의 형태로 회사 필드에주고 싶을 것입니다.

관련 문제