Django (DRF) Boolean Field missing in JSON - python

I'm writing a rather simple REST API using Django REST Framework. I am trying to add a boolean field to my model that would show if it is publicly accessible or not.
In my models.py, my model looks like this:
class BlogPost(models.Model):
title = models.CharField(max_length=20, default='', blank=False)
description = models.CharField(max_length=140, default='', blank=False)
is_public = models.BooleanField(default=True, blank=False)
Then in my serializers.py, my serializer for the model looks like this:
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = ('title', 'description', 'is_public')
However, when I create an instance of that model, and run my development server, the JSON only returns the title and the description. The is_public field is missing from the JSON.
I've searched everywhere and can't find the reason for this odd problem.
Any help would be much appreciated!

Related

Copying data from a model field to another field without losing data

I want to copy data and add it to another field without lose or corrupt data. after that delete old field and continue with new field. Im using postgresql and when i try this connection with fields to copy data i get e.300 and e.307 error as i see on internet this problem cause by wrong foreign key usage and caused by same problem.
POST MODEL
class Post(models.Model):
user = models.ForeignKey('user.CustomUser', verbose_name='Author', on_delete=models.CASCADE, related_name='posts')
title = models.CharField(max_length=120)
content = models.TextField()
image = models.ImageField(null=True, blank=True, upload_to="media/images")
publishing_date = models.DateTimeField(verbose_name='Publishing Date', auto_now_add=True)
COMMENT MODEL
class Comment(models.Model):
post = models.ForeignKey('post.Post', related_name='comments', on_delete=models.CASCADE)
name = models.CharField(max_length=200, verbose_name='Name')
# user = models.ForeignKey('self.user', related_name='comment', on_delete=models.CASCADE)
content = models.TextField(verbose_name='Comment')
created_date = models.DateTimeField(auto_now_add=True)
I'm currently trying to copy name field to user field and when makemigrate i get e.307 and e.300 errors
ERRORS:
post.Comment.user: (fields.E300) Field defines a relation with model 'self.user', which is either not installed, or is abstract.
post.Comment.user:(fields.E307) The field post.Comment.user was declared with a lazy reference to 'self.user', but app 'self' isn't installed.
Thanks for anyone who try to help.

How to display all available choices of a manytomany field in django admin using filter_horizontal

I have two models that have many to many relationship. One model consists of all possible choices and the other model can have some or all of those choices.
These are the two models:
class LanguageDomains(models.Model):
DOMAIN_CHOICES=(
('Choice1', _(u'Choice1')),
('Choice2', _(u'Choice2')),
('Choice3', _(u'Choice3')),
('Choice4', _(u'Choice4')),
)
# There is many more choices in the actual code
domains = models.CharField(max_length=255, choices=DOMAIN_CHOICES, default=None)
def __unicode__(self):
return self.domains
class Revitalization(models.Model):
code = models.ForeignKey(Codes, related_name ='revitalization')
program_name = models.CharField(max_length=255, null=True, blank=True)
year_founded = models.CharField(max_length=4, null=True, blank=True)
some_domains = models.ManyToManyField(LanguageDomains, related_name='revitalization')
def __unicode__(self):
return self.code.primary_name
My admin.py:
class RevitalizationAdmin(admin.ModelAdmin):
list_display = ('code','id')
filter_horizontal = ('language_domains',)
This is what the admin console looks like:
The question is, is there a way to populate the "Available language domains" list with all the DOMAIN_CHOICES from LanguageDomains model?
You could write a data migration that will populate the LanguageDomains model table with all the available choices.
Depending on your use-case, if the sole purpose of LanguageDomains is to present multiple choices and it's not going to be edited in runtime look into using django-multiselectfield.

Django reference a Model by foreign key or a different field

I am using Django REST Framework. I have two models, Sites and Statuses.
class Sites(models.Model):
site_id = models.AutoField(primary_key=True)
status = models.ForeignKey(Statuses, models.DO_NOTHING, blank=True, null=True)
class Statuses(models.Model):
status_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=255, blank=True, null=True, unique=True)
class Meta:
managed = True
db_table = 'Statuses'
I would like to be able to perform a GET on sites, and have the Statuses.description field returned (instead of Statuses.status_id). Also, I would like it so that either status_id or description may be used interchangeably in a POST to create a new site. Where does this type of functionality belong (serializer, models, etc...)?
I know I can accomplish the first part of my question by adding a property to the Sites model and then referencing this field in the Sites serializer.
#property
def status(self):
return self.row_status.description
However I thought the convention of a Model is that it should be a 1:1 representation of the database table. Is there a better way to do this?
This fits well in the serializer, like this:
class SitesSerializer(serializers.ModelSerializer):
description = serializers.CharField(source='status.description')
class Meta:
model = Sites
fields = ('site_id', 'description')
(But the status field should probably not have null=True set.)

Custom field not being freezed by South in Django

In my Django model I created a custom field called LocationField following this tutorial Django admin Google Maps.
Now my problem is migration using south doesnt seem to be working. It gave me an error
! Cannot freeze field 'SilverInningsHelpline.classified.location'
! (this field has class SilverInningsHelpline.widgets.LocationField)
! South cannot introspect some fields; this is probably because they are custom
! fields. If they worked in 0.6 or below, this is because we have removed the
! models parser (it often broke things).
! To fix this, read http://south.aeracode.org/wiki/MyFieldsDontWork
To fix this, I added the inspection rules as defined by the documentation of South as follows:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([
(
[Classified],
[],
{
"location": ["LocationField", {"blank": "true"}]
}
)
], ["^southut\.fields\.Classified"])
where Classified model contains the LocationField. My classified model is as follows:
class Classified(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=256)
contact_person = models.CharField(max_length=300)
email = models.CharField(max_length=100)
address = models.ForeignKey(Address)
subcategory = models.ForeignKey(Subcategory)
phone_number = models.BigIntegerField(max_length=20, default=0)
secondary_number = models.BigIntegerField(max_length=20, default=0, blank=True)
more_numbers = models.CharField(max_length=300, default='', blank=True)
image = S3DirectField(upload_to='s3direct', blank=True)
description = models.TextField(max_length=1000, blank=True)
location = LocationField(blank=True, max_length=255)
Any suggestions to fix this would be massively appreciated.
It looks like you didn't bother to read the doc.
You're passing your model class (Classified) where add_instrospection_rules expects your field class (LocationField).
The 'keyword arguments' dict is supposed to describe which keyword args your field expects, not a description of how your field is used in a given model class
The qualified field name pattern at the end should match your field's qualified name, not some random mumbo jumbo combination of what's in the tutorial and your model class name.

Retrieve Django rest framework related fields

Using the django-rest-framework is it possible to retrieve content from a related field. So for example I want to create a genre list which contains all projects within it. This is what I have but I keep on getting the error:
'Genre' object has no attribute 'project_set'
models.py
class Genre(models.Model):
name = models.CharField(max_length=100, db_index=True)
class Project(models.Model):
title = models.CharField(max_length=100, unique=True)
genres = models.ManyToManyField(Genre, related_name='genres')
serializers.py
class GenreSerializer(serializers.ModelSerializer):
project_set = serializers.ManyRelatedField()
class Meta:
model = Genre
fields = ('name', 'project_set')
The related name you're using on the Project class is badly named. That related name is how you access the set of projects related to a given genre instance. So you should be using something like related_name='projects'. (As it is you've got it the wrong way around.)
Then make sure that your serializer class matches up with the related name you're using, so in both places project_set should then instead be projects.
(Alternatively you could just remove the related_name='genres' entirely and everything will work as you were expecting, as the default related_name will be 'project_set'.)

Categories