How to add and update data into foreign key field in django model
I have two models which is related to a forignkey.
class BikeModel(models.Model):
City = models.ForeignKey(CityForBike, on_delete=models.CASCADE)
BikeModels = models.CharField(default='', max_length=50)
Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png')
class Meta:
verbose_name_plural = 'BikeModels'
def __str__(self):
return self.BikeModels
class CityForBike(models.Model):
CityForCars = models.CharField(default="",max_length=50)
class Meta:
verbose_name_plural = 'CityForBikes'
def __str__(self):
return self.CityForCars
and i want to insert data to BikeModel. but it gives me error.
AssertionError: You cannot call `.save()` on a serializer with invalid data.
I want to know how to insert data to forign key field.
if request.method == 'POST':
import pdb;
pdb.set_trace()
input_data = json.loads(request.read().decode('utf-8'))
print(input_data)
serializer = serializers.BikeModelSerializer(data=input_data)
if serializer.is_valid():
serializer.save()
return render(request, "bike_model_add.html", {'car_city': car_city}, status=200)
And this is the data i am sending.
{'City': 'testo', 'BikeModels': 'ds'}
this is my serializers
class CityForBikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.CityForBike
fields = '__all__'
class BikeModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.BikeModel
fields = '__all__'
django python-3.x django-models
add a comment |
I have two models which is related to a forignkey.
class BikeModel(models.Model):
City = models.ForeignKey(CityForBike, on_delete=models.CASCADE)
BikeModels = models.CharField(default='', max_length=50)
Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png')
class Meta:
verbose_name_plural = 'BikeModels'
def __str__(self):
return self.BikeModels
class CityForBike(models.Model):
CityForCars = models.CharField(default="",max_length=50)
class Meta:
verbose_name_plural = 'CityForBikes'
def __str__(self):
return self.CityForCars
and i want to insert data to BikeModel. but it gives me error.
AssertionError: You cannot call `.save()` on a serializer with invalid data.
I want to know how to insert data to forign key field.
if request.method == 'POST':
import pdb;
pdb.set_trace()
input_data = json.loads(request.read().decode('utf-8'))
print(input_data)
serializer = serializers.BikeModelSerializer(data=input_data)
if serializer.is_valid():
serializer.save()
return render(request, "bike_model_add.html", {'car_city': car_city}, status=200)
And this is the data i am sending.
{'City': 'testo', 'BikeModels': 'ds'}
this is my serializers
class CityForBikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.CityForBike
fields = '__all__'
class BikeModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.BikeModel
fields = '__all__'
django python-3.x django-models
You need to show BikeModelSerializer.
– Daniel Roseman
Nov 20 '18 at 13:35
above are my BikeModelSerializer.
– Nitesh Kumar
Nov 20 '18 at 14:24
This is tagged as django, butModelSerializeris not a django class: docs.djangoproject.com/en/2.1/search/?q=ModelSerializer This look like django-rest-framework. Also, json should be like{'City': 3, 'BikeModels': 'ds'}
– dani herrera
Nov 20 '18 at 15:13
add a comment |
I have two models which is related to a forignkey.
class BikeModel(models.Model):
City = models.ForeignKey(CityForBike, on_delete=models.CASCADE)
BikeModels = models.CharField(default='', max_length=50)
Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png')
class Meta:
verbose_name_plural = 'BikeModels'
def __str__(self):
return self.BikeModels
class CityForBike(models.Model):
CityForCars = models.CharField(default="",max_length=50)
class Meta:
verbose_name_plural = 'CityForBikes'
def __str__(self):
return self.CityForCars
and i want to insert data to BikeModel. but it gives me error.
AssertionError: You cannot call `.save()` on a serializer with invalid data.
I want to know how to insert data to forign key field.
if request.method == 'POST':
import pdb;
pdb.set_trace()
input_data = json.loads(request.read().decode('utf-8'))
print(input_data)
serializer = serializers.BikeModelSerializer(data=input_data)
if serializer.is_valid():
serializer.save()
return render(request, "bike_model_add.html", {'car_city': car_city}, status=200)
And this is the data i am sending.
{'City': 'testo', 'BikeModels': 'ds'}
this is my serializers
class CityForBikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.CityForBike
fields = '__all__'
class BikeModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.BikeModel
fields = '__all__'
django python-3.x django-models
I have two models which is related to a forignkey.
class BikeModel(models.Model):
City = models.ForeignKey(CityForBike, on_delete=models.CASCADE)
BikeModels = models.CharField(default='', max_length=50)
Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png')
class Meta:
verbose_name_plural = 'BikeModels'
def __str__(self):
return self.BikeModels
class CityForBike(models.Model):
CityForCars = models.CharField(default="",max_length=50)
class Meta:
verbose_name_plural = 'CityForBikes'
def __str__(self):
return self.CityForCars
and i want to insert data to BikeModel. but it gives me error.
AssertionError: You cannot call `.save()` on a serializer with invalid data.
I want to know how to insert data to forign key field.
if request.method == 'POST':
import pdb;
pdb.set_trace()
input_data = json.loads(request.read().decode('utf-8'))
print(input_data)
serializer = serializers.BikeModelSerializer(data=input_data)
if serializer.is_valid():
serializer.save()
return render(request, "bike_model_add.html", {'car_city': car_city}, status=200)
And this is the data i am sending.
{'City': 'testo', 'BikeModels': 'ds'}
this is my serializers
class CityForBikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.CityForBike
fields = '__all__'
class BikeModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.BikeModel
fields = '__all__'
django python-3.x django-models
django python-3.x django-models
edited Nov 20 '18 at 15:09
Cartucho
2,05111842
2,05111842
asked Nov 20 '18 at 13:30
Nitesh KumarNitesh Kumar
235
235
You need to show BikeModelSerializer.
– Daniel Roseman
Nov 20 '18 at 13:35
above are my BikeModelSerializer.
– Nitesh Kumar
Nov 20 '18 at 14:24
This is tagged as django, butModelSerializeris not a django class: docs.djangoproject.com/en/2.1/search/?q=ModelSerializer This look like django-rest-framework. Also, json should be like{'City': 3, 'BikeModels': 'ds'}
– dani herrera
Nov 20 '18 at 15:13
add a comment |
You need to show BikeModelSerializer.
– Daniel Roseman
Nov 20 '18 at 13:35
above are my BikeModelSerializer.
– Nitesh Kumar
Nov 20 '18 at 14:24
This is tagged as django, butModelSerializeris not a django class: docs.djangoproject.com/en/2.1/search/?q=ModelSerializer This look like django-rest-framework. Also, json should be like{'City': 3, 'BikeModels': 'ds'}
– dani herrera
Nov 20 '18 at 15:13
You need to show BikeModelSerializer.
– Daniel Roseman
Nov 20 '18 at 13:35
You need to show BikeModelSerializer.
– Daniel Roseman
Nov 20 '18 at 13:35
above are my BikeModelSerializer.
– Nitesh Kumar
Nov 20 '18 at 14:24
above are my BikeModelSerializer.
– Nitesh Kumar
Nov 20 '18 at 14:24
This is tagged as django, but
ModelSerializer is not a django class: docs.djangoproject.com/en/2.1/search/?q=ModelSerializer This look like django-rest-framework. Also, json should be like {'City': 3, 'BikeModels': 'ds'}– dani herrera
Nov 20 '18 at 15:13
This is tagged as django, but
ModelSerializer is not a django class: docs.djangoproject.com/en/2.1/search/?q=ModelSerializer This look like django-rest-framework. Also, json should be like {'City': 3, 'BikeModels': 'ds'}– dani herrera
Nov 20 '18 at 15:13
add a comment |
1 Answer
1
active
oldest
votes
If you want to identify cities by their name in the bike serializer, you need to use SlugRelatedField.
class BikeModelSerializer(serializers.ModelSerializer):
City = serializers.SlugRelatedField(slug_field='CityForCars')
class Meta:
model = models.BikeModel
fields = '__all__'
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394112%2fhow-to-add-and-update-data-into-foreign-key-field-in-django-model%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you want to identify cities by their name in the bike serializer, you need to use SlugRelatedField.
class BikeModelSerializer(serializers.ModelSerializer):
City = serializers.SlugRelatedField(slug_field='CityForCars')
class Meta:
model = models.BikeModel
fields = '__all__'
add a comment |
If you want to identify cities by their name in the bike serializer, you need to use SlugRelatedField.
class BikeModelSerializer(serializers.ModelSerializer):
City = serializers.SlugRelatedField(slug_field='CityForCars')
class Meta:
model = models.BikeModel
fields = '__all__'
add a comment |
If you want to identify cities by their name in the bike serializer, you need to use SlugRelatedField.
class BikeModelSerializer(serializers.ModelSerializer):
City = serializers.SlugRelatedField(slug_field='CityForCars')
class Meta:
model = models.BikeModel
fields = '__all__'
If you want to identify cities by their name in the bike serializer, you need to use SlugRelatedField.
class BikeModelSerializer(serializers.ModelSerializer):
City = serializers.SlugRelatedField(slug_field='CityForCars')
class Meta:
model = models.BikeModel
fields = '__all__'
answered Nov 20 '18 at 15:39
Daniel RosemanDaniel Roseman
444k41576632
444k41576632
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394112%2fhow-to-add-and-update-data-into-foreign-key-field-in-django-model%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You need to show BikeModelSerializer.
– Daniel Roseman
Nov 20 '18 at 13:35
above are my BikeModelSerializer.
– Nitesh Kumar
Nov 20 '18 at 14:24
This is tagged as django, but
ModelSerializeris not a django class: docs.djangoproject.com/en/2.1/search/?q=ModelSerializer This look like django-rest-framework. Also, json should be like{'City': 3, 'BikeModels': 'ds'}– dani herrera
Nov 20 '18 at 15:13