Reputation: 9401
using Django 1.11 I'm stuck with uuid referencing in my views. I read through all similar looking questions here, but they either focus on forms or anything else.
Minimal example
It's an app called MegaTest. It's bound to /testuuid/
I have a working index view that generate links to /testuuid/<uuid>
If I click on a link on my index page, I get:
AttributeError at /testuuid/5a147a14-a9a9-4045-8e79-0ce2e8258a68/
'MegaTest' object has no attribute 'get'
models.py
class MegaTest(models.Model):
uuid = models.UUIDField(db_index=True, default=uuid.uuid4,
editable=False, unique=True)
name = models.CharField(max_length=128, blank=True, null=True)
views.py
class IndexView(generic.ListView):
template_name = 'testuuid/index.html'
context_object_name = 'test_list'
def get_queryset(self):
"""Return the last five published questions."""
return MegaTest.objects.all()
class MegaTestDetailView(generic.DetailView):
model = MegaTest
def get(self, request, uuid):
try:
megatest = MegaTest.objects.get(uuid=uuid)
return megatest
except MegaTest.DoesNotExist:
raise Http404
urls.py
app_name = 'testuuid'
urlpatterns = [
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<uuid>[\w-]+)/$', views.MegaTestDetailView.as_view(), name='detail'),
]
testuuid/index.html
{% if test_list %}
<ul>
{% for test in test_list %}
<li>
<a href="{% url 'testuuid:detail' test.uuid %}">{{ test.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No tests available.</p>
{% endif %}
I assume a damn simple mistake, but I really have no clue at this point.
The complete traceback can be found here http://dpaste.com/3JTB5NZ
Upvotes: 1
Views: 2252
Reputation: 53386
You should override get_object()
method instead of get()
.
class MegaTestDetailView(generic.DetailView):
model = MegaTest
def get_object(self):
try:
megatest = MegaTest.objects.get(uuid=self.kwargs['uuid'])
return megatest
except MegaTest.DoesNotExist:
raise Http404
You can also work with get_queryset()
or even just specify pk
field in url and don't write any method in the view class. Django will automatically query on your specified field in pk_url_kwarg
Upvotes: 1