1

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

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 

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

没有重定向到错误的 URL

意见:

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'),
4

1 回答 1

1

我确信有一种方法可以在像您这样的基于类的视图中重定向,但我会这样做,只要保存表单,它就会重定向。如果是这样,您的保存方法是否有效?已经在初始创建表单中提交了说。任何其他问题让我知道。

视图.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'),
于 2015-08-19T15:20:34.453 回答