加載另一個網頁,我也創建了一個簡單的登記表的博客詢問用戶的用戶名和註冊名。 當爲註冊編號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',)
{% 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 %}
能否請您顯示整個錯誤跟蹤日誌,正常情況下你不應該重定向當你形成無效 – dentemm
添加跟蹤日誌 –
的圖片我已經發布了一個答案您跟蹤日誌,嘗試修復錯誤,然後我會嘗試幫助您的彈出窗口 – dentemm