本文介绍了Python:如何解决问题:Django中的“格式错误的十六进制UUID字符串”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了 post模型,其中将 post_id作为主键字段。当我尝试创建帖子时,它会引发一个错误:格式错误的UUID字符串。我希望能帮助我解决这个问题。
I have created 'post' model in which I included 'post_id' as the primary key field. When I am trying to create a post, it is raising an error: 'badly formed hexadecimal UUID string'. I would appreciate helping me in solve this.
这是我的代码。
Models.py:
Models.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)
推荐答案
您需要导入模块,并且不要在'uuid.uuid4'
周围使用引号。
You need to import the module and not use quotes around '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"]
NB我尚未测试以上代码,并且我同意一些您不需要UUID的注释用于post_id。不知道更多我无能为力。
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.
这篇关于Python:如何解决问题:Django中的“格式错误的十六进制UUID字符串”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!