2013-03-13 50 views
0

我需要以下代碼的幫助。我想我快到了。我正在嘗試創建一個用於編輯和添加新對象的視圖。但是,在保存時出現下面列出的錯誤。django查看完整性錯誤

我不知道是否有人能告訴我我哪裏出錯了嗎?

謝謝。

view.py

def group(request, id=None): 

    if id: 
     group = get_object_or_404(Groups, pk=id) 

    else: 
     group = Groups() 

     # If we had a POST then get the request post values. 
    if request.method == 'POST': 
     form = GroupFrom(request.POST) 
     # Check we have valid data 
     if form.is_valid(): 
      group = Groups(
       name=form.cleaned_data['name'], 
       description=form.cleaned_data['description'], 
       active=form.cleaned_data['active'], 
       user=request.user 
      ) 

      group.save() 

    else: 
     form = GroupFrom(instance=group) 

    context = {'form': form} 
    return render_to_response('contacts/group.html', context, context_instance=RequestContext(request)) 

urls.py

 (r'^group/new/$', 'contacts.views.group', {}, 'group_new'), 
    (r'^group/edit/(?P<id>\d+)/$', 'contacts.views.group', {}, 'group_edit'), 

model.py

class Groups(models.Model): 
    """ 
    Stores all groups. 
    """ 
    name = models.CharField(max_length=60) 
    description = models.TextField(max_length=250) 
    active = models.BooleanField() 
    modified = models.DateTimeField(null=True, auto_now=True, help_text="Shows when object was modified.") 
    created = models.DateTimeField(auto_now_add=True, help_text="Shows when object was created.") 

    #FK 
    user = models.ForeignKey(User, unique=True, related_name="user") 

    def __unicode__(self): 
     return self.name 

錯誤

IntegrityError在/聯繫人/組/編輯/ 1/ (1062, 「關鍵 'user_ID的' 重複項 '1'」)

UPDATE: 原來這就是我現在,它的工作原理,但只有在編輯不添加。在添加時我仍然得到了同樣的錯誤:

def group(request, id=None): 

    if id: 
     # If we have an id try and get it and populate instance. 
     group = get_object_or_404(Groups, pk=id) 
     # If we have an instance check that it belongs to the login. 
     if group.user != request.user: 
      return HttpResponseForbidden() 
    else: 
     # If we don't have an id get the instance (which is blank here) and populate it with the user. 
     group = Groups(user=request.user) 

    # If we had a POST then get the request post values. 
    if request.method == 'POST': 
    # Populate the form with the instance. 
     form = GroupFrom(request.POST, instance=group) 
     # Check we have valid data before saving trying to save. 
     if form.is_valid(): 
      group.save() 
      messages.add_message(request, messages.SUCCESS, 'Successfully Created/Updated Group') 

    else: 
     # Populate from at this point group with either be blank or have values. 
     form = GroupFrom(instance=group) 

    context = {'form': form} 
    return render_to_response('contacts/group.html', context, context_instance=RequestContext(request)) 

回答

1

可以縮短你的代碼相當多:

class GroupForm(forms.ModelForm): 
    class Meta: 
     model = Group 

    def __init__(self, *args, **kwargs) 
     user = kwargs.pop('user') 
     super(GroupForm, self).__init__(*args, **kwargs) 
     self.user = user 

def group(request, id=None): 
    if id: 
     instance = get_object_or_404(Groups, pk=id) 
    else: 
     instance = None 

    form = GroupFrom(request.POST or None, instance=instance, user=request.user) 

    if request.method == 'POST': 
     if form.is_valid(): 
      group = form.save() 
    return render_to_response('contacts/group.html', {'form': form}, 
     context_instance=RequestContext(request)) 

的GroupForm的__init__一個簡單的替代,您可以從該請求的用戶的手,無需手動分配的價值爲您節省視圖。表單初始化中的or語句允許您在一個地方執行實例化,而不是在GET請求中有單獨的方法。您的用戶外鍵屬性爲unique=True。在視圖中手動分配它不會得到任何驗證。在表單被實例化時分配屬性在提交表單之前應該觸發驗證錯誤。

+0

是的,這是獨特的=真,我更新了我的問題,以納入你的想法(一些什麼)和完美的作品。謝謝布蘭登。 – jason 2013-03-13 17:22:44

1

嘗試更換

  group = Groups(
      name=form.cleaned_data['name'], 
      description=form.cleaned_data['description'], 
      active=form.cleaned_data['active'], 
      user=request.user 
     ) 

由:

 group.name=form.cleaned_data['name'] 
     group.description=form.cleaned_data['description'] 
     group.active=form.cleaned_data['active'] 
     group.user=request.user 

group = Groups(只是擦除變量的前值。

+0

我已更新以反映(請參閱問題更新),但我仍然在保存新對象時發生錯誤。 – jason 2013-03-13 17:19:44