Lorsque j'ai essayé de publier un blog, une exception se produit "objet de type chaîne ou octets exceptés". J'ai beaucoup essayé mais je ne sais pas comment résoudre ce problème. Ce que je comprends, c'est que cela se produit parce que DateTimeField (default = timezone.now). J'ai bon?

Voici l’erreur que j’obtiens lors de l’écriture de py manage.py runserver:

File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python
    parsed = parse_datetime(value)
  File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime
    match = datetime_re.match(value)
TypeError: expected string or bytes-like object
[] "GET / HTTP/1.1" 500 139276
Not Found: /favicon.ico
[] "GET /favicon.ico HTTP/1.1" 404 4283

Voici models.py:-

    from django.db import models
    from django.utils import timezone
    from django.urls import reverse
    
    
    class Post(models.Model):
        author=models.ForeignKey('auth.User',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)

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

    def approve_comments(self):
        return self.comments.filter(approve_comments=True)

    def get_absolute_url(self):
        return reverse('post_detail',kwargs={'pk':self.pk})

    def __str__(self):
        return self.title


class Comment(models.Model):
    post=models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE)
    author=models.CharField(max_length=200)
    text=models.TextField()
    created_date=models.DateTimeField(default=timezone.now)
    approve_comment=models.BooleanField(default=False)

    def approve(self):
        self.approved_comment=True
        self.save()

    def get_absolute_url(self):
        return reverse('post_list')


    def __str__(self):
        return self.text

Voici views.py:-

from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.forms import PostForm,CommentForm
from blog.models import Post,Comment 
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,DetailView,
                                    CreateView,UpdateView,DeleteView)

class AboutView(TemplateView):
    template_name='about.html'

class PostListView(ListView):
    model=Post

    #generating a query to db (so this means that grab all object filtered by published
    # by date in order of decending)
    def get_queryset(self):
        return Post.objects.filter(published_date__lte=timezone.now).order_by('-published_date')

class PostDetailView(DetailView):
    model=Post

class CreatePostView(LoginRequiredMixin,CreateView):
    login_url='/login/'
    redirect_field_name='blog/post_detail.html'
    form_class=PostForm
    model=Post


class PostUpdateView(LoginRequiredMixin,UpdateView):
    login_url='/login/'
    redirect_field_name='blog/post_detail.html'
    form_class=PostForm
    model=Post


class PostDeleteView(LoginRequiredMixin,DeleteView):
    model=Post

    success_url= reverse_lazy('post_list')

class DraftListView(LoginRequiredMixin,ListView):
    login_url='/login/'
    redirect_field_name='blog/post_list.html'
    model='Post'

    def get_queryset(self):
        return Post.objects.filter(published_date__isnull=True).order_by('created_date')


@login_required
def post_publish(request,pk):
    post=get_object_or_404(Post,pk=pk)
    post.publish()
    return redirect('post_detail',pk=pk)


@login_required
def add_comment_to_post(request,pk):
    post=get_object_or_404(Post,pk=pk)

    if request.method=='POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            comment=form.save(commit=False)
            comment.post=post
            comment.save()
            return redirect('post_detail',pk=post.pk)

        else:
            form=CommentForm()

        return render(request,'blog/comment_form.html',{'form':form})


@login_required
def comment_approve(request,pk):
    comment=get_object_or_404(Comment,pk=pk)
    comment.approve()

    return redirect('post_detail',pk=comment.post.pk)

@login_required
def comment_remove(request,pk):
    comment=get_object_or_404(Comment,pk=pk)
    post_pk=comment.post.pk
    comment.delete()
    return redirect('post_detail',pk=post_pk)

Aidez-moi, s'il vous plaît!!

0
Shagun Raghav 16 févr. 2021 à 19:13

1 réponse

Meilleure réponse

Comme @unknown l'a suggéré, vous devriez changer timezone.now -> timezone.now() où est attend une valeur au lieu de callable.

models.py

class Post(models.Model):
    def publish(self):
        self.published_date = timezone.now()
        self.save()

views.py

class PostListView(ListView):
    def get_queryset(self):
        return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')

Notez que l'autre timezone.now doit rester inchangé, car le champ de modèle par défaut attend un objet appelable.

1
Kryštof Řeháček 16 févr. 2021 à 16:39