Django ModelForm错误消息未在模板中显示

时间:2017-08-29 16:56:03

标签: python django

我在文档后面创建了一些自定义错误消息(尽我所能找到),但我没有收到任何错误,更不用说我的自定义错误了。这是我的代码:

forms.py

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = Job
        fields = ['jobID','original_file']
        labels = {
            'jobID': _('Job ID'),
            'original_file': _('File'),
        }
        error_messages = {
            'jobID': {
                'max_length': _("Job ID is limited to 50 characters."),
                'required': _("Please provide a Job ID."),
                'invalid': _("Job ID must be a combination of letters, numbers, - and _.")
            },
            'original_file': {
                'required': _("Please provide a file."),
                'validators': _("Please ensure you are selecting a zipped (.zip) GDB."),
            },
        }
        help_texts = {
            'original_file': _('Please provide a zipped (.zip) GDB.'),
        }

upload.html

    <form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data" name="uploadForm">
        {% csrf_token %}

        {% for field in form %}
        <div>
            <strong>{{ field.errors }}</strong>
            {{ field.label_tag }} {{ field }}
            {% if field.help_text %}
                <p class ="help-text">{{ field.help_text }}</p>
            {% endif %}
        </div>
        {% endfor %}

        <br />
        <button type="button" id="uploadButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off" style="margin: auto 20%; ">Upload</button>

    </form>

views.py

def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES, user = request.user)
        if form.is_valid():
            form.save()
            request.session['jobID'] = request.POST['jobID']
            #job = Job.objects.filter(user_id = request.user.id).filter(jobID = request.POST['jobID']).latest()
            # initialize(job)
            return render(request,'precheck/run_precheck.html')
    form = UploadFileForm()
    historyList = Job.objects.filter(user_id = request.user.id)[:10]
    return render(request, 'precheck/upload.html',{'form': form, 'history': historyList})

我已经包含了我认为相关的所有内容,如果您还需要更多内容,请与我们联系。

1 个答案:

答案 0 :(得分:2)

问题是,如果表单无效,您可以将表单重置为初始表单:

form = UploadFileForm()
historyList = Job.objects.filter(user_id = request.user.id)[:10]
return render(request, 'precheck/upload.html',{'form': form, 'history': historyList})

您的流程应该呈现绑定的表单(及其错误),因此它应该是:

if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES, user = request.user)
    if form.is_valid():
         # do stuff for valid form
         return redirect
elif request.method == 'GET':
     form = UploadFileForm()
# flow common for GET and invalid form
return render(request, template, {'form': form})