How to use django api with foreignkey2019 Community Moderator ElectionHow do I filter ForeignKey choices in a Django ModelForm?Django foreign key access in save() functionDoes Django scale?What's the difference between django OneToOneField and ForeignKey?Saving form data rewrites the same rowdifferentiate null=True, blank=True in djangoDjango foreign keys : settings.AUTH_USER_MODEL keeps giving null for form.saveDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform field

Best mythical creature to use as livestock?

Sword in the Stone story where the sword was held in place by electromagnets

Life insurance that covers only simultaneous/dual deaths

Counter-example to the existence of left Bousfield localization of combinatorial model category

Can infringement of a trademark be pursued for using a company's name in a sentence?

What has been your most complicated TikZ drawing?

Am I not good enough for you?

If Invisibility ends because the original caster casts a non-concentration spell, does Invisibility also end on other targets of the original casting?

How to make readers know that my work has used a hidden constraint?

How does Dispel Magic work against Stoneskin?

Do I need to leave some extra space available on the disk which my database log files reside, for log backup operations to successfully occur?

Deleting missing values from a dataset

Unreachable code, but reachable with exception

Can you reject a postdoc offer after the PI has paid a large sum for flights/accommodation for your visit?

Word for a person who has no opinion about whether god exists

Is having access to past exams cheating and, if yes, could it be proven just by a good grade?

Decoding assembly instructions in a Game Boy disassembler

How is the Swiss post e-voting system supposed to work, and how was it wrong?

Best approach to update all entries in a list that is paginated?

What is the definition of "Natural Selection"?

Why does Deadpool say "You're welcome, Canada," after shooting Ryan Reynolds in the end credits?

Humans have energy, but not water. What happens?

Coworker uses her breast-pump everywhere in the office

Why must traveling waves have the same amplitude to form a standing wave?



How to use django api with foreignkey



2019 Community Moderator ElectionHow do I filter ForeignKey choices in a Django ModelForm?Django foreign key access in save() functionDoes Django scale?What's the difference between django OneToOneField and ForeignKey?Saving form data rewrites the same rowdifferentiate null=True, blank=True in djangoDjango foreign keys : settings.AUTH_USER_MODEL keeps giving null for form.saveDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform field










0















I try to save foreign key in django restframework serializer.



My goal is to save in database information from iframely.com and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint



My model:



class Embed(models.Model):
url = models.URLField(max_length=255)
title = models.CharField(max_length=255)
description = models.TextField()
thumbnail_url = models.URLField(max_length=255)
html = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')


Form:



class SubmitEmbed(forms.Form):
url = forms.URLField()
board = forms.ModelChoiceField(queryset=Board.objects.all())


Serializer:



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)

class Meta:
model = Embed
fields = '__all__'


View:



def save_embed(request):

if request.method == "POST":
form = SubmitEmbed(request.POST)
if form.is_valid():
url = form.cleaned_data['url']
r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY)
json = r.json()
serializer = EmbedSerializer(data=json, context='request': request)
if serializer.is_valid():
embed = serializer.save()
return render(request, 'embed/embeds.html', 'embed': embed)
else:
form = SubmitEmbed()

return render(request, 'embed/embedadd.html', 'form': form)









share|improve this question






















  • Are you getting Board instance in your request?

    – Akhilendra
    Mar 7 at 10:11
















0















I try to save foreign key in django restframework serializer.



My goal is to save in database information from iframely.com and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint



My model:



class Embed(models.Model):
url = models.URLField(max_length=255)
title = models.CharField(max_length=255)
description = models.TextField()
thumbnail_url = models.URLField(max_length=255)
html = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')


Form:



class SubmitEmbed(forms.Form):
url = forms.URLField()
board = forms.ModelChoiceField(queryset=Board.objects.all())


Serializer:



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)

class Meta:
model = Embed
fields = '__all__'


View:



def save_embed(request):

if request.method == "POST":
form = SubmitEmbed(request.POST)
if form.is_valid():
url = form.cleaned_data['url']
r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY)
json = r.json()
serializer = EmbedSerializer(data=json, context='request': request)
if serializer.is_valid():
embed = serializer.save()
return render(request, 'embed/embeds.html', 'embed': embed)
else:
form = SubmitEmbed()

return render(request, 'embed/embedadd.html', 'form': form)









share|improve this question






















  • Are you getting Board instance in your request?

    – Akhilendra
    Mar 7 at 10:11














0












0








0








I try to save foreign key in django restframework serializer.



My goal is to save in database information from iframely.com and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint



My model:



class Embed(models.Model):
url = models.URLField(max_length=255)
title = models.CharField(max_length=255)
description = models.TextField()
thumbnail_url = models.URLField(max_length=255)
html = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')


Form:



class SubmitEmbed(forms.Form):
url = forms.URLField()
board = forms.ModelChoiceField(queryset=Board.objects.all())


Serializer:



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)

class Meta:
model = Embed
fields = '__all__'


View:



def save_embed(request):

if request.method == "POST":
form = SubmitEmbed(request.POST)
if form.is_valid():
url = form.cleaned_data['url']
r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY)
json = r.json()
serializer = EmbedSerializer(data=json, context='request': request)
if serializer.is_valid():
embed = serializer.save()
return render(request, 'embed/embeds.html', 'embed': embed)
else:
form = SubmitEmbed()

return render(request, 'embed/embedadd.html', 'form': form)









share|improve this question














I try to save foreign key in django restframework serializer.



My goal is to save in database information from iframely.com and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint



My model:



class Embed(models.Model):
url = models.URLField(max_length=255)
title = models.CharField(max_length=255)
description = models.TextField()
thumbnail_url = models.URLField(max_length=255)
html = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')


Form:



class SubmitEmbed(forms.Form):
url = forms.URLField()
board = forms.ModelChoiceField(queryset=Board.objects.all())


Serializer:



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)

class Meta:
model = Embed
fields = '__all__'


View:



def save_embed(request):

if request.method == "POST":
form = SubmitEmbed(request.POST)
if form.is_valid():
url = form.cleaned_data['url']
r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY)
json = r.json()
serializer = EmbedSerializer(data=json, context='request': request)
if serializer.is_valid():
embed = serializer.save()
return render(request, 'embed/embeds.html', 'embed': embed)
else:
form = SubmitEmbed()

return render(request, 'embed/embedadd.html', 'form': form)






django django-rest-framework django-forms django-views






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 9:49









Maciej UrmańskiMaciej Urmański

134




134












  • Are you getting Board instance in your request?

    – Akhilendra
    Mar 7 at 10:11


















  • Are you getting Board instance in your request?

    – Akhilendra
    Mar 7 at 10:11

















Are you getting Board instance in your request?

– Akhilendra
Mar 7 at 10:11






Are you getting Board instance in your request?

– Akhilendra
Mar 7 at 10:11













1 Answer
1






active

oldest

votes


















0














Its because you have



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)


You have set board to read_only. DRF will drop this field when this field is provided and DRF validation occurs.



You can remove the entire line and it will work.






share|improve this answer























  • Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

    – Maciej Urmański
    Mar 7 at 15:09










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%2f55040701%2fhow-to-use-django-api-with-foreignkey%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














Its because you have



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)


You have set board to read_only. DRF will drop this field when this field is provided and DRF validation occurs.



You can remove the entire line and it will work.






share|improve this answer























  • Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

    – Maciej Urmański
    Mar 7 at 15:09















0














Its because you have



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)


You have set board to read_only. DRF will drop this field when this field is provided and DRF validation occurs.



You can remove the entire line and it will work.






share|improve this answer























  • Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

    – Maciej Urmański
    Mar 7 at 15:09













0












0








0







Its because you have



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)


You have set board to read_only. DRF will drop this field when this field is provided and DRF validation occurs.



You can remove the entire line and it will work.






share|improve this answer













Its because you have



class EmbedSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
board = serializers.RelatedField(read_only=True)


You have set board to read_only. DRF will drop this field when this field is provided and DRF validation occurs.



You can remove the entire line and it will work.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 7 at 11:00









Giannis KatsiniGiannis Katsini

18919




18919












  • Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

    – Maciej Urmański
    Mar 7 at 15:09

















  • Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

    – Maciej Urmański
    Mar 7 at 15:09
















Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

– Maciej Urmański
Mar 7 at 15:09





Still have error: null value in column "board_id" violates not-null constraint. I don't know how to assign board list choice in Embed model. In admin work good, but on front end not. I first time try building something with django rest framework.

– Maciej Urmański
Mar 7 at 15:09



















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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55040701%2fhow-to-use-django-api-with-foreignkey%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







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

Zrinski family tree See also Navigation menu