Django 控制器方法中的时区错误

问题描述 投票:0回答:1

我的 Django 项目中有以下控制器方法:

def blog_detail(request, pk):

    post = Post.objects.get(pk=pk)

    conn = psycopg.connect(
        host="localhost",
        dbname="myproject2",
        user="postgres",
        password=""
    )

    from django.db import connections
    connections['default'].connection = conn

    form = comment_form()
    if request.method == 'POST':
        form = comment_form(request.POST)
        if form.is_valid():
            comment = Comments(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comments.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form
    }
    return render(request, "blog_detail.html", context)

当我加载与此控制器关联的视图时,我得到:

“.../base.py”,第 336 行,create_cursor 中 如果 self.timezone != tzloader.timezone: AttributeError:类型对象“TimestamptzLoader”没有属性“timezone”

模型看起来像:

class Category(models.Model):
    name = models.CharField(max_length=20)

class Post(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comments(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

我的设置文件有:

TIME_ZONE = 'UTC'
USE_TZ = True

我的 postgresql.conf 文件将时区设置为欧洲/伦敦,所以我将其设置为 UTC,但我得到了同样的错误。

django postgresql psycopg2
1个回答
0
投票

我在控制器中使用以下代码解决了这个问题:

from django.db.backends.postgresql.psycopg_any import register_tzloader 
register_tzloader("UTC", conn)
© www.soinside.com 2019 - 2024. All rights reserved.