2017-03-13 2 views
2

현재 작업중인 Django 프로젝트에 문제가 있습니다. 이 잘 작동모델 변경 후 장고보기가 업데이트되지 않습니다.

class CreatePollView(View): 
    template = "polls/create_poll.html" 

    @method_decorator(login_required) 
    def post(self, request): 
     question_text = request.POST['question'] 
     pub_date = now() 
     new_question = Question(question_text=question_text, pub_date=pub_date) 
     new_question.save() 

     options_list = request.POST.getlist('options') 
     for option in options_list: 
      option_text = option 
      new_option = Option(option_text=option_text, question=new_question) 
      new_option.save() 

     return HttpResponseRedirect(reverse('polls:detail', args=(new_question.id,))) 

:

나는 내가 POST 요청을 통해 모델의 인스턴스를 만들 수있는 볼 수 있습니다. DB에 질의와 옵션을 추가하고 관리자가 추가했는지 확인할 수 있습니다. 그러나 모든 질문 객체를 나열하는 index.html을 호출하면 업데이트되지 않습니다.

class IndexView(View): 
    template = loader.get_template('polls/index.html') 
    questions = Question.objects.all() 
    context = { 
     'question_list': questions, 
    } 

    def get(self, request): 
     return HttpResponse(self.template.render(self.context, request)) 

그리고 템플릿 : 내가보기에 오류를 빌드 할 때

{% extends 'homepage/base.html' %} 
{% block content %} 
    <div class="row"> 
     <div class="col-md-6 col-md-offset-3"> 
      <h1>All Polls:</h1> 
      <div> 
       {% for question in question_list %} 
        <p><a href="{{ question.pk }}">{{ question }}</a></p> 

       {% endfor %} 
       <a href="new_poll" class="btn btn-primary">New Poll</a> 
      </div> 
     </div> 
    </div> 
{% endblock %} 

는, 다음을 수정하고 코드를 실행 다시 목록을 업데이트합니다. Question.objects.all()

그러나 새 모델 인스턴스를 게시 할 때 모델 변경 사항이 여기에 표시되지 않습니다. 누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까?

편집 : 이것은 클래스 기반보기에서만 발생합니다. 메서드 뷰를 사용할 때 제대로 작동했습니다.

def index(request): 
    question_list = Question.objects.all() 
    template = loader.get_template('polls/index.html') 
    context = { 
     'question_list': question_list, 
    } 
    return HttpResponse(template.render(context, request)) 


def new_poll(request): 
    if request.method == 'POST': 
     question_text = request.POST['question'] 
     pub_date = now() 
     new_question = Question(question_text=question_text, pub_date=pub_date) 
     new_question.save() 

     options_list = request.POST.getlist('options') 
     # import pdb 
     # pdb.set_trace() 
     for option in options_list: 
      option_text = option 
      new_option = Option(option_text=option_text, question=new_question) 
      new_option.save() 

     return HttpResponseRedirect(reverse('polls:detail', args=(new_question.id,))) 
    else: 
     template = loader.get_template('polls/create_poll.html') 
     context = { 
      'user': request.user 
     } 
     return HttpResponse(template.render(context, request)) 
+0

일반 클래스 기반보기를 사용하면 이보다 훨씬 적은 코드를 작성할 수 있습니다. –

+0

저는 리팩토링의 한가운데에 있는데, 이것이 좋지만 처음에는 어떻게 변화를 내 모델에 표시할지 알아 내고 싶습니다. – Ozymandias

답변

2

은 장고는하지 모든 것이 각각의 모든 HTTP 요청에 다시로드되는 CGI 스크립트로, (한 번로드 영원히 제공) 장기 실행 프로세스로 작동하도록 설계되었습니다. 즉, 함수 밖에서 발생하는 모든 일 (즉, 모듈의 최상위 레벨, 클래스 명령문의 본문 등)은 모듈의 첫 번째 가져 오기에서 한 번만 (프로세스 당) 실행됩니다 (물론 모든 Python 프로세스의 경우와 마찬가지로 실제로 여기의 점이 있음을 의미합니다 그것은 단발 스크립트가 아니라 장기 실행 프로세스라는 것입니다. 그래서 여기

: 클래스 본문에

class IndexView(View): 
    template = loader.get_template('polls/index.html') 
    questions = Question.objects.all() 
    context = { 
     'question_list': questions, 
    } 

이 세 문은 모듈의 첫 번째 수입에 class 문 eval'd된다. 그런 다음 해당 값은 프로세스 수명 동안 다시 평가되지 않으므로 서버 프로세스를 종료하고 새 프로세스를 시작하기 전까지 요청에서 요청까지 context['question_list']에 대해 동일한 결과를 실제로 유지합니다 (첫 번째 요청 후 부실하게됩니다). , 등).

코드가 각 요청에 대해 실행되어 최신 쿼리 세트를 생성하기 때문에 함수 기반 뷰에 문제가 없습니다.

는 클래스에 get 방법이 코드를 이동하여 시작, 긴 이야기를 짧게 만들려면 :

class IndexView(View): 
    def get(self, request): 
     template = loader.get_template('polls/index.html') 
     questions = Question.objects.all() 
     context = { 
      'question_list': questions, 
     } 
     return HttpResponse(template.render(context, request)) 

그런 다음 당신이 장고의 forms, modelforms, shortcuts 등에 대해 배우고 좀 더 시간이 걸릴 수도 있습니다, 그리고 클래스 기반 뷰를 사용하기를 원한다면 various mixins도 사용하는 법을 배워야합니다.

+0

대단히 감사합니다! 좋은 것을 배우고 지금은 완벽하게 작동합니다. – Ozymandias

관련 문제