sumanth
sumanth

Reputation: 781

Python: NoReverseMatch error: Reverse for 'detail' with arguments '(UUID)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['']in django

I have created a model 'Post' in which I use UUID rather than Django inbuilt autogenerated ID. In 'Post' model I define a def get_absolute_url so that i can keep it in my template. When i am trying to get the Deal page, it is raising an error : NoReverseMatch at /deal/ Reverse for 'detail' with arguments '(UUID('086d177f-9071-4548-b5db-1d329078853e'),)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['deal/(?P\d+)/$']. I would appreciate helping me in solve this.

Here's my code:

Models.py:

class Post(models.Model):
    post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)

    def __str__(self):
        return self.post_id

    def get_absolute_url(self):
        return reverse("detail", args=(self.post_id))

urls.py:

url(r'^deal/$', views.deal, name='deal'),
url(r'^deal/(?P<post_id>\d+)/$', views.post_detail, name='detail'),

Views.py:

def deal(request):
    queryset_list = Post.objects.active() #.order_by("-timestamp")
    if request.user.is_staff or request.user.is_superuser:
        queryset_list = Post.objects.all()
    context = {
        "object_list": queryset_list, 
        "post_id": "List",
    }
    return render(request, 'before_login/deal.html', context)

def post_detail(request, post_id=None):  
    instance = get_object_or_404(Post, post_id=post_id)
    if instance.date > timezone.now().date():
        if not request.user.is_staff or not request.user.is_superuser:
            raise Http404
    share_string = quote_plus(instance.Material_Type)
    context = {
        "from1": instance.from1,
        "instance": instance,
        "share_string": share_string
    }
    return render(request, "loggedin_load/post_detail.html", context)

deal.html:

{% for obj in object_list %}
    <tr>
      <td scope="row">{{obj.post_id}}</td>
      <td> <a href='{{ obj.get_absolute_url }}'>{{ obj.from1 }}</a><br/></td>
      <td>{{obj.user}}</td>
    </tr>
{% endfor %}

Upvotes: 0

Views: 4543

Answers (2)

Mark Filley
Mark Filley

Reputation: 173

For UUID, here is the regular expression

url(r'^deal/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.post_detail, name='detail'),

Upvotes: 0

knbk
knbk

Reputation: 53669

Your UUID contains letters and hyphens, but your regex only matches numbers (\d+). You need to change your regex to capture letters and hyphens:

url(r'^deal/(?P<post_id>[\w-]+)/$', views.post_detail, name='detail'),

Upvotes: 5

Related Questions