2016-09-10 1 views
0

기존 데이터가있는 경우 ModelForm을 채우려하고 있거나 존재하지 않는 경우 새 인스턴스를 만들려고합니다. django docs 및 스택 오버플로에 대한 몇 가지 질문을 읽었지만 내 양식이 기존 데이터로 채워지지 않는 이유를 알 수 없습니다. 나는 간단한 것을 놓치고 있다고 확신한다. 어떤 도움이라도 인정 될 것이다.인스턴스 = 개체가 설정된 경우 Django 모델 양식이 채워지지 않습니다.

views.py에서
from django.forms import ModelForm, Textarea 
from .models import Batch 

class BatchForm(ModelForm): 
    class Meta: 
     model = Batch 
     fields = ('recipe', 'date', 'original_gravity', 'final_gravity', 'gravity_units', 'notes') 
     widgets = {'notes': Textarea(attrs={'cols': 40, 'rows': 10})} 

: (인스턴스 = 배치 인수 통지 이것이 올바른 형태를 미리 입력합니까?)

def batch_entry(request, batch_id): 
    if int(batch_id) > 0: 
     batch = get_object_or_404(Batch, id=batch_id) 
     form = BatchForm(request.POST, instance=batch) 
     context = {'BatchForm': form, 'batch': batch } 
    else: 
     form = BatchForm() 
     context = {'BatchForm': form, 'batch': None } 
    return render(request, 'logger/batch_entry.html', context) 

batch_entry.html forms.py에서

템플릿 :

{% if batch.id > 0 %} 
<h1>{{batch.date}}</h1> 
<h3>{{batch.recipe}}</h3> 
<form action="{% url 'logger:batch_entry' batch.id %}" method="post"> 
    {% csrf_token %} 
    <table> 
    {{BatchForm.as_table}} 
    </table> 
    <input type="submit" value="Submit"> 
</form> 
{% else %} 
<h1>New Batch</h1> 
<form action="{% url 'logger:batch_entry' 0 %}" method="post"> 
    {% csrf_token %} 
    <table> 
    {{BatchForm.as_table}} 
    </table> 
    <input type="submit" value="Submit"> 
</form> 
{% endif %} 
<form action="{% url 'logger:index' %}" method="post"> 
    {% csrf_token %} 
    <input type="submit" value="Return to Index"> 
</form> 

답변

1

당신이 request.POST을 통과 이야 때문입니다. 그것은 이 제출 된 데이터를 포함해야하는데,이 데이터는 당연히 인스턴스에 이미있는 값을 대체합니다. 하지만 GET에서 그렇게하기 때문에 POST 데이터는 비어 있으므로 양식이 비어있게 표시됩니다.

요청이 실제로 POST 인 경우에만 request.POST를 양식에 전달하십시오.

+0

감사합니다. 나는 그것이 간단 할 것이라고 생각했다. –

관련 문제