Django:1.11.5
Python:3.5.2
Markdown 2.6.9 https://pypi.python.org/pypi/Markdown/
views.py
from django.shortcuts import render
from .models import Post
import markdown
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
Post.content = markdown.markdown(Post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
# Create your views here.
models.py
from django.db import models
import django.utils.timezone as timezone
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(blank = True, null = True)
pub_date = models.DateTimeField(default=timezone.now)
update_time = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category)
# Create your models here.
Error message
AttributeError at /
'DeferredAttribute' object has no attribute 'strip'
Request Method: GET
Request URL: http://www.balinzuoqi.com/
Django Version: 1.11.5
Exception Type: AttributeError
Exception Value:
'DeferredAttribute' object has no attribute 'strip'
Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/__init__.py in convert, line 355
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/data/mysite',
'/usr/local/bin',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-i386-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Do not know where there is a problem.
Remove Post.content = markdown.markdown (Post.content), show normal!
English is not my native language; please excuse typing errors.
You are reading content from and writing content to the Post class, not an instance of the class. You need to iterate through the list and update each instance:
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
for post in Post_list:
post.content = markdown.markdown(post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
Whether that is a recommended way of converting Markdown to HTML to pass to a template is another matter. Its been a few years since I've used Django, but that wasn't how it used to be done. However, that is a different question.
Regardless, you were not actually passing any Markdown text to the Markdown parser as you were not using an instance of the class. With the for loop I added above, the Markdown content for each 'Post' is now being passed to the Markdown parser.
Related
Im new to Django Framework and i'm taking an online course on LinkedIn Learning. I am using a newer version of python/django so I run into some syntax problems.
my python version is 3.5.4rc1.
my django version is 1.11.4
I created a model in models.py for an inventory:
class Item(models.Model):
titel = models.CharField(max_length=200)
omschrijving = models.TextField()
aantal = models.IntegerField()
This is the code in my views.py file:
from django.shortcuts import render
from django.http import Http404
from inventory.models import Item
def index(request):
items = Item.objects.exclude(aantal=0)
return render (request, 'inventory/index.html', {
'items': items,
})
return HttpResponse('<p>In index view</p>')
def item_detail(request, id):
try:
item = Item.objects.get.id=(id) #THIS ONE CAUSES PROBLEM???
except Item.DoesNotExist:
raise Http404('Dit item bestaat niet')
return render(request, 'inventory/item_detail.html', {
'item': item,
})
In the browser the localhost:8000 shows homepage as expected.
localhost:8000/item/1/ gives error:
AttributeError at /item/1/
'method' object has no attribute 'id'
Request Method: GET
Request URL: http://localhost:8000/item/1/
Django Version: 1.11.4
Exception Type: AttributeError
Exception Value:
'method' object has no attribute 'id'
Exception Location:
C:\Users\info_000\Desktop\django\mysite\inventory\views.py in item_detail, line 15
Please Help!
item = Item.objects.get(id=id)
^^^
# id = field_name of primary key in your model as string ('id' on default)
# id = your local variable 'id' from function signature
Whenever I try to run, I'm getting the following error described below. Already I researched a solution, but I can not make it work.
Exception Type: ValueError
Exception Value:
ModelForm has no model class specified.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in init, line 275
Python Executable: /usr/bin/python
Python Version: 2.7.6
Erro Traceback
File "/home/ubuntu/workspace/envelope/views.py" in cad_professor
67. form = ProfessorForm()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in init
275. raise ValueError('ModelForm has no model class specified.')
views.py
#login_required(login_url='/login/')
def cad_professor(request):
context = {}
if request.method == 'POST':
form = ProfessorForm(request.POST)
if form.is_valid():
form.save()
context['success'] = True
else:
form = ProfessorForm()
context['form'] = form
template_name = 'envelope/cad_professor.html'
return render(request,template_name , context)
forms.py
from django import forms
from .models import Professor
class ProfessorForm(forms.ModelForm):
class meta:
model = Professor
Your meta spelling is wrong. Change to:
class ProfessorForm(forms.ModelForm):
class Meta:
model = Professor
I'm stuck in the following problem: When I try to implement Autocomplete following the example in this link, modifying search_index.py as follows:
import datetime
from haystack import indexes
from myapp.models import Note
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='user')
pub_date = indexes.DateTimeField(model_attr='pub_date')
# We add this for autocomplete.
content_auto = indexes.EdgeNgramField(model_attr='content')
def get_model(self):
return Note
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return Note.objects.filter(pub_date__lte=datetime.datetime.now())
I get the following error:
Failed to add documents to Solr: [Reason: Error 400 ERROR: [doc=example.autor.1] unknown field 'content_auto'].
Of course, "content_auto" is not and attribute of the class autor, but accordingly to the Autocomplete documentation, that's needed.
I'm not sure why I'm getting the error. Here are the views and clesses
from polls.models import Word, Results
def detail(request):
q = Word(type="How do you like")
q.save()
Word.objects.get(pk=1)
q.score_set.create(score=5)
q.score_set.create(score=4)
q.score_set.create(score=3)
q.score_set.create(score=2)
q.score_set.create(score=1)
return render_to_response('/$')
Models.py
from django.db import models
class Word(models.Model):
type = models.CharField(max_length=200)
def __unicode__(self):
return self.type
class Results(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField()
def __unicode__(self):
return self.score
Error:
IntegrityError at /
polls_word.score may not be NULLRequest Method: GET
Request URL: Django Version: 1.4.1
Exception Type: IntegrityError
Exception Value: polls_word.score may not be NULL
Exception Location: /home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 337
Python Executable: /home/oveledar/.virtualenvs/django/bin/python
Python Version: 2.6.6
Python Path: ['/home/oveledar/django/mysite',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/pip-1.0.2-py2.6.egg',
'/home/oveledar/.virtualenvs/django/lib64/python26.zip',
'/home/oveledar/.virtualenvs/django/lib64/python2.6',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/plat-linux2',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-tk',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-old',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-dynload',
'/usr/lib/python2.6',
'/usr/lib64/python2.6',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages']
You table structure incorrect, you need:
class Results(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField(blank=True, null=True)
after, remove this table and run command:
python manange.py syncdb
#blank option it`s required or not this node for form validate
#null option it`s for you database (Null true or false)
Summary: The problem is that I cannot access the thumbnail image from a nested class in the serialized model and I don't know how to expose it in the JSON response.
Description: I am trying to serialize my Thing model to JSON and it works, in a fashion. I get the following in my JSON response:
// JSON response
[
{
pk: 1
model: "base.thing"
fields: {
active: true
created_at: "2011-04-13 07:18:05"
num_views: 1
file: "things/5216868239_b53b8d5e80_b.jpg"
title: "ding ding ding"
}
}
]
I just started using django-imagekit to manipulate the Thing images to thumbnail sizes and it works in normal usage, i.e. running 'thing.thumbnail_image.url' in a template returns the correct url to the thumbnail image.
The sandbox code I'm playing around with:
# base/models.py
from django.db import models
from imagekit.models import ImageModel
class Thing(ImageModel):
title = models.CharField(max_length=30)
file = models.ImageField(upload_to='things')
created_at = models.DateTimeField(auto_now_add=True)
active = models.BooleanField()
num_views = models.PositiveIntegerField(editable=False, default=0)
def __unicode__(self):
return self.title
class IKOptions:
spec_module = 'base.specs'
image_field = 'file'
save_count_as = 'num_views'
# base/views.py
from django.views.generic.base import View
from django.views.generic.list import MultipleObjectTemplateResponseMixin, ListView
from base.models import Thing
from django import http
from django.utils import simplejson as json
from utils import JsonResponse
class JSONResponseMixin(object):
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(context)
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return JsonResponse(content['thing_list']) # I can't serialize the content object by itself
class ThingsView(JSONResponseMixin, ListView):
model = Thing
context_object_name = "thing_list"
template_name = "base/thing_list.html"
def render_to_response(self, context):
if self.request.GET.get('format', 'html') == 'json':
return JSONResponseMixin.render_to_response(self, context)
else:
return ListView.render_to_response(self, context)
# base/specs.py
from imagekit.specs import ImageSpec
from imagekit import processors
class ResizeThumb(processors.Resize):
width = 100
height = 75
crop = True
class ResizeDisplay(processors.Resize):
width = 600
class EnchanceThumb(processors.Adjustment):
contrast = 1.2
sharpness = 1.1
class Thumbnail(ImageSpec):
access_as = 'thumbnail_image'
pre_cache = True
processors = [ResizeThumb, EnchanceThumb]
class Display(ImageSpec):
increment_count = True
processors = [ResizeDisplay]
# utils.py
from django.core.serializers import json, serialize
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.utils import simplejson
class JsonResponse(HttpResponse):
def __init__(self, object):
if isinstance(object, QuerySet):
content = serialize('json', object)
else:
content = simplejson.dumps(
object, indent=2, cls=json.DjangoJSONEncoder,
ensure_ascii=False)
super(JsonResponse, self).__init__(
content, content_type='application/json')
I appreciate any help with this, it's been blocking me for a day.
Best regards-
Using versions:
Django 1.3
PIL 1.1.7
django-imagekit 0.3.6
simplejson 2.1.3
I couldn't figure out how to expose the inner class over JSON so I chose an alternative way of doing it and dropping django-imagekit and manually resizing the image to a thumbnail and saving it in the model's save() function.
im = ImageOps.fit(im, (sizes['thumbnail']['width'], sizes['thumbnail']['height'],), method=Image.ANTIALIAS)
thumbname = filename + "_" + str(sizes['thumbnail']['width']) + "x" + str(sizes['thumbnail']['height']) + ".jpg"
im.save(fullpath + '/' + thumbname)
It's a less than clean approach but it works for now.
I think that you are looking for a result like <img src="{{ product.photo.url }}"/> which is loading the full path to your images like "/media/images/2013/photo_01.jpg". With JSON you have only the path which is stored in you database model.
What you can do is add some prefix in the template like <img src="media/{{ product.photo.url }}"/>.