【问题标题】:Python: How to solve the issue : 'badly formed hexadecimal UUID string' in DjangoPython:如何解决问题:Django 中的“格式错误的十六进制 UUID 字符串”
【发布时间】:2016-11-22 10:21:52
【问题描述】:

我创建了“post”模型,其中包含“post_id”作为主键字段。当我尝试创建帖子时,它会引发错误:“格式错误的十六进制 UUID 字符串”。我将不胜感激帮助我解决这个问题。

这是我的代码。

模型.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)
    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"]

views.py:

def post_create(request):

    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        print(form.cleaned_data.get("post_id"))
        instance.user = request.user
        instance.save()
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form": form,
    }
    return render(request, "loggedin_load/post_load.html", context)

【问题讨论】:

  • 为什么要创建自定义post_id?默认情况下,Django 模型包含 idpk 字段。您可以使用其中任何一个来跟踪post_id
  • 你得到的完整错误是什么?
  • 尝试不带引号,default=uuid.uuid4
  • @Rohan 如果我要删除引号,则会引发名称错误:未定义名称'uuid'。
  • uuid是模块,你使用它的方式你只需要import uuid

标签: django django-models django-views auto-generate


【解决方案1】:

您需要导入模块并且不要在'uuid.uuid4' 周围使用引号。

应该有点像:

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"]

注意,我没有测试过上面的代码,我同意一些 cmets,你不应该为 post_id 使用 UUID。在不了解更多信息的情况下,我无法提供更多帮助。

【讨论】:

    【解决方案2】:

    我会这样做:

    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"]
    

    无论何时创建一个对象,都会自动为其分配一个 ID,该 ID 将填充您的 __unicode____str__get_absolute_url

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2016-05-29
      • 2023-01-28
      • 2015-12-03
      • 1970-01-01
      相关资源
      最近更新 更多