我有一个Django表单,一旦提交了数据,我想重定向到另一个显示数据的页面。
我遇到了麻烦,因为在表单提交之前,我不知道如何检索外键
表单
class addEventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(addEventForm, self).__init__(*args, **kwargs)
class Meta:
model = Event
fields = '__all__'
查看
class addEventView(LoginRequiredMixin,View):
template_name = 'pages/add_event.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
form = addEventForm(request.POST)
if form.is_valid():
form.save()
data = {"success": "successfully added"}
else:
data = {"error": form.errors}
return JsonResponse(data, safe=False)
JS-
onst xhr = new XMLHttpRequest();
xhr.open("POST", "/pages/add_event");
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(formdata);
xhr.onload = () => {
window.location.reload();
};
如何重定向但从POST
中提取数据?
感谢
您可以使用CreateView和success_url
试试
from django.views.generic.edit import CreateView
from django.urls.base import reverse_lazy
class addEventView(LoginRequiredMixin, CreateView):
template_name = 'pages/add_event.html'
model = Event
form_class = addEventForm
success_url = reverse_lazy('url_name_you_want_to_redirect_to')
仅供参考:在python中,类名通常应该使用CapWords约定,因此最好分别将addEventForm
更改为AddEventForm
,将addEventView
更改为AddEventView