/ skye / u'\ u201c'处的KeyError

时间:2018-09-22 21:34:56

标签: python html django database postgresql

当我在博客上发布内容如此丰富的帖子时,就会发生这种情况。

我正在使用postgresql数据库。

我想知道如何解决这个问题。

这是我的post_detail.html

<!--my post_detail.html-->
{% extends "base.html" %}
{% load urlify %}
{% load crispy_forms_tags %}


{% block head_title %}
{{ instance.title }} | {{ block.super }}
{% endblock head_title %}


  {% block post_detail_link %}
  <li><a href='{{ instance.get_absolute_url }}'>{{ instance.title }}</a></li>
  {% endblock %}



{% block content %}
<div class='col-sm-7 col-sm-offset-1'>

       <hr/>
    {% if instance.image %}
    <img  style="height:100%; width:100%" src='{{ instance.image.url }}' class='img-responsive' />
    {% endif %}
    <hr/>
    <h1><a style="color:black; font: 40px bold Tahoma">{{ title }}</a> <small style="font:5px; color: #777777;">{% if instance.draft %}<span style='color:red;'>Draft</span> {% endif %}{{ instance.publish }}</small></h1>
    {% if instance.user.get_full_name %}
    <p>Author: {{ instance.user.get_full_name }}</p>
    {% endif %}
    <p><div class="a2a_kit a2a_kit_size_32 a2a_default_style">
            <a class="a2a_dd" href="https://www.addtoany.com/share"></a>
            <a class="a2a_button_facebook"></a>
            <a class="a2a_button_twitter"></a>
            <a class="a2a_button_google_plus"></a>
            </div><br/>
            <script async src="https://static.addtoany.com/menu/page.js"></script>
        <div class="fb-like" data-href="{{ request.build_absolute_uri }}" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></div>


        <hr/>
        </p>


<!-- {% if instance.|time:"i" <= "01" %} < 1 minute {% else %}{{ instance.read_time|time:"i" }} minutes {% endif %} -->








<!-- <p>
<a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}">
Facebook
</a>

<a href="https://twitter.com/home?status={{ instance.content|truncatechars:80|urlify }}%20{{ request.build_absolute_uri }}">
Twitter
</a>

<a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'>


<a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}&title={{ instance.title }}&summary={{ share_string }}&source={{ request.build_absolute_uri }}">
Linkedin
</a>

<a href="http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&title={{ share_string }}.">Reddit</a>

</p> -->
<div class='row'>
<div class='col-sm-12'>

   <div class='post-detail-item '>{{ instance.content|safe }}</div><!--get_markdown-->

    <hr/>
    <br/>

    <div id="disqus_thread"></div>
<script>
    /**
     *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
     *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
     */
    /*
    var disqus_config = function () {
        this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };
    */
    (function() {  // REQUIRED CONFIGURATION VARIABLE: EDIT THE SHORTNAME BELOW
        var d = document, s = d.createElement('script');

        s.src = 'https://EXAMPLE.disqus.com/embed.js';  // IMPORTANT: Replace EXAMPLE with your forum shortname!

        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
    <!--div>

        <p class='lead'>Comments</p>
        {% if request.user.is_authenticated %}
        <form method="POST" action="."> {% csrf_token %}
            {{ comment_form|crispy }}
            <input type='submit' value='Post comment' class='btn btn-default'>
        </form>
        {% else %}
        <p>You must login to comment </p>
        {% endif %}
        <hr/>
        {% for comment in comments %}

        <blockquote>
          <p>{{ comment.content }}</p>
          <footer>via {{ comment.user }} | {{ comment.timestamp|timesince }} ago | {% if comment.children.count > 0 %}{{ comment.children.count }} Comment{% if comment.children.count > 1 %}s{% endif %} | {% endif %} <a class='comment-reply-btn' href='#'>Reply</a> | <a class='' href='{{ comment.get_absolute_url }}'>Thread</a></footer>
          <div class='comment-reply'>
              {% for child_comment in comment.children %}
                <blockquote>
                <p>{{ child_comment.content }}</p>
                <footer>via {{ child_comment.user }} | {{ child_comment.timestamp|timesince }} ago</footer>
                </blockquote>
             {% endfor %}
             {% if request.user.is_authenticated %}
            <form method="POST" action="."> {% csrf_token %}
                {{ comment_form|crispy }}
                <input type='hidden' name='parent_id' value='{{ comment.id }}'>
                <input type='submit' value='Reply' class='btn btn-default'>
            </form>
            {% else %}
        <p>You must login to comment </p>
        {% endif %}
        </div>

        </blockquote>

        <hr/>
        {% endfor %}
    </div-->




</div>
</div>

<div class='row'>
    <div class='col-sm-12 '>




        <!--div>

            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
            <div id="gplus-cm"></div>
            <script type="text/javascript">
              jQuery(document).ready(function($) {
                $('#gplus-cm').html('<div class="g-comments" data-width="543" data-href="http://nampnq.vietnamcode.info" data-first_party_property="BLOGGER" data-view_type="FILTERED_POSTMOD">Loading Google+ Comments ...</div>');
              });
            </script>
            <script async type="text/javascript" src="http://apis.google.com/js/plusone.js?callback=gpcb"></script>
            </div>

            </blockquote>

            <hr/>

        </div-->




    </div>
    </div>
</div>


{% endblock content %}

我该如何解决?

我的模型。py

from __future__ import unicode_literals

from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.text import slugify


from markdown_deux import markdown
from comments.models import Comment

#from .utils import get_read_time
# Create your models here.
# MVC MODEL VIEW CONTROLLER


#Post.objects.all()
#Post.objects.create(user=user, title="Some time")

class PostManager(models.Manager):
    def active(self, *args, **kwargs):
        # Post.objects.all() = super(PostManager, self).all()
        return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now())


def upload_location(instance, filename):
    #filebase, extension = filename.split(".")
    #return "%s/%s.%s" %(instance.id, instance.id, extension)
    PostModel = instance.__class__
    new_id = PostModel.objects.order_by("id").last().id + 1
    #new_id = 1
    #qs = PostModel.objects.order_by("id").exists()
    #if qs:
    #    new_id = qs.last().id + 1

    """
    instance.__class__ gets the model Post. We must use this method because the model is defined below.
    Then create a queryset ordered by the "id"s of each object,
    Then we get the last object in the queryset with `.last()`
    Which will give us the most recently created Model instance
    We add 1 to it, so we get what should be the same id as the the post we are creating.
    """
    return "%s/%s" %(new_id, filename)

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    title = models.CharField(max_length=300)
    main = models.CharField(max_length=30, default=False)
    section = models.CharField(max_length=20, default=False)
    view = models.CharField(max_length=20, default=False)
    view_second = models.CharField(max_length=25, default=False)
    slug = models.SlugField(unique=True, max_length=400)
    image = models.ImageField(upload_to=upload_location,
            null=True,
            blank=True,
            width_field="width_field",
            height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    content = models.TextField()
    draft = models.BooleanField(default=False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    #read_time = models.IntegerField(default=0)#models.TimeField(null=True, blank=True) #assume minutes models.IntegerField(default=0)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    objects = PostManager()

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

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

    def get_absolute_urllifestyle(self):
        return reverse("posts:lifestyle", kwargs={"slug": self.slug})

    def get_absolute_urlbusiness(self):
        return reverse("posts:business", kwargs={"slug": self.slug})

    def get_absolute_urlnews(self):
        return reverse("posts:news", kwargs={"slug": self.slug})

    def get_absolute_urlforex(self):
        return reverse("posts:forex", kwargs={"slug": self.slug})

    def get_absolute_urltravel(self):
        return reverse("posts:travel", kwargs={"slug": self.slug})



    def get_absolute_urlafrica(self):
        return reverse("posts:africa", kwargs={"slug": self.slug})

    def get_absolute_urltechnology(self):
        return reverse("posts:technology", kwargs={"slug": self.slug})

    def get_absolute_urlasia(self):
        return reverse("posts:asia", kwargs={"slug": self.slug})

    def get_absolute_urlamericas(self):
        return reverse("posts:americas", kwargs={"slug": self.slug})

    def get_absolute_urleurope(self):
        return reverse("posts:europe", kwargs={"slug": self.slug})

    def get_absolute_urlaustralia(self):
        return reverse("posts:australia", kwargs={"slug": self.slug})

    def get_absolute_urlfoodandhealth(self):
        return reverse("posts:foodandhealth", kwargs={"slug": self.slug})

    def get_absolute_urlearnmoney(self):
        return reverse("posts:earnmoney", kwargs={"slug": self.slug})

    def get_absolute_urllife(self):
        return reverse("posts:lifey", kwargs={"slug": self.slug})

    def get_absolute_urlus(self):
        return reverse("posts:usa", kwargs={"slug": self.slug})

    def get_absolute_urluk(self):
        return reverse("posts:uking", kwargs={"slug": self.slug})

    def get_absolute_urlmoney(self):
        return reverse("posts:money", kwargs={"slug": self.slug})

    def get_absolute_urlglobal(self):
        return reverse("posts:global", kwargs={"slug": self.slug})



    def get_absolute_urlbanking(self):
        return reverse("posts:banking", kwargs={"slug": self.slug})

    def get_absolute_urlinvestment(self):
        return reverse("posts:investment", kwargs={"slug": self.slug})

    def get_absolute_urlsports(self):
        return reverse("posts:sports", kwargs={"slug": self.slug})

    def get_absolute_urleducation(self):
        return reverse("posts:education", kwargs={"slug": self.slug})

    def get_absolute_urlentertainment(self):
        return reverse("posts:entertainment", kwargs={"slug": self.slug})


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

    def get_markdown(self):
        content = self.content
        markdown_text = markdown(content)
        return mark_safe(markdown_text)

    @property
    def comments(self):
        instance = self
        qs = Comment.objects.filter_by_instance(instance)
        return qs

    @property
    def get_content_type(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type


def create_slug(instance, new_slug=None):
    slug = slugify(instance.title)
    if new_slug is not None:
        slug = new_slug
    qs = Post.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" %(slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug


def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)

    #if instance.content:
    #    html_string = instance.get_markdown()
    #    read_time_var = get_read_time(html_string)
    #    instance.read_time = read_time_var


pre_save.connect(pre_save_post_receiver, sender=Post)

我的post_detail视图

def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    if instance.publish > timezone.now().date() or instance.draft:
        if not request.user.is_staff or not request.user.is_superuser:
            raise Http404
    share_string = quote_plus(instance.content)

    initial_data = {
            "content_type": instance.get_content_type,
            "object_id": instance.id
    }
    #queryset_list = Post.objects.active() #.order_by("-timestamp")

    if request.user.is_staff or request.user.is_superuser:
        queryset_list = Post.objects.all()
    queryset_list.filter(view__icontains="Trending"),
    form = CommentForm(request.POST or None, initial=initial_data)

    if form.is_valid() and request.user.is_authenticated():
        c_type = form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = form.cleaned_data.get('object_id')
        content_data = form.cleaned_data.get("content")
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()


        new_comment, created = Comment.objects.get_or_create(
                            user = request.user,
                            content_type= content_type,
                            object_id = obj_id,
                            content = content_data,
                            parent = parent_obj,
                        )

        return HttpResponseRedirect(new_comment.content_object.get_absolute_url())

    comments = instance.comments
    context = {
        "title": instance.title,
        "object_lista": queryset_list.filter(view__icontains="Trending"),
        "titlea": "TRENDING",
        "object_listb": queryset_list.filter(view_second__icontains="Business"),
        "object_listc": queryset_list.filter(view_second__icontains="Banking"),

        "object_listd": queryset_list.filter(view_second__icontains="Investment"),
        "object_liste": queryset_list.filter(view_second__icontains="Earn Money"),
        "object_listf": queryset_list.filter(view_second__icontains="Forex"),
        "object_listg": queryset_list.filter(view_second__icontains="Africa"),
        "object_listh": queryset_list.filter(view_second__icontains="Asia"),
        "object_listi": queryset_list.filter(view_second__icontains="Americas"),
        "object_listj": queryset_list.filter(view_second__icontains="Australia"),
        "object_listk": queryset_list.filter(view_second__icontains="Europe"),
        "object_listl": queryset_list.filter(view_second__icontains="Usa"),
        "object_listm": queryset_list.filter(view_second__icontains="UK"),
        "object_listn": queryset_list.filter(view_second__icontains="Tech"),
        "object_listo": queryset_list.filter(view_second__icontains="Sports"),
        "object_listp": queryset_list.filter(view_second__icontains="Entertainment"),
        "object_listq": queryset_list.filter(view_second__icontains="Lifestyle"),
        "object_listr": queryset_list.filter(view_second__icontains="Food And Health"),
        "object_lists": queryset_list.filter(view_second__icontains="Travel"),
        "object_listt": queryset_list.filter(view_second__icontains="Education"),
        "instance": instance,
        "share_string": share_string,
        "comments": comments,
        "comment_form":form,
    }
    return render(request, "post_detail.html", context)

我的表格.py

from django import forms

from pagedown.widgets import PagedownWidget

from .models import Post


class PostForm(forms.ModelForm):
    content = forms.CharField(widget=PagedownWidget(show_preview=False))
    publish = forms.DateField(widget=forms.SelectDateWidget)
    class Meta:
        model = Post
        fields = [
            "title",

            "main",
            "section",
            "view",
            "view_second",
            "content",
            "image",
            "draft",
            "publish",

        ]

我不知道错误是从哪里来的。如果我的内容很小,则不会出错,但是如果内容很大,或者如果包含一些html标签,则会出现关键错误。

0 个答案:

没有答案