反向网址没有显示django中的完整网址

时间:2015-02-04 12:18:40

标签: python django

这是我的代码

#Send mail to admin
admin_subject = "New question added"
admin_message = "A new question has been successfully added. Please review and approve it."
url = reverse("admin:appname_question_change", args=(new_question.pk,))
admin_html_message = "<h3>%s</h3>\
                                <p>%s</p>\
                                <a href='%s'>%s</a>" % (admin_subject, admin_message, url, url)

我用它来发送邮件。 在我收到邮件中的完整URL之前。 与http://192.168.1.0:8000/admin/appname/answer/12

一样

但现在只提供/admin/appname/answer/12

之类的路径

我没有改变任何东西只是为其他视图添加了相同的代码。

我的新代码:

from django.http import HttpRequest
admin_subject = "New question added"
admin_message = "A new question has been successfully added. Please review and approve it."
location = reverse("admin:appname_question_change", args=(new_question.pk,))
url = HttpRequest.build_absolute_uri(location)
admin_html_message = "<h3>%s</h3>\
                        <p>%s</p>\
                        <a href='%s'>%s</a>" % (admin_subject, admin_message, url, url)
mail_admins(admin_subject, admin_message, fail_silently=False, connection=None, html_message=admin_html_message)

仍然收到此错误:

unbound method build_absolute_uri() must be called with HttpRequest instance as first argument (got str instance instead)

1 个答案:

答案 0 :(得分:4)

Django&#39; Request has a method for that

  

<强> HttpRequest.build_absolute_uri(位置)   返回位置的绝对URI形式。如果未提供位置,则该位置将设置为request.get_full_path()。

     

如果该位置已经是绝对URI,则不会更改。否则,绝对URI是使用此请求中可用的服务器变量构建的。

     

示例:&#34; http://example.com/music/bands/the_beatles/?print=true&#34;

传递url来自reverse

更新:除其他外,Django Rest Framework提供了一个可以构建绝对URL的反向版本 - 如果您以前使用它,它将解释更改。 (你改变了什么?)