反向函数如何在Django中工作?

时间:2016-01-09 15:51:24

标签: django

我有两个看起来像这样的模型:

class Respond(models.Model):
        id = models.AutoField(primary_key=True, unique=True)

class Product(models.Model):
        responde = models.ForeignKey(Responde, null=True)
        name = models.CharField(max_length=255)
        description = models.CharField(max_length=10, blank=True, null=True)
        price = models.CharField(max_length=50, blank=True, null=True)

我的表单是在提交后,将数据发送到远程服务器,然后接收xml响应。我有一个解析xml文件或类文件对象的脚本。比我将xml数据保存到数据库。

class MyView(View):

        template_name = 'myapp/form.html'

        def get(self, request, *args, **kwargs):
                my_form = MyForm(prefix='my_form')
                return render(request, self.template_name, { 'my_form' : my_form })

        def post(self, request, *args, **kwargs):
                my_form = MyForm(request.POST, prefix='my_form')
                if my_form.is_valid():
                ## cleaned data
                r = Respond.objects.create() 
                for xmldata in products_xml:
                   p = Product(
                      name=xmldata['ProductName'],
                      description=xmldata['ProductDescription'],
                      price=xmlData['ProductPrice'],
                   )
                   p.respond = r
                   p.save()
                r.product_set.all() 
        return HttpResponseRedirect(reverse(respond:'result', args=(r.id)))

之后我想重定向到显示来自响应ID的所有保存数据的页面。

在我的情况下,invalid syntax函数字符串出现reverse错误。我阅读有关它的官方文档,但我真的不明白工作如何反向功能。 我的views.py:

def result(request):
        all_products = Products.objects.all()
        template = get_template("booking/results.html")
        context = Context({ 'all_products':all_products })
        html = template.render(context)
        return HttpResponse(html)

我的urls.py看起来像这样:

urlpatterns = patterns('',
        url(r'^$', views.MyView.as_view()),
        url(r'^(?P<respond_id>[0-9]+)/result/$', name='result'),
)

帮助我理解如何使用url配置看起来像反向功能。谢谢。

2 个答案:

答案 0 :(得分:1)

首先,您缺少应在urlpatterns中调用的实际功能:

urlpatterns = patterns('',
        url(r'^$', views.MyView.as_view()),
        url(r'^(?P<respond_id>[0-9]+)/result/$', views.result, name='result'),
)

反向函数的参数应为:

reverse('result', args=['your-arguments'])

描述here

因此,您要从要反转的视图名称开始,如果需要,可以附加argskwargs

答案 1 :(得分:1)

而不是:

return HttpResponseRedirect(reverse(respond:'result', args=(r.id)))

试试这个:

return HttpResponseRedirect(reverse('result', args=[r.id]))