How to add and update data into foreign key field in django model












0














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__'









share|improve this question
























  • 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 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


















0














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__'









share|improve this question
























  • 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 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
















0












0








0







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__'









share|improve this question















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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, 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




















  • 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 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


















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














1 Answer
1






active

oldest

votes


















0














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__'





share|improve this answer





















    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
    });


    }
    });














    draft saved

    draft discarded


















    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









    0














    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__'





    share|improve this answer


























      0














      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__'





      share|improve this answer
























        0












        0








        0






        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__'





        share|improve this answer












        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__'






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 15:39









        Daniel RosemanDaniel Roseman

        444k41576632




        444k41576632






























            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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