Search code examples
pythondjangouuid

How to generate UUID paths in views.py in Django?


I would like to create an object in views.py with an ID using UUID and then enter its specific path directly from the views file where I have create it. The error that I get is:

TypeError at /item/create_item _reverse_with_prefix() argument after * must be an iterable, not UUID

So I wonder whether anyone knows a way how this could be done?

models.py:

class Item(models.Model):
    id = models.UUIDField(
        primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100, blank=True)

views.py

def create_item(request):

    context = {}

    if request.method == 'POST':
        name = request.POST['name']

        item = Item(name=name)
        item.save()

        return HttpResponsePermanentRedirect(reverse('item', args=(item.id)))

    return render(request, 'items/item.html', context)


def item(request, pk):
    item = get_object_or_404(Item, pk=pk)
    
    #Code to be written


Solution

  • You should wrap the item.id in a singleton tuple, by using (…,):

    return HttpResponsePermanentRedirect(reverse('item', args=(item.id,)))

    You can however make use of the redirect(…) function [Django-doc] which is basically wrapping the result of a reverse(…) in a HttpResponseRedirect(…), but this offers an interface with positional and named parameters instead:

    from django.shortcuts import redirect
    
    return redirect('item', pk=item.id, permanent=True)