Django内联外键与父主键不匹配

Posted

技术标签:

【中文标题】Django内联外键与父主键不匹配【英文标题】:Django inline foreign key does not match parent primary key 【发布时间】:2012-07-08 11:45:05 【问题描述】:

我需要一些帮助来解决使用内联表单的 django 错误。我似乎无法弄清楚这一点。如果我能在尝试验证之前弄清楚如何执行此操作,我可能会强制插入 eventID。

提交表单时出现错误:Hidden field (event): The inline foreign key did not match the parent instance primary key

有没有办法让这段代码工作?

下面的代码应该让老师为一个活动注册多个学生。

------models.py ------------

class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    time = models.DateTimeField()
    duration = models.DecimalField(max_digits=5, decimal_places=2)
    location = models.CharField(max_length=200)


# Customer is a parent, teacher, or school
class Customer(models.Model):
    event = models.ForeignKey(Event)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30) 
    address1 = models.CharField(max_length=60) 
    address2 = models.CharField(max_length=60, blank=True) 
    city = models.CharField(max_length=30) 
    state = models.CharField(max_length=2) 
    zipcode = models.CharField(max_length=5) 
    phone_number = models.CharField(max_length=30)
    email = models.EmailField()


# A customer can enroll several students for a single event.
class Attendee(models.Model):
    event = models.ForeignKey(Event)
    sponsor = models.ForeignKey(Customer)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30) 

-----forms.py -----------

class AttendeeForm(forms.ModelForm):
  event = forms.IntegerField(required=True, widget=forms.HiddenInput())

  class Meta:
    model = Attendee
    fields = ( 'event', 'last_name', 'first_name', 'gender', 'schoolYr', )
    #exclude = ('event', )
    #widgets = 
    #     'dtgPurchase' : DateTimeWidget(),
    #

  def __init__(self, *args, **kwargs):
      super(AttendeeForm, self).__init__(*args, **kwargs)

-------views.py ----------

def register3(request, event_id):
  messages = []
  try:
    event = get_object_or_404(Event, id=event_id)  #Event ID is passed in here.
    AttendeeFormSet = inlineformset_factory(Event, Attendee, form=AttendeeForm, extra=1)
    #AttendeeFormSet = formset_factory(AttendeeForm)
    if request.method == 'POST':
      print "POST"
      formset = AttendeeFormSet(request.POST, request.FILES, prefix='attendees')
      #formset.save(commit=False)
      i=0
      for form in formset.forms:
         print "Form %s " % str(i)
         #  ??  Is is possible to set the event Here? 

      if formset.is_valid():
          attendees = formset.save_all()
          print "Yay!!!"   
          #return redirect('event_view', event_id=event.id)
      else:
          print "Invalid formset"

    else:   # is get method on first step
      formset = AttendeeFormSet(instance=event, prefix='attendees')
      print "Event: %s " % event

  except Event.DoesNotExist:
      raise Http404

  c = Context(
      'messages': messages,
      'event' : event,
      'attendees': formset,
  )
  return prepCxt(request, 'register3.html', c)    

【问题讨论】:

【参考方案1】:

您可能还需要在 POST 处理中传递实例。

formset = AttendeeFormSet(request.POST, request.FILES, prefix='attendees', instance=event)

【讨论】:

以上是关于Django内联外键与父主键不匹配的主要内容,如果未能解决你的问题,请参考以下文章

如何分清SQL数据库中的主键与外键

sql用命令创建主键与外键。

sql server的主键与外键问题

在navicat中怎么外键与主键关联

数据库中 主键与外键的区别?

sql server 主键与外键约束无法创建