I'm writing my first django app from
https://docs.djangoproject.com/en/dev/intro/tutorial01/
and i'm experiencing 2 problems.
My Models.py are
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def _unicode_(self):
return self.question self.question
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.question
My First Error is when I do
python manage.py shell
from mysite.myapp.models import Poll,Choice
p = Poll(question="What Your Name",pub_date"1990-02-04")
p.save()
Poll.objects.all()
[<Poll: Poll object>, <Poll: Poll object>]
Why Doesn't it show { Poll: What's up? } instead
[<Poll: Poll object>, <Poll: Poll object>]
My second question is when i type
p = Poll.objects.get(id=1)
p.question.objects.all()
I get this errror
AttributeError: 'unicode' object has no attribute 'objects'
how do i fix it?
you must define your __unicode__ method of your model, not _unicode_.In addition, the code you given return self.question self.question is syntax invalid.
p is a poll instance, p.question is CharField not ForeignKey, has no attribute objects. p has objects, call p.objects.all() works well.
1> its __unicode__ not _unicode_
Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question, self.pub_date
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
2> objects function is a property of a document instance not a field, p.questions is a document field,
Related
I am creating a survey / voting api, I can successfully POST question but I am getting the following error Choice() got an unexpected keyword argument 'question' when I try to create a choice that is linked to a question, I can't figure it out.
These are the models
from django.db import models
import datetime
from django.utils import timezone
# Модели для опоросов
class Question(models.Model):
poll_question = models.CharField(max_length=255, blank=False)
title = models.CharField(max_length=255, blank=True)
start_date = models.DateTimeField('date published', blank=False)
def __str__(self):
return self.poll_question
def published_not_longage(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.start_date <= now
#Модель для Выбора
class Choice(models.Model):
poll_question = models.ForeignKey(Question, on_delete=models.CASCADE)
poll_question_choice = models.CharField(max_length=255)
votes = models.IntegerField(default=0)
The choices serializer
class ChoiceSerializer(serializers.Serializer):
poll_question_choice = serializers.CharField(max_length=255)
def create(self, validated_data):
return Choice.objects.create(**validated_data)
#The choices view
- The error is arising when I pass in the question instance in the serializer.save() method.
#api_view(['POST'])
def choice_details(request, pk):
question = Question.objects.get(pk=pk)
# question = get_object_or_404(Question, pk=pk)
serializer = ChoiceSerializer(data=request.data)
if serializer.is_valid():
poll_question_choice = serializer.save(question=question)
return Response(ChoiceSerializer(poll_question_choice).data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
From the model Choice, the field is named poll_question so it needs to be used (as opposed to question) in save:
poll_question_choice = serializer.save(poll_question=question)
I just started out django and python so bear with me. (Just a newbie)
I have 3 models Programme, Module and Lecture.
Programme has a variable 'code' which is a foreign key to module.
Module has in turn also a variable 'code' which is a foreign key to lecture.
In lecture I have implemented a function to get dynamic path for uploading files based on the 'code' of programme, 'code' of module and 'title' of lecture.
Here is a snippet of my models.py
from django.db import models
class Programme(models.Model):
code = models.CharField(blank=True, max_length=20, primary_key=True)
title = models.CharField(blank=True, max_length=120)
synopsis = models.TextField(blank=True)
pub_date = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
def get_programme_code(self):
return self.code
def __str__(self):
return self.title
class Module(models.Model):
code = models.CharField(blank=True, max_length=20, primary_key=True)
programme = models.ForeignKey(Programme, on_delete=models.CASCADE)
title = models.CharField(blank=True, max_length=120)
synopsis = models.TextField(blank=True)
pub_date = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
def get_module_code(self):
return self.code
def __str__(self):
return self.title
class Lecture(models.Model):
def get_upload_to(self):
return 'uploads/%s/%s/%s/%s' % (Programme().get_programme_code(),Module().get_module_code,self.title,filename)
title = models.SlugField(max_length=100)
module = models.ForeignKey(Module, on_delete=models.CASCADE)
lecture_pdf = models.FileField(upload_to=get_upload_to)
lecture_video = models.FileField(upload_to=get_upload_to)
def __str__(self):
return self.title
I know that there is something wrong with my code by the way of accessing 'code's from programme and modules but I cannot figure it out.
And here is a snippet of my unit testing of the models.
from django.test import TestCase
from module_content.models import Programme, Module, Lecture
from django.utils import timezone
from django.core.urlresolvers import reverse
class ProgrammeTest(TestCase):
def create_programme(self, code="E318", title="Computer Science", synopsis="Englobes all computer related fields"):
return Programme.objects.create(code =code, title=title, synopsis=synopsis, pub_date=timezone.now())
def test_programme_creation(self):
t = self.create_programme()
self.assertTrue(isinstance(t, Programme))
self.assertEqual(t.__str__(), t.title)
def test_get_programme_code(self):
t = self.create_programme()
self.assertEqual(t.get_programme_code(), t.code)
class ModuleTest(TestCase):
def create_module(self, code="CSE2233", title="Computer Networks", synopsis="About data transmission"):
v = ProgrammeTest().create_programme()
return Module.objects.create(code=code, programme=v, title=title, synopsis=synopsis, pub_date=timezone.now())
def test_module_creation(self):
t = self.create_module()
self.assertTrue(isinstance(t, Module))
self.assertEqual(t.__str__(), t.title)
class LectureTest(TestCase):
def create_lecture(self, title="Lecture 1"):
t = ModuleTest().create_module()
return Lecture.objects.create(title=title, module=t)
def test_lecture_creation(self):
s = self.create_lecture()
self.assertTrue(isinstance(s, Lecture))
self.assertEqual(s.__str__(), s.title)
def test_get_upload_to(self):
s = self.create_lecture()
self.assertEqual( s.get_upload_to(), 'uploads/E318/CSE2233/lecture-1')
I put the field of title for lecture to be a slugfield, so does django put it automatically as a slug ?
I tried the slugfield and it just return the title as "Lecture 1" instead of "lecture-1", or maybe I'm missing something.
So how can I access the foreign keys from the models and test it that the dynamic upload path is working properly?
I just needed to access the other models by their foreign keys such as self.module.programme.code - to retrieve the code of the programme.
I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)
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