2012-12-01 3 views
3

나는 같은 저자 ForeignKey이있는 모델을 가지고있다. 즉, 저자 필드 내 Form 클래스에 나타나지 않아야합니다 :일반 뷰를 사용하여 뷰에서 모델 필드를 설정하는 방법은 무엇입니까? <pre><code>class Appointment(models.Model): # ... author = models.ForeignKey(User) </code></pre> <p></p> 내가 현재 로그인하는 사용자가 약속을 만들 때 <code>author</code> 필드가 자동으로 설정하려면 :

  1. 어떻게 일반적인 CreateView에서 폼을 액세스하고 author을 설정 :

    class AppointmentCreateForm(ModelForm): 
        class Meta: 
         model = Appointment 
         exclude = ('author') 
    

    두 가지 문제가있다?

  2. 사용자 입력에서 읽은 값과 함께 제외 필드를 저장하도록 양식에 알리는 방법은 무엇입니까?

답변

2

나는 같은 내 일반적인 뷰 서브 클래스를 수정했습니다

class AppointmentCreateView(CreateView):   
    model=Appointment 
    form_class = AppointmentCreateForm 

    def post(self, request, *args, **kwargs): 
     self.object = None 
     form_class = self.get_form_class() 
     form = self.get_form(form_class) 

     # the actual modification of the form 
     form.instance.author = request.user 

     if form.is_valid(): 
      return self.form_valid(form) 
     else: 
      return self.form_invalid(form) 

몇 가지 중요한 부분이 여기에 있습니다 :

  • 내가 양식에게 무슨 실제 모델을 보유하고 instance 필드를 수정 구원 받는다.
  • 는 계층 구조에서 위의 두 클래스 당신은 물론 내가 수정하는 데 필요 한 form_class
  • 포스트 방법 제거 할 수 있었다, 그래서 나는 과부하를 병합, 기본 코드 self.object = None 라인을 통합하는 데 필요한 하나의 함수로 기본이된다 (나는 에 super을 호출하지 않는다).

꽤 일반적인 문제를 해결하는 좋은 방법이라고 생각합니다. 그리고 다시 한 번 내 자신의 사용자 지정보기를 작성할 필요가 없습니다.

7

다음은 약간 더 단순 해 보입니다. `: 그 self.request는`데프 get_form (자기, form_class ** = 없음 **)를 할 수 없다 woudn't View.as_view

class AppointmentCreateView(CreateView):   
    model=Appointment 
    form_class = AppointmentCreateForm 

    def get_form(self, form_class): 
     form = super(AppointmentCreateView, self).get_form(form_class) 
     # the actual modification of the form 
     form.instance.author = self.request.user 
     return form 
+1

올바른 서명에 설정되어 참고? –

+1

당신은 절대적으로 @AllanVital입니다, 장고 1.8 이후 작성한 것입니다 (1.7이 나왔을 때 장고 사용을 중단했습니다) –