Inserting manytomany field into db - python

I'd like to insert individual squawks into the Room object so I can insert into the database. How do I do this?
I tried, Room(squawk=squawk object), but this doesn't appear to work.
class Squawk(models.Model):
username = models.ForeignKey(User)
message = models.CharField(max_length=160)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.username) + ' - ' + self.message
class Room(models.Model):
title = models.CharField(max_length=160)
created = models.DateTimeField(auto_now_add=True)
users = models.ManyToManyField(User)
squawks = models.ManyToManyField(Squawk)
def __unicode__(self):
return self.title

from django.shortcuts import get_object_or_404
# get Room instance by id or raise 404 page if not found
room = get_object_or_404(Room,pk = id)
# add squawk to many-to-many relation
room.squawks.add(squawk_object)
https://docs.djangoproject.com/en/dev/ref/models/relations/

Related

How to Fix Cannot resolve keyword 'date_added' into field?

the BUG :
Cannot resolve keyword 'date_added' into field. Choices are: date, entry, id, owner, owner_id, text
here s My Models :
from `django`.db import models
from `django.contrib.auth`.models import User
class Topic(models.Model) :
text = models.CharField(max_length=200)
date = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.text
class Entry(models.Model) :
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
text = models.CharField(max_length=200)
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
return self.text[:50] + "..."
heres My Views functions
def topics(request) :
topics = Topic.objects.filter(owner=request.user).`order_by`('date_added')
context = {'topics':topics}
return render(request, 'learning_logs/topics.html', context)
You have to add "date_added" field to your Topic model, because order_by orders items in Topic model, but now you have only Date field.

Django Cannot Insert ForeignKey into Database : It's Error ,MultiValueDictKeyError

I try to Insert Foreign Key into the database. But When I hit the submit, I get
Error:MultiValueDictKeyError
model.py
from django.db import models
class Candidate_Military(models.Model):
"""docstring forCandidate_Military."""
auto_increment_id = models.AutoField(primary_key=True)
military_status = models.CharField(max_length=100,null=True)
military_reason = models.CharField(max_length=250,null=True)
def __int__(self):
return self.auto_increment_id
class Candidate_Basic(models.Model):
"""docstring for Candidate_basic."""
id_number = models.CharField(primary_key=True,max_length=13)
position = models.CharField(max_length=250)
salary = models.IntegerField()
profile_pic = models.ImageField()
nickname = models.CharField(max_length=100)
name_title = models.CharField(max_length=50)
firstname = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
candidate_military = models.ForeignKey(Candidate_Military, on_delete=models.CASCADE,null=True)
def __int__(self):
return self.id_number
view.py
from .models import Candidate_Basic, Candidate_Military
def index(request):
template=loader.get_template("index.html")
return HttpResponse(template.render())
def submit_applyjob(request):
print("ohh! It's sumbitted!")
military_status = request.POST.get('military_status')
military_reason = request.POST.get('military_reason')
candidate_military = Candidate_Military(military_status=military_status,military_reason=military_reason)
candidate_military.save()
id_number = request.POST["id_number"]
position = request.POST["position"]
salary = request.POST["salary"]
profile_pic = request.POST["profile_pic"]
nickname = request.POST["nickname"]
name_title = request.POST["name_title"]
firstname = request.POST["firstname"]
lastname = request.POST["lastname"]
print("candidate_military" + "-->>>" + str(candidate_military))
candidate_military = request.POST["candidate_military"]
candidate_basic = Candidate_Basic(id_number=id_number,position=position,salary=salary,
profile_pic=profile_pic,nickname=nickname,name_title=name_title,
firstname=firstname,lastname=lastname,candidate_military=candidate_military)
candidate_basic.save()
return render(request, "index.html")
And When I fill the form and hit the submit button It's Error Like This
I don't Understand Why It cannot insert into my database. I try to print the value of 'candidate_military' It's Print the right value!
Plz Help me to Debug This issue T^T
I try to fix this code with
candidate_military = request.POST.get("candidate_military",False)
But It's not Work ;
ValueError: Cannot assign "False": "Candidate_Basic.candidate_military" must be a "Candidate_Military" instance.
The issue is in this line
candidate_military = request.POST["candidate_military"]
There is no need for this line. Just remove it and the code should just work fine.

Django model foreignkey queries

So i have this two models in django:
class Course(models.Model):
def get_image_path(self, filename):
return os.path.join('courses', str(self.slug), filename)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Course, self).save(*args, **kwargs)
name = models.CharField(max_length=255, verbose_name="Nombre")
description = models.CharField(max_length=255, verbose_name="DescripciĆ³n")
price = models.DecimalField(max_digits=12,decimal_places=2, verbose_name="Precio")
slug = models.SlugField(blank=True, max_length=255)
icon_img = models.ImageField(upload_to=get_image_path, blank=True, null=True, verbose_name="Imagen")
background_color = ColorField(default="#026085")
class Meta:
verbose_name = "curso"
verbose_name_plural = "cursos"
class UserCourse(models.Model):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
So whenever a user "buys" a course, it is stored in UserCourse. I have a view where the system shows a list of all the courses the user has bought. This is the view code:
def user_course_list_view(request, username):
context_dict = {}
try:
user_courses = UserCourse.objects.filter(user=request.user).course_set
context_dict['courses'] = user_courses
context_dict['heading'] = "Mis cursos"
except:
context_dict['courses'] = None
context_dict['heading'] = "Mis cursos wey"
return render(request, 'courses/course_list.html', context=context_dict)
I dont know where is the error and I cant seem to catch the exception (im using django with docker)
tl;dr
Something like this should work.
usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
user_courses = [x.course for x in usercourse_objects]
Explanation
There are multiple ways to do this, but one way would be to first get all the UserCourse objects for the current user:
usercourse_objects = UserCourse.objects.filter(user=request.user)
Then, for each UserCourse object, get the related Course:
user_courses = [x.course for x in usercourse_objects]
Now, the second line causes N database queries (one for each time we follow the course foreign key relation. To prevent this, the first line can be changed to:
usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
This pre-populates the course attribute of the UserCourse objects. More info about select_related() can be found here.

Return multiples related models using django

class Room (models.Model):
restaurant = models.ForeignKey(Restaurant,verbose_name='Restaurant', on_delete=models.CASCADE)
room_name = models.CharField(max_length=50,verbose_name='Room Name')
def __str__(self):
return self.room_name
class Table (models.Model):
room = models.ForeignKey(Room,on_delete=models.CASCADE)
capacity = models.IntegerField()
name = models.CharField(max_length=30,verbose_name='Table Name')
def __str__(self):
return self.room.room_name + ': ' + self.name
I'm using django to build an API and I want to return these models as a JSON. The problem is that when I return a Room object the Tables are not in the JSON. How can I serialise a Room and also get the tables serialised with it.
This is how I'm serialising the Room:
rooms = Room.objects.filter(restaurant=id)
return HttpResponse(serializers.serialize("json", rooms))
The problem is that the reverse relationship is not being included.

Counting comments per object in `models.py` with Django's comments framework

I know in templates you can easily count comments with get_comment_count, but how can you get the same count as a method inside a class in models.py?
For example
class Blog( models.Model ) :
def comment_count( self ) :
return self.comment_set.count() # This line won't work.
title = ....
....
I want to have comment_count so that I can get a count the comments in the admin page.
EDIT: For your convenience, here is the models.py for django.contrib.comments
from django.contrib.auth.models import User
from django.contrib.comments.managers import CommentManager
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.conf import settings
COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000)
class BaseCommentAbstractModel(models.Model):
"""
An abstract base class that any custom comment models probably should
subclass.
"""
# Content-object field
content_type = models.ForeignKey(ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField(_('object ID'))
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
# Metadata about the comment
site = models.ForeignKey(Site)
class Meta:
abstract = True
def get_content_object_url(self):
"""
Get a URL suitable for redirecting to the content object.
"""
return urlresolvers.reverse(
"comments-url-redirect",
args=(self.content_type_id, self.object_pk)
)
class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)
# Metadata about the comment
submit_date = models.DateTimeField(_('date/time submitted'), default=None)
ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
is_public = models.BooleanField(_('is public'), default=True,
help_text=_('Uncheck this box to make the comment effectively ' \
'disappear from the site.'))
is_removed = models.BooleanField(_('is removed'), default=False,
help_text=_('Check this box if the comment is inappropriate. ' \
'A "This comment has been removed" message will ' \
'be displayed instead.'))
# Manager
objects = CommentManager()
class Meta:
db_table = "django_comments"
ordering = ('submit_date',)
permissions = [("can_moderate", "Can moderate comments")]
verbose_name = _('comment')
verbose_name_plural = _('comments')
def __unicode__(self):
return "%s: %s..." % (self.name, self.comment[:50])
def save(self, *args, **kwargs):
if self.submit_date is None:
self.submit_date = timezone.now()
super(Comment, self).save(*args, **kwargs)
def _get_userinfo(self):
"""
Get a dictionary that pulls together information about the poster
safely for both authenticated and non-authenticated comments.
This dict will have ``name``, ``email``, and ``url`` fields.
"""
if not hasattr(self, "_userinfo"):
self._userinfo = {
"name" : self.user_name,
"email" : self.user_email,
"url" : self.user_url
}
if self.user_id:
u = self.user
if u.email:
self._userinfo["email"] = u.email
# If the user has a full name, use that for the user name.
# However, a given user_name overrides the raw user.username,
# so only use that if this comment has no associated name.
if u.get_full_name():
self._userinfo["name"] = self.user.get_full_name()
elif not self.user_name:
self._userinfo["name"] = u.username
return self._userinfo
userinfo = property(_get_userinfo, doc=_get_userinfo.__doc__)
def _get_name(self):
return self.userinfo["name"]
def _set_name(self, val):
if self.user_id:
raise AttributeError(_("This comment was posted by an authenticated "\
"user and thus the name is read-only."))
self.user_name = val
name = property(_get_name, _set_name, doc="The name of the user who posted this comment")
def _get_email(self):
return self.userinfo["email"]
def _set_email(self, val):
if self.user_id:
raise AttributeError(_("This comment was posted by an authenticated "\
"user and thus the email is read-only."))
self.user_email = val
email = property(_get_email, _set_email, doc="The email of the user who posted this comment")
def _get_url(self):
return self.userinfo["url"]
def _set_url(self, val):
self.user_url = val
url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment")
def get_absolute_url(self, anchor_pattern="#c%(id)s"):
return self.get_content_object_url() + (anchor_pattern % self.__dict__)
def get_as_text(self):
"""
Return this comment as plain text. Useful for emails.
"""
d = {
'user': self.user or self.name,
'date': self.submit_date,
'comment': self.comment,
'domain': self.site.domain,
'url': self.get_absolute_url()
}
return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d
class CommentFlag(models.Model):
"""
Records a flag on a comment. This is intentionally flexible; right now, a
flag could be:
* A "removal suggestion" -- where a user suggests a comment for (potential) removal.
* A "moderator deletion" -- used when a moderator deletes a comment.
You can (ab)use this model to add other flags, if needed. However, by
design users are only allowed to flag a comment with a given flag once;
if you want rating look elsewhere.
"""
user = models.ForeignKey(User, verbose_name=_('user'), related_name="comment_flags")
comment = models.ForeignKey(Comment, verbose_name=_('comment'), related_name="flags")
flag = models.CharField(_('flag'), max_length=30, db_index=True)
flag_date = models.DateTimeField(_('date'), default=None)
# Constants for flag types
SUGGEST_REMOVAL = "removal suggestion"
MODERATOR_DELETION = "moderator deletion"
MODERATOR_APPROVAL = "moderator approval"
class Meta:
db_table = 'django_comment_flags'
unique_together = [('user', 'comment', 'flag')]
verbose_name = _('comment flag')
verbose_name_plural = _('comment flags')
def __unicode__(self):
return "%s flag of comment ID %s by %s" % \
(self.flag, self.comment_id, self.user.username)
def save(self, *args, **kwargs):
if self.flag_date is None:
self.flag_date = timezone.now()
super(CommentFlag, self).save(*args, **kwargs)
Comments are related to your Models via generic relations so you can look up the comments for your object as you would any generic relation:
from django.conrtib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Blog( models.Model ) :
def comment_count(self) :
ct = ContentType.objects.get_for_model(Blog)
obj_pk = self.id
return Comment.objects.filter(content_type=ct,object_pk=obj_pk).count()

Categories

Resources