I have the following in my models.py
import datetime
from django.utils import timezone
from django.db import models
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
but when I enter
from polls.models import Poll, Choice
Poll.objects.all()
I don't get
Poll: What's up?
but
Poll: Poll object
Any ideas?
Django 1.5 has experimental support for Python 3, but the Django 1.5 tutorial is written for Python 2.X:
This tutorial is written for Django 1.5 and Python 2.x. If the Django version doesn’t match, you can refer to the tutorial for your version of Django or update Django to the newest version. If you are using Python 3.x, be aware that your code may need to differ from what is in the tutorial and you should continue using the tutorial only if you know what you are doing with Python 3.x.
In Python 3, you should define a __str__ method instead of a __unicode__ method. There is a decorator python_2_unicode_compatible which helps you to write code which works in Python 2 and 3.
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question
For more information see the str and unicode methods section in the Porting to Python 3 docs.
Related
I currently try to figure out how to implement the following:
https://github.com/danielquinn/django-encrypted-filefield
I only want to transparently encrypt my uploaded Data for later use on e.g. S3
First Problem is that I'm not able to get
from django.contrib.auth.mixins import AuthMixin
imported. I get the following exception:
from django.contrib.auth.mixins import AuthMixin
ImportError: cannot import name 'AuthMixin'
I'm simply not able to find it. At what package is it located?
and second is that I have no idea how to implement the view if I only want encrypt and decrypt the file on the fly.
Any suggestions?
my models.py
from django.db import models
from django.utils import timezone
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
from django_encrypted_filefield.fields import EncryptedFileField
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
postattachment = EncryptedFileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
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 __str__(self):
return self.title
views.py
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'quickblog/post_detail.html', {'post': post})
Thank you :)
That mixin is not present in the django mixins. Maybe, the demo refers to a class extending any of the mixins you can find in django.
Having a look at the django sources, try with the class:
from django.contrib.auth.mixins import AccessMixin
In the view, try to show the encoded file, it must be stored already encrypted.
I got a field error when I was trying to run the tutorial of Django Part 2. I'm using Python 3.6 and Django 1.11.
models.py
import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Working with the tutorial, step by step. I was running the python manage.py shell:
>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
I got the following error after Question.objects.filter(question_text__startswith='What'):
django.core.exceptions.FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text
I don't know what to do to repair this error, maybe I put something wrong at models, that's why I share models.py with you. I hope you can help me
You should have 2 underscores before startswith.
Try
Question.objects.filter(question_text__startswith='What')
From the Django tutorial:
I've defined my models as follows:
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self): # Python 3: def __str__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self): # Python 3: def __str__(self):
return self.choice_text
Where is choice_set defined and how does this work?
>>> p = Poll.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
I don't know how deep an explanation you want, but Django defines it for you when you do poll = models.ForeignKey(Poll).
You can read here about it.
choice_set wasn't defined anywhere.
Django creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Poll object p has access to a list of all related Choice objects via the choice_set attribute: p.choice_set.all().
So choice_set. Where choice is your Choice model in lowercase and _set is kind of Django Manager Tool.
In details, you can read right here .
I'm adding a unicode() method to my model, however when displaying all objects in the interactive it's not working.
import datetime
from django.db import models
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def _unicode_(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def _unicode_(self):
return self.choice
# Create your models here.
(InteractiveConsole
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
They need to be named __unicode__ (two underscores on either side). This is an awkward detail of Python reserved methods that is not immediately obvious by looking at them.
The django docs show you how to specify a unicode method in your model:
https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#other-model-instance-methods
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
Note: These are DOUBLE underscores, where in your example you are only using single underscores.
Its a standard python special class method, as listed here
I am reading django official tutorial ( http://docs.djangoproject.com/en/dev/intro/tutorial01/ ). When i try run "python manage.py shell", python throw error:
File "D:\DjangoProjects\mysite\polls\models.py", line 8
def __unicode__(self):
^
IndentationError: unexpected indent
Help please! How solve this problem?
models.py:
import datetime
from django.db import models
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
You have a python indentation error. I'm not exactly sure where, but the django docs show this: http://docs.djangoproject.com/en/dev/intro/tutorial01/
So follow it to the letter /space.
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
Your exact indentation you've pasted wouldn't throw that error, but in your real code, you must have the def __unicode__ line at the exact indent depth as the other lines in your model.
Make sure you are using spaces and not tabs for all of your indents, as tabs can sometimes make the indent level seem the same as the others.