2

This is a simple blog app I am creating. I have a model that creates an article and generates a UUID for each article created. This functions as expected.

I am now attempting to create a view variable that contains the "post_id" object from my model "Post" so that I can later insert this variable into my html template. The confusing thing is I know the Post model generates a valid UUID (at least my understand of UUIDs) as I have seen it generated so I am unclear where to start looking to resolve this issue. Other similar issues online do not seem to be related to my issue.

myapp/views.py

from django.shortcuts import render
from django.utils import timezone
from .models import Post

def blog_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    post_uid = Post.objects.get(pk="post_id")

    context = {
        "post_uid": post_uid,
        "posts": posts
            }

    return render(request, 'blog/blog_list.html', context)


def article(request, post_id):
    current_article = Post.objects.get(pk=post_id)
    return render(request, 'blog/article.html', {'current_article':current_article})

myapp/model.py

from django.db import models
from django.conf import settings
from django.utils import timezone
import uuid


class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

Errors Returned

Internal Server Error: /blog/
Traceback (most recent call last):
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2434, in to_python
    return uuid.UUID(**{input_form: value})
  File "/usr/lib/python3.8/uuid.py", line 171, in __init__
    raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/taylor/tc_site/blog/views.py", line 7, in blog_list
    post_uid = Post.objects.get(pk="post_id")
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 424, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1347, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1193, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/lookups.py", line 25, in __init__
    self.rhs = self.get_prep_lookup()
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/lookups.py", line 77, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2418, in get_prep_value
    return self.to_python(value)
  File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2436, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“post_id” is not a valid UUID.']

Also, in case it is valuable- the latest migration file from when the post_id object was added.

myapp/migrations/0002_auto_20210830_1450.py

from django.db import migrations, models
import uuid

def create_uuid(apps, schema_editor):
    Post = apps.get_model('blog', 'Post')
    for x in Post.objects.all():
        x.post_id = uuid.uuid4()
        x.save()


class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='post',
            name='id',
        ),
        migrations.AddField(
            model_name='post',
            name='post_id',
            field=models.UUIDField(blank=True, null=True),
        ),
        migrations.RunPython(create_uuid),
        migrations.AlterField(
            model_name='post',
            name='post_id',
            field=models.UUIDField(default=uuid.uuid4, unique=True)
        )
    ]

1 Answers1

1

Your query looks wrong. You used quotes around post_id

post_uid = Post.objects.get(pk="post_id")

try this instead of above without quotes:

post_uid = Post.objects.get(pk=post_id)

Also there is no post_id parameter in your blog_list method. You need to pass post_id parameter to this method.

kamilyrb
  • 2,502
  • 3
  • 10
  • 25
  • Thanks for the help! Although passing a parameter to blog_list wouldn't really make much sense with what I am trying to do. There's no way that method would call that parameter. Ultimately, I want a list of articles where the titles are hyperlinks that will take you to the article page. I was thinking of doing this by using the post_id as the variable used in a href tag in the html file associated with that method that would direct the client to the article method which does require the post_id to be passed to it. – Darceknight Sep 01 '21 at 19:26