Django에서는 어떻게 Django의 Update_object Generic View를 사용하여 상속 모델의 형식을 편집 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/213237

문제

Django에서는 응용 프로그램에서 발췌 한 내용이 주어졌습니다 동물 LIKESO :

동물/models.py 와 함께:

from django.db import models
from django.contrib.contenttypes.models import ContentType

class Animal(models.Model):
  content_type = models.ForeignKey(ContentType,editable=False,null=True)
  name = models.CharField()

class Dog(Animal):
  is_lucky = models.BooleanField()

class Cat(Animal):
  lives_left = models.IntegerField()

그리고 동물/urls.py:

from django.conf.urls.default import *

from animals.models import Animal, Dog, Cat

dict = { 'model' : Animal }

urlpatterns = (
  url(r'^edit/(?P<object_id>\d+)$', 'create_update.update_object', dict),
)

동일한 형태를 사용하여 개 및/또는 고양이를 편집하기 위해 일반적인 뷰를 어떻게 사용할 수 있습니까?

형태 전달 된 객체 동물/동물 _form.html 동물이 될 것이므로 파생 클래스 개와 고양이에 대한 세부 사항을 포함하지 않습니다. Django가 어린이 수업을위한 양식을 자동으로 전달할 수 있습니까? 동물/동물 _form.html?

또한 사용 중입니다 Djangosnippets #1031 ContentType Management의 경우 동물은 as_leaf_class 그것은 파생 수업을 반환합니다.

분명히, 각각의 파생 클래스에 대해 양식을 만들 수 있지만, 템플릿이 모두 일반적인 경우 ({{form.as_p}}) 매우 불필요한 복제입니다.

덧붙여서, 동물이 아마도 같은 문제를 가진 여러 관련없는 기본 클래스 중 하나 일 것이라고 가정하는 것이 가장 좋습니다. 따라서 이상적인 솔루션은 일반적입니다.

도와 주셔서 미리 감사드립니다.

도움이 되었습니까?

해결책

좋아, 여기에 내가 한 일이 있으며, 효과가 있고 현명한 디자인 인 것 같습니다 (수정 되더라도!).

핵심 라이브러리 (예 : mysite.core.views.create_update)에서 나는 데코레이터를 썼습니다.

from django.contrib.contenttypes.models import ContentType
from django.views.generic import create_update

def update_object_as_child(parent_model_class):
   """
   Given a base models.Model class, decorate a function to return  
   create_update.update_object, on the child class.

   e.g.
   @update_object(Animal)
   def update_object(request, object_id):
      pass

  kwargs should have an object_id defined.
  """

  def decorator(function):
      def wrapper(request, **kwargs):
          # may raise KeyError
          id = kwargs['object_id']

          parent_obj = parent_model_class.objects.get( pk=id )

          # following http://www.djangosnippets.org/snippets/1031/
          child_class = parent_obj.content_type.model_class()

          kwargs['model'] = child_class

          # rely on the generic code for testing/validation/404
          return create_update.update_object(request, **kwargs)
      return wrapper

  return decorator

그리고 동물/보기에서.

from mysite.core.views.create_update import update_object_as_child

@update_object_as_child(Animal)
def edit_animal(request, object_id):
  pass

그리고 동물/urls.py에서는 다음과 같습니다.

urlpatterns += patterns('animals.views',
  url(r'^edit/(?P<object_id>\d+)$', 'edit_animal', name="edit_animal"),
)

이제 각 기본 클래스마다 고유 한 편집 함수 만 필요합니다. 각 기본 클래스는 데코레이터로 만들기 위해 사소한 것입니다.

누군가가 도움이되기를 바랍니다. 피드백을 받게되어 기쁩니다.

다른 팁

AFAICT, 고양이 및 개는 다른 DB 테이블에 있으며 동물성 테이블이 없을 수도 있습니다. 그러나 당신은 모두 하나에 하나의 URL 패턴을 사용하고 있습니다. 어딘가에 각각을 선택해야합니다.

나는 고양이와 개에게 다른 URL 패턴을 사용할 것입니다. 둘 다 'create_update.update_object'; 그러나 다른 것을 사용합니다 dict 각각. 하나와 함께 'model':Dog 그리고 다른 하나는 'model':Cat

아니면 각 레코드가 고양이 나 개가 될 수있는 단일 테이블을 원하십니까? 나는 당신이 그것을 위해 상속 된 모델을 사용할 수 있다고 생각하지 않습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top