Python: How to solve the issue : 'badly formed hexadecimal UUID string' in Django

这一生的挚爱 提交于 2019-12-02 03:31:39

You need to import the module and not use quotes around 'uuid.uuid4'.

It should be somewhat like:

import uuid  # The uuid module
class Post(models.Model):

    post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)  # using the function uuid4 on the module
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    To = models.CharField(max_length=20)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    objects = PostManager()

    def __unicode__(self):
        return self.post_id

    def __str__(self):
        return self.post_id

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"post_id": self.post_id})

    class Meta:
        ordering = ["-timestamp", "-Time"]

N.B I've not tested the above code, and I agree with some of the comments you shouldn't need a UUID for the post_id. Without knowing more I couldn't help further.

I would do something like this:

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Post(models.Model):
    # Instead of default, maybe do null=True to take old entries into account?
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    # You may want to reconsider the naming of the "To" field
    # to avoid capital letters and built-in functions
    To = models.CharField(max_length=20)
    timestamp = models.DateTimeField(auto_now_add=True)

    objects = PostManager()

    # You can remove this with the decorator above
    # def __unicode__(self):
        # return self.id

    def __str__(self):
        return self.id  # acts as your post_id

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"post_id": self.id})

    class Meta:
        ordering = ["-timestamp", "-Time"]

Whenever an object is created, it will automatically be assigned an id, which will populate your __unicode__, __str__, and get_absolute_url.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!