I started using Django REST this week, and I am running into something I do not understand.
I building a POST that takes in the following payload:
{
"requestor":"naughtron",
"test_name":"testName",
"workers":"2"
}
The value for requestor in our data model is set to CurrentUserField()
When the payload comes into the serializer
class TestSuiteRequestSerializer(serializers.Serializer):
requestor = what_do_use_here?
test_name = serializers.CharField(required=True, allow_blank=False, max_length=100)
workers = serializers.CharField(required=True, allow_blank=True, max_length=3)
the following error is thrown
database_1 | ERROR: null value in column "requestor" violates not-null constraint
because I am believe it is not being serialized properly therefore the model has no idea what to do.
I looked through the documentation and the current list of Serializer fields. Nothing seems to be helping.
I tried using a basic serializers.CharField but that threw an error stating must be a "User" instance.
Related
I am creating an application in Django REST Fremework, in which the user can add an order.
I would like the serializer to set a reference to the user based on the token and complete the "Client" model field.
It's actually works with HiddenField, as shown in the documentation.
(Link: https://www.django-rest-framework.org/api-guide/fields/#hiddenfield)
class OrderSerializer(serializers.ModelSerializer):
client = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = Order
fields = '__all__'
The problem is that when I fetch a single order or list of orders, Client field is of course hidden becouse of HiddenField type.
curl -X GET http://127.0.0.1:8000/api/orders/12
{
"id":12,
"name":"sprzatanie ogrodka",
"description":"dupa",
"price":"12.20",
"work_time_hours":2,
"work_time_minutes":50,
"workers_needed_num":3,
"coords_latitude":"-1.300000",
"coords_longitude":"1.100000",
"created_at":"2020-03-08T13:20:16.455289Z",
"finished_at":null,
"category":1,
"workers":[]
}
I would like the field to still capture reference to the logged in user, but at the same time to be visible when returning data from the API.
What serializers field type I need to use?
Thanks!
Going through the documentation i found: https://www.django-rest-framework.org/api-guide/validators/
Using a standard field with read_only=True, but that also includes a default=… argument. This field will be used in the serializer output representation, but cannot be set directly by the user.
this is what you need i think.
So whatever field type you have set in Model can be used with read_only=True
For example:
client = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
Hope this helps
I have a field in my model which is required in the resource body while creating the resource (POST) and is not passed in the request body(will be passed along with URL) while updating the resource (PUT).
I have created my marshmallow model:
class DummySchema():
field_1 = fields.Str(required=True)
field_2 = fields.Id()
If I leave field_1 to required=True, I get the following error on PUT :
{
"message": {
"field_1": [
"Missing data for required field."
]
}
}
I could leave it required in the model, but that would mean it would cause a problem in POST request.
Is there a way I could set the field as optional, but set it required for my POST request so that I can perform my validation?
I think I should've read the documentation thoroughly before :(
I could set a field as partial, so when it'll do validation marshmallow would skip the field
data, errors = DummySchema().load({'field_2': 42}, partial=('field_1',))
REF: https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#validation
If you want to use it for /POST request then this field can be added in dump_only list.
This can also be used for /PUT request.
class StrategySchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Strategy
sqla_session = db.session
ordered = True
load_instance = True
dump_only = ( # read-only
"id",
"created_by",
"created_by_id",
"created_at",
"updated_at",
)
dump_only means:
Consider these fields only while dumping a model to json (deserialization)
ignore it while loading a model from json
read-only fields in other words
When trying to save the data in the DB I have this error:
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
models.py
class Movie(Model):
title = CharField(max_length=255)
omdb = JSONField()
slug = SlugField(max_length=255, unique=True, allow_unicode=True)
views.py
omdb_data = get_movie(title) # returns response.json() from external API call
print(type(omdb_data['Title'])) # str
print(type(omdb_data)) # dict
movie = Movie(title=omdb_data['Title'],
omdb=omdb_data, slug=slugify(title))
movie.save() # crashing here
What could be wrong? I'm guess it's problem with title or omdb parameters (not sure if ID counts or not) but no idea whats wrong.
SQLite doesn't support all types data. It's in its name (Lite). You may try to convert to PostgreSQL or another complete database solution. Here is a tutorial for Django+Postgres but be careful, it's little bit outdated.
I'm trying to create a custom error message for unique_together:
class Recipient(models.Model):
mobile = PhoneNumberField()
mobile2 = PhoneNumberField()
class Meta:
unique_together = (("mobile", "mobile2"),)
def unique_error_message(self, model_class, unique_check):
print("I don't seem to run")
if model_class == type(self) and unique_check == ('mobile', 'mobile2'):
return 'My custom error message'
else:
return super(Recipient, self).unique_error_message(model_class, unique_check)
However my error message is not running instead I get:
Duplicate entry '+4473192817212-+4478192817210' for key 'mobile'\"
why?
The error message you pasted seems more like an error caused by a unique constraint on the mobile field of the recipient table, indicating that at one point you had unique=True at one point. Check for this constraint in the database or if this is just in development, delete the database and syncdb again.
I'm a bit of a newbie in Python, so go easy on me. I'm writing an AJAX handler in Django. Everything's been pretty straight-forward on this until now. I've been banging my head against this bit for the better part of a day. I'd like to return a JSON string that contains a dict that contains a queryset:
#
# models.py
#
class Project(models.Model):
unique_name = models.CharField(max_length=32, unique=True)
title = models.CharField(max_length=255, blank=True)
description = models.TextField('project description', blank=True)
project_date = models.DateField('Project completion date')
published = models.BooleanField()
class ProjectImage(models.Model):
project = models.ForeignKey('Project', related_name='images')
image = models.ImageField(upload_to=get_image_path)
title = models.CharField(max_length=255)
sort_metric = models.IntegerField()
#
# views.py
#
...
projects = Project.Project.objects.filter(published=True)
...
response_dict({
'success' : True,
'maxGroups' : 5, # the result of some analysis on the projects queryset
'projects' : projects
});
# This one works if I remove 'projects' from the dict
# response = json.dumps( response_dict )
# This one works only on projects
# response = serializers.serialize( 'json', response_dict, relations=('images') )
return HttpResponse( response, mimetype='application/javascript' )
I've commented out the two serialization lines, because:
The first one seems to only work with 'simple' dicts and since projects is included in my dict, it fails with [<Project: Project object>] is not JSON serializable
The second one seems to only work with querysets/models and since the 'outer' part of my dict is non-model, it complains that 'str' object has no attribute '_meta'. Note that I am using the wadofstuff serializer with the understanding that it would resolve the OneToMany relationship as defined in my model. But even when I get this working by only serializing projects, I do not have any of my ProjectImages in the output.
QUESTION 1: What is the best way to serialize the whole response_dict? Surely, I'm not the first person to want to do this, right?
QUESTION 2: Why am I unable to get the ManyToOne relationship to work?
Many thanks for your help.
UPDATE: Just found this one: Django JSON Serialization with Mixed Django models and a Dictionary and it looked promising, but I get 'QuerySet' object has no attribute '_meta' =(
You can't serialize a python object like that. There is a section in the django documentation on what to do.
https://docs.djangoproject.com/en/dev/topics/serialization/#id2
Here is the key part to look at:
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)