2015-09-24 75 views
1

以下是我在做inlineformset django時所需的代碼。問題是,我有相同的ForeignKeys兩個屬性,它返回一個錯誤的Django具有兩個相同外鍵的Django Inlineformset

models.py

class Reference(models.Model): 
    user = models.ForeignKey(UserProfile, related_name="user_mariner", default=None) 
    verified_by = models.ForeignKey(UserProfile, related_name="verified_by", default=None) 
    company = models.ForeignKey(Company, default=None) 
    date = models.DateField(null=True, blank=True, default=None) 
    person_contacted = models.ForeignKey(PersonReference, default=None) 
    veracity_seagoing_history = models.NullBooleanField() 
    health_problem = models.NullBooleanField() 
    financial_liability = models.NullBooleanField() 
    rehiring_prospects = models.NullBooleanField() 
    character = models.TextField(null=True, blank=True, default=None) 
    comments = models.TextField(null=True, blank=True, default=None) 

forms.py

class ReferenceForm(forms.ModelForm): 
    class Meta: 
     model = Reference 
     exclude = '__all__' 

views.py

try: 
    reference = Reference.objects.filter(user=id) 
    ReferenceFormSet = inlineformset_factory(UserProfile, Reference, fields='__all__', extra=3, can_delete=True) 
    reference_form = ReferenceFormSet(request.POST or None, instance=user_profile) 
except: 
     print "%s - %s" % (sys.exc_info()[0], sys.exc_info()[1]) 

template = "application-profile/profile.html" 
context_dict = {} 
context_dict['reference_form'] = reference_form 
return render(request, template, context_dict) 

profile.html

{{ reference_form }} 

錯誤

<type 'exceptions.ValueError'> - 'mariners_profile.Reference' has more than one ForeignKey to 'login.UserProfile'. 
+0

您是否嘗試過在您的inlineformset_factory調用中使用'fk_name'? :https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#more-than-one-foreign-key-to-the-same-model – trpt4him

+0

這實際上回答了我的問題。非常感謝! –

回答

0

您必須指定要用作 '鏈接' 的母體使用字段的名稱。例如:

ReferenceFormSet = inlineformset_factory(UserProfile, Reference, fk_name='user', fields='__all__', extra=3, can_delete=True) 
+0

非常感謝,這正是我正在尋找的! –

相關問題