MU
Maciej UrmańskiMarch 7, 2019, 5:01 a.m.
Django rest framework and foreignkey
Hi,
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
Maybe here someone help me.
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})
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.Do you like it? Share on social networks!
d
- dsfs
- April 26, 2024, 11:56 a.m.
C ++ - Test 004. Pointers, Arrays and Loops
- Result:80points,
- Rating points4
d
- dsfs
- April 26, 2024, 11:35 a.m.
C++ - Test 001. The first program and data types
- Result:73points,
- Rating points1
Last comments
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий КононенкоFeb. 5, 2024, 9:50 a.m.
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
DA
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел ДорофеевApril 14, 2024, 9:35 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
Hi,
You need to add default value, or set up this field like null=True, and blank=True
or