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

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived