Anil Sharma
Anil Sharma

Reputation: 65

Reverse url not showing the full url in django

This is my code

#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)

I was using this to send in a mail. Before I was getting full URL in my mail. Like http://192.168.1.0:8000/admin/appname/answer/12

But now it is only giving the path like /admin/appname/answer/12

I haven't altered anything just added the same code for other views.

My new code:

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)

Still getting this error:

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

Upvotes: 0

Views: 1083

Answers (1)

Carlton Gibson
Carlton Gibson

Reputation: 7386

Django's Request has a method for that:

HttpRequest.build_absolute_uri(location) Returns the absolute URI form of location. If no location is provided, the location will be set to request.get_full_path().

If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request.

Example: "http://example.com/music/bands/the_beatles/?print=true"

Pass in the url you get from reverse

Update: Amongst others, Django Rest Framework provides a version of reverse that can build an absolute URL - if you were previously using that it would explain the change. (What did you alter?)

Upvotes: 4

Related Questions