gpt4 book ai didi

python - “No URL to redirect to” 如何重定向到django同一页面

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:45 24 4
gpt4 key购买 nike

我正在使用由用户填充的表单。 forms.py 的 save 方法如下所示:

def save(self, commit=True):
instance = super(LocationForm, self).save(commit=False)
if instance.location_id:
instance.save()
else:
new_location=Location.objects.create(name=self.cleaned_data['name'])
instance.location=new_company
instance.save()
return instance

因此,当我单击更新时,数据会保存在数据库中,但出现错误

No URL to redirect to error

浏览次数:

class LandingView(CreateView):
model = Review
form_class = LocationForm
template_name="core/index.html"

models.py - 我创建了一个 get_absolute_url 函数

from django.core.urlresolvers import reverse

def get_absolute_url(self):
return reverse ('index', args=[str(self.id)])

所以在网址中我尝试了这个

url(r'^$', core.views.LandingView.as_view(success_url="success"), name='index'),

但是,如果我希望将其重定向到其原始页面,例如“回到我来自的地方”,我该怎么办?

我试过了

url(r'^$', core.views.LandingView.as_view(success_url=""), name='index'),

url(r'^$', core.views.LandingView.as_view(success_url=reverse('index')), name='index'),

url(r'^$', core.views.LandingView.as_view(success_url=reverse("")), name='index'),

但是这些都不起作用!

编辑此网址有效,我不需要 def_get_absolute_url

url(r'^$', core.views.LandingView.as_view(success_url="/"), name='index'),

最佳答案

我确信有一种方法可以在像您这样的基于类的 View 中进行重定向,但我将这样做,只需保存表单即可重定向。您的保存方法是否有效,如果是的话,我喜欢您这样做的方式,但我不确定编辑您的保存方法是否是最好的方法,而不是在 View 中获取实例,而是使用以下数据预先填充表单已经以初始创作形式提交。任何其他问题请告诉我。

View .py

 from app.forms import LocationForm

def Landing_View(request)
if request.method == 'POST':
form = LocationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/your_url/')
else:
print form.errors()
else:
form = LocationForm()
return render (request, 'template.html', {'form':form},)

urls.py - Landing_View 的 URL,然后我会在保存时将您重定向回此 URL

  url(r'^your_url/', app.views.Landing_View, name='your_url'),

关于python - “No URL to redirect to” 如何重定向到django同一页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com