2013-03-13 2 views
0

다음 코드는 도움이 필요합니다. 나는 거의 다 왔다고 생각해. 편집 및 새 개체 추가 작업에 대한보기를 만들려고 해요. 그러나 절약에 나는 아래 나열된 오류가 발생합니다.django보기 integrityError

누군가 내가 잘못 가고있는 것을 보여줄 수 있는지 궁금합니다.

감사합니다.

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, "중복 항목을 '1'키 'USER_ID'에 대한")는

는 UPDATE : 그래서 이것은 무엇이다 I 지금 가지고 있고, 작동하지만 편집에만 추가하지 마라.

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

귀하의 group = Groups( 그냥 그룹 변수의 이전 값을 삭제한다 :

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

당신은 당신의 코드를 꽤을 단축 할 수 전망. 양식의 초기화에있는 or 문을 사용하면 GET 요청 인 경우 별도의 메소드가 아닌 한 곳에서 인스턴스화 할 수 있습니다.

사용자 외래 키 속성에 unique=True이 있습니다. 뷰에 수동으로 할당해도 유효성 검사를 수행하지 않습니다. 폼이 인스턴스화 될 때 속성을 할당하면 폼이 제출되기 전에 유효성 검사 오류가 트리거됩니다.

+0

네, 그것은 독특했습니다 = True, 그리고 당신의 아이디어 (일부)와 t가 완벽하게 작동하도록 내 질문을 업데이트했습니다. Brandon, 고마워. – jason

1

시도가

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

에 의해 대체 : 추가에 나는 여전히 같은 오류가 . 수동으로 값을 할당 할 필요가 당신을 절약

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__의 간단한 재정의 당신이 요청에서 사용자의 손으로 할 수 있습니다 :

+0

업데이트 (질문 업데이트 참조)를 반영하도록 업데이트되었지만 저장중인 새 개체에 오류가 발생합니다. – jason