2017-04-16 49 views
0

I just like the way django displays an error message like this顯示驗證錯誤就像一個彈出窗口,而不是在Django

加載另一個網頁,我也創建了一個簡單的登記表的博客詢問用戶的用戶名和註冊名。 當爲註冊編號django輸入無效條目時,默認情況下將我重定向到頁面顯示由於數據無法驗證而無法創建對象。 而不是重定向到該頁面,如何在類似的彈出窗口中顯示「無效的註冊號碼」。

我views.py:

def post_new(request,): 
if request.method=="POST": 
    authorform=NewAuthor(request.POST) 
    form=NewPost(request.POST) 
    if form.is_valid() and authorform.is_valid(): 
     new_post=form.save(commit=False) 
     new_author=authorform.save(commit=False) 
     new_post.published_date=timezone.now() 
     new_author.save() 
     new_post.author=new_author 
     new_post.save() 
     return redirect('post_detail',pk=new_post.id) 
else: 
    form=NewPost() 
    authorform=NewAuthor() 
    return render(request,'justablog/post_new.html',{'form':form,'authorform':authorform}) 

我的models.py:

from django.db import models 
from django.utils import timezone 
# Create your models here. 
from django.core.validators import RegexValidator 
class Author(models.Model): 
    Username=models.CharField(max_length=30) 
    RegNo=models.CharField(max_length=9,validators=[RegexValidator(
     regex=r'^[0-9]{2}[A-Z]{3}[0-9]{4}', 
     message=("Invalid Registration Number"), 
     code='invalid_regno' 
),]) 
    def __str__(self): 
     return self.Username+'('+self.RegNo+')' 
class Post(models.Model): 
    title = models.CharField(max_length=50) 
    body = models.TextField(max_length=1000) 
    author = models.ForeignKey(Author,null=True) 
    published_date=models.DateTimeField(blank=True,null=True) 
    def publish(self): 
     self.published_date=timezone.now() 
     self.author.save() 
     self.save() 
    def __str__(self): 
     return self.title 

我forms.py;

class NewPost(forms.ModelForm): 
    class Meta: 
     model=Post 
     fields=('title','body',) 
class NewAuthor(forms.ModelForm): 
    class Meta: 
     model=Author 
     fields=('Username','RegNo',) 

我的形式,同時增加了用戶,其註冊號是不正確的:enter image description here

我的錯誤回溯頁: enter image description here 我post_new.html:

{% extends 'justablog/base.html' %} 
{% block content %} 
<h1>Add a new post</h1> 
<form method="POST" class="post-form"> 
{% csrf_token %} 
{{ form.as_p }} 
{{ authorform.as_p }} 
<button type="submit" class="save btn btn-default">Save</button> 
</form> 
{% endblock %} 
+0

能否請您顯示整個錯誤跟蹤日誌,正常情況下你不應該重定向當你形成無效 – dentemm

+0

添加跟蹤日誌 –

+0

的圖片我已經發布了一個答案您跟蹤日誌,嘗試修復錯誤,然後我會嘗試幫助您的彈出窗口 – dentemm

回答

0

有一個錯誤的查看代碼。您檢查表單是否有效,但您不檢查授權形式是否也有效。所以django抱怨說,你正在試圖保存授權形式而不先驗證它。你的if語句應該檢查兩個表單是否有效。

編輯: 現在前端,回答你原來的問題。

你可能想手動渲染表單,而不是使用form.as_p。您可以通過表單的各個領域的循環,像這樣每個字段中顯示錯誤:

<form> 
{% csrf_token %} 
{% for field in form %} 
    <div class="popup"> 
    {{ field.errors }} 
    </div> 
    {{ field.label_tag }} 
    {{ field }} 
    </div> 
{% endfor %} 
</form> 

所以你把field.errors在彈出的窗口中,並在頁面重載您在前端代碼查詢如果有任何錯誤存在。如果有錯誤,則顯示彈出窗口。

這應該讓你開始,我認爲

+0

添加您要求的if語句@dentemm –

+0

好的,我現在能看到您的HTML表單嗎? – dentemm

+0

也添加了post_new.html文件.. –